Weekly Rust Trivia is a problem-oriented series of articles that assist developers while learning Rust. Every article solves simple, everyday development tasks using the Rust standard library or leveraging popular and proven crates.

Question: How to implement the builder pattern in Rust?

To create an HTTP API with Actix, we must add the actix-web crate to our project. We can add it using cargo add:

# Add actix-web as dependency
cargo add actix-web

Having the crate added to our project, we can move on and use Actix to implement our HTTP API. First, we will implement two handlers, responsible for constructing HTTP responses. actix-web provides macros like post, get, … with which we can decrate our handler functions to describe how Actix should expose them via HTTP:

use actix_web::{get, post, HttpResponse, Responder};

#[post("/parrot")]
async fn parrot(request_body: String) -> impl Responder {
    HttpResponse::Ok().body(request_body)
}

#[get("/healthz/readiness")]
async fn is_ready() -> impl Responder {
    HttpResponse::Ok()
}

Having the handlers in place, we can take care of creating and spawning the HTTP server itself. To do so, we must decorate our main function with the actix_web::main macro and make it async first:

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    Ok()
}

Now we have to configure our HTTP server using the HttpServer struct and register our handlers using App struct, which is also provided by actix-web:

use actix_web::{HttpServer, App};

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .service(parrot)
            .service(is_ready)
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}