Skip to content
Go back

Building Web API's With Rust 1

Published:  at  06:06 PM

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

[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

use hyper::service::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::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::rt::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::sync::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::speculate_0::main_server_routes::test_calls_an_inexistent_route_and_returns_404 ... ok
test tests::speculate_0::main_server_routes::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)



Previous Post
Don't break it
Next Post
Having My Own Blog Platform