DEV Community

Cover image for πŸ¦€βš‘ Building extremely fast APIs with Rust & snowboard: Step-by-Step
Brian3647
Brian3647

Posted on

πŸ¦€βš‘ Building extremely fast APIs with Rust & snowboard: Step-by-Step

Today we'll be writing a working web API using rust and snowboard, an extremely simple HTTP library.

Contents

  1. Setting up the server
  2. Creating the routes
  3. Wrapping up

Prerequisites

You'll need to have rust installed for this project.

1. Setting up the server

First off, we'll create the project (that will be named "faster") and install snowboard:

$ cargo new faster
$ cd faster
$ cargo add snowboard@0.4.1
Enter fullscreen mode Exit fullscreen mode

Then, we will add the following code to src/main.rs:

use snowboard::{response, Server};

fn main() {
    Server::new("localhost:3000").run(|req| {
        println!("Request: {:?}", req);

        response!(ok, "Hello, world!")
    });
}
Enter fullscreen mode Exit fullscreen mode

and run it using cargo run. And that's it! You got yourself a working server on localhost:3000. Now, to the API functionality

2. Creating the routes

Instead of using that closure, we'll be writing our app router in a new function called router and adding some routes:

use snowboard::{response, Request, Response, Server};

fn router(req: Request) -> Response {
    let path = req.parse_url();

    match path.at(0) {
        Some("hello") => match path.at(1) {
            Some(name) => response!(ok, format!("Hello, {}!", name)),
            None => response!(ok, "Hello, World!"),
        },
        None => response!(
            ok,
            "Send a request to /hello to get a greeting!"
        ),
        _ => response!(not_found, "πŸ‘€"),
    }
}

fn main() {
    Server::new("localhost:3000").run(router);
}
Enter fullscreen mode Exit fullscreen mode

In this code, we're doing a lot of things:

  • We're checking for the first part of the path (url/this). If the request is just /, that'll be None where we return an ok response (point 5).
  • If it matches and it's "/hello" we check for the second part of the path (url/hello/this). If it exists, we get it and say hello to them. If it doesn't, we just return "Hello, world!".

And it works perfectly! You can check it out for yourself on your terminal using curl:

$ curl localhost:3000/
Send a request to /hello to get a greeting!
$ curl localhost:3000/hello
Hello, World!
$ curl localhost:3000/hello/Joe
Hello, Joe!
$ curl localhost:3000/thisroutedoesntexist
πŸ‘€
Enter fullscreen mode Exit fullscreen mode

3. Wrapping up

That's it for today! You got yourself an extremely fast & simple API written in Rust. You can check out snowboard here on contact me in discord @ Brian3647.

If needed, snowboard also supports async/await routes, so feel free to expand your API however you want to.

Top comments (0)