Rust Hello World Web Service

I always wanted to learn about writing web services in Rust. I know a bit about Java servlets and the Spring framework for Java. But how to start in Rust?

As Rust is strong in systems programming, it has good support for networking and some frameworks to help you with writing applications and services for the web. I prefer to start at the HTTP level so I do not need to fumble with TCP/IP protocol things. Something similar to Java servlets would be nice to get started.

While reading an article about asynchronous programming in Rust (in German), I stumbled across Tokio, an asynchronous runtime. At first, it looked as if it would be a good starting point. But after trying the hello world example, I realized that it is a bit too low level for me. My knowledge of Rust is not yet good enough for this. However, there are other, more high-level libraries to choose from. Next, I had a look at Warp and Rocket.

The following is the hello world example for Warp right from their documentation.

use warp::Filter;

#[tokio::main]
async fn main() {
    // GET /hello/warp => 200 OK with body "Hello, warp!"
    let hello = warp::path!("hello" / String)
        .map(|name| format!("Hello, {}!", name));

    warp::serve(hello)
        .run(([127, 0, 0, 1], 3030))
        .await;
}

This looks simple enough for me to understand. 😀 I could setup this example and run it in my local Rust development environment without problems. After I got that working, I had a look at the hello world example for Rocket. Again, this is straight from their website, just to get an impression.

#[macro_use] extern crate rocket;

#[get("/hello/<name>/<age>")]
fn hello(name: &str, age: u8) -> String {
    format!("Hello, {} year old named {}!", age, name)
}

#[launch]
fn rocket() -> _ {
    rocket::build().mount("/", routes![hello])
}

This as well looks good to me. What I like about Rocket is that they have first-class support for JSON and a testing library as well.

I haven’t decided yet, whether to start with Warp or Rocket. I’ll go, study their documentation and try some example code to get a better feeling for them.

Comment