Building Web API's With Rust 1

When you start building stuff with Rust, you notice that applications are made of small, specialized libraries.

The product I want to build is a web application, just a regular one, will receive HTTP requests, respond accordingly and it might call other HTTP services.

To start, I’m using hyper, a very lightweight HTTP server. It leverages the library tokio and futures for async capabilities. I recommend reading tokio’s documentation to understand more how the async part works with rust.

What I currently have (sort of hello word)

My tests should perform a call to the root url “/” and another to an unkown url. This is just to make sure it compiles and runs.

Cargo.toml

1
2
3
4
5
6
7
8
9
[dependencies]
hyper = "0.12"
futures = "0.1"
pretty_env_logger = "0.3"
log = "0.4"

[dev-dependencies]
speculate = "0.1"
reqwest = "0.9" 

main.rs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
use hyper::service_fn;
use hyper::{Body, Method, Request, Response, Server, StatusCode};
use futures::{future, Future};

use std::env;

extern crate pretty_env_logger;
#[macro_use] extern crate log;

type InternalServerError = Box<dyn std::Error + Send + Sync>;
type BoxedResponseFuture = Box<dyn Future<Item = Response<Body>, Error = InternalServerError> + Send>;

fn main() {
    env::set_var("RUST_LOG", "app=debug");
    env::set_var("RUST_BACKTRACE", "1");
    pretty_env_logger::init();

    let addr = "0.0.0.0:3000".parse().unwrap();

    let new_service = || service_fn(move |req| router(req));

    let server = Server::bind(&addr)
        .serve(new_service)
        .map_err(|e| eprintln!("server error: {}", e));

    info!("Listening on http://{}", addr);
    hyper::run(server);
}

fn router(req: Request<Body>) -> BoxedResponseFuture {
    info!("INFO {:?}", req);

    match (req.method(), req.uri().path()) {
        (&Method::GET, "/") => index(),
        _ => handle_404(),
    }
}

fn handle_404() -> BoxedResponseFuture {
    Box::new(future::ok(
        Response::builder()
            .status(StatusCode::NOT_FOUND)
            .body(Body::empty())
            .unwrap(),
    ))
}

fn index() -> BoxedResponseFuture {
    Box::new(future::ok(
        Response::builder()
            .status(StatusCode::OK)
            .body(Body::empty())
            .unwrap(),
    ))
}

#[cfg(test)]
mod tests {
    extern crate speculate;
    extern crate reqwest as request;    
    
    use hyper::StatusCode;
    use speculate::speculate;    
    use std::thread;
    use std::Once;

    use super::main;

    static SETUP: Once = Once::new();    

    speculate! {      
        before {
            SETUP.call_once(|| {
                let _main_server = thread::spawn(main);
            });
        }

        describe "main server routes" {
            it "calls the root path and returns 200" {
                let resp = request::get("http://0.0.0.0:3000").unwrap();
                assert!(resp.status().is_success());
            }

            it "calls an inexistent route and returns 404" {
                let resp = request::get("http://0.0.0.0:3000/notfound").unwrap();
                assert!(resp.status().is_client_error());
                assert_eq!(resp.status(), StatusCode::NOT_FOUND);
            }
        }
    }
}


So far, is not doing anything except returning an empty body for the root path “/” and 404 for everything else, but you can already see the libraries ecosystem.

running 2 tests
 INFO  app > Listening on http://0.0.0.0:3000
 INFO  app > INFO Request { method: GET, uri: /, version: HTTP/1.1, headers: {"user-agent": "reqwest/0.9.22", "accept": "*/*", "accept-encoding": "gzip", "host": "0.0.0.0:3000"}, body: Body(Empty) }
 INFO  app > INFO Request { method: GET, uri: /notfound, version: HTTP/1.1, headers: {"user-agent": "reqwest/0.9.22", "accept": "*/*", "accept-encoding": "gzip", "host": "0.0.0.0:3000"}, body: Body(Empty) }
test tests::test_calls_an_inexistent_route_and_returns_404 ... ok
test tests::test_calls_the_root_path_and_returns_200 ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

The libraries pretty_env_logger and log are for logging purposes.
The library speculate helps structuring my tests.
The library reqwest provides a high level API for making HTTP requests.

Next, I need to figure out how to properly set up routes for the app.

Note on running tests: I managed to bootstrap the server only once on tests using the struct Once. Otherwise every test would try to spawn a thread with the server (they still do, but Once prevents it)