How to build a REST API with Axum

Build a REST API in Rust by adding axum and tokio dependencies, defining route handlers, and running the server with axum::serve.

Use the axum crate with tokio to define routes and run an async server. Add dependencies to Cargo.toml, define a handler function, and start the server with axum::serve.

use axum::{routing::get, Router};

#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(handler));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

async fn handler() -> &'static str {
    "Hello, World!"
}

In Cargo.toml, add:

[dependencies]
axum = "0.7"
tokio = { version = "1", features = ["full"] }