Today we'll be writing a working web API using rust and snowboard, an extremely simple HTTP library.
Contents
- Setting up the server
- Creating the routes
- 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
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!")
});
}
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);
}
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 beNone
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
π
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)