Rust HTTP Server with Axum
Build a type-safe HTTP server in Rust using Axum with extractors, JSON responses, error handling, and state sharing. Includes route definitions, middleware.
Code
use axum::{
extract::State,
http::StatusCode,
response::Json,
routing::get,
Router,
};
use serde_json::{json, Value};
use std::sync::Arc;
struct AppState {
db: String,
}
async fn health() -> &'static str {
"OK"
}
async fn get_data(State(state): State<Arc<AppState>>) -> Result<Json<Value>, StatusCode> {
Ok(Json(json!({"db": state.db, "data": []})))
}
#[tokio::main]
async fn main() {
let state = Arc::new(AppState { db: "postgres".into() });
let app = Router::new()
.route("/health", get(health))
.route("/api/data", get(get_data))
.with_state(state);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}What the code does
Rust HTTP Server with Axum reduces to the functions health, get_data and main.
Fallible operations return Result, forcing the caller to handle both arms explicitly.
Caveats
- Plan for an install step:
axum::andserde_json::are a real dependency, resolved by the package manager. - Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Applying it
The main signature reads fn health() -> &'static str
Statements that matter
async fn get_data(State(state): State<Arc<AppState>>) -> Result<Json<Value>, StatusCode> {
Ok(Json(json!({"db": state.db, "data": []})))
}
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
Interactive Tools for This Topic
Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.Set-Cookie ParserParse one or more Set-Cookie header values into the cookie name, value, and attributes like Path, Domain, Expires, Max-Age, Secure, HttpOnly, and SameSite.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.
FAQ
- What is the error handling style?
- Through `Result` values. Nothing panics inside the snippet; the caller decides how to handle each failure.
- What does this need from the package registry?
- These are real dependencies: `axum::` and `serde_json::`. Without them the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.