Create a new Rust project, add the actix-web dependency, and define a handler function to return a response.
-
Initialize a new project and navigate into it.
cargo new my_api && cd my_api -
Add the
actix-webcrate to yourCargo.tomldependencies.cargo add actix-web -
Write the server code in
src/main.rsusingactix_web::Appandactix_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`
- Run the server to start listening on port 8080.
cargo run