Creating an asynchronous API server in Rust

Creating an asynchronous API server in Rust

Photo by Ilya Pavlov on Unsplash

Unlike other Rust programs, asynchronous applications require runtime support. In particular, the following runtime services are necessary:

  • An I/O event loop, called the driver, which drives I/O resources and dispatches I/O events to tasks that depend on them.

  • A scheduler to execute tasks that use these I/O resources.

  • A timer for scheduling work to run after a set period of time.

This is where Tokio comes in. It provides these functionalities together without much configuration required from the user's side.

Creating a Async web server

Here, I'm planning to use the following dependencies:

[dependencies]
tokio = { version = "1", features = ["full"] }
warp = "0.3"

where tokio will be used to provide a runtime for async execution of code and warp will be used to create the API endpoint.

I've kept the code very simple in order not to over-complicate things. The API will take a single argument from the URL itself and just append the ": added suffix" string to it before returning it to the caller.

use warp::Filter;

// Tells rust to use the tokio runtime.
#[tokio::main]
async fn main() {
    // Creates endpoint info which accepts an argument from the URL itself.
    let api = warp::path!("info" / String)
        .map(|name| {
            let summary = get_info(name);
            return summary
        });

    // Starting the server on port 3030.
    warp::serve(api)
        .run(([127, 0, 0, 1], 3030))
        .await;
}

// Simple adds a suffix
fn get_info(keyword: String) -> String{
    let mut res = String::from(keyword);
    res.push_str(" : added suffix");

    return res;
}

Explanation in comments inline. If you haven't seen the syntax similar to #[tokio::main] before, you can read usethesource.hashnode.dev/what-are-rusts-at.. to learn more about Rust attributes and their usage.

This API can be called by going to the following endpoint from a browser:

http://localhost:3030/info/input
----------------------------------------------
Output:
input : added suffix