How to Build a REST API with Actix-Web in Rust

Initialize a Rust project, add actix-web, define a handler, and run the server to build a REST API.

Create a new Rust project, add the actix-web dependency, and define a handler function to return a response.

  1. Initialize a new project and navigate into it. cargo new my_api && cd my_api

  2. Add the actix-web crate to your Cargo.toml dependencies. cargo add actix-web

  3. Write the server code in src/main.rs using actix_web::App and actix_web::HttpServer. `cat > src/main.rs << 'EOF' use actix_web::{web, App, HttpResponse, HttpServer, Responder};

async fn hello() -> impl Responder { HttpResponse::Ok().body("Hello world!") }

#[actix_web::main] async fn main() -> std::io::Result<()> { HttpServer::new(|| { App::new().route("/", web::get().to(hello)) }) .bind("127.0.0.1:8080")? .run() .await } EOF`

  1. Run the server to start listening on port 8080. cargo run