Let’s add more routes to handle different paths and HTTP methods:
use axum::{routing::{get, post}, http::StatusCode, Json, Router};use serde::{Deserialize, Serialize};#[tokio::main]async fn main() { // Initialize tracing tracing_subscriber::fmt::init(); // Build our application with multiple routes let app = Router::new() .route("/", get(root)) .route("/users", post(create_user)); // Run it let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); tracing::debug!("listening on {}", listener.local_addr().unwrap()); axum::serve(listener, app).await;}// Basic handler that responds with a static stringasync fn root() -> &'static str { "Hello, World!"}async fn create_user( // This argument tells axum to parse the request body // as JSON into a `CreateUser` type Json(payload): Json<CreateUser>,) -> (StatusCode, Json<User>) { // Insert your application logic here let user = User { id: 1337, username: payload.username, }; // This will be converted into a JSON response // with a status code of `201 Created` (StatusCode::CREATED, Json(user))}// The input to our `create_user` handler#[derive(Deserialize)]struct CreateUser { username: String,}// The output to our `create_user` handler#[derive(Serialize)]struct User { id: u64, username: String,}
Add serde = { version = "1.0", features = ["derive"] } and tracing-subscriber = "0.3" to your dependencies to run this example.
use axum::{ routing::{get, post}, http::StatusCode, Json, Router,};use serde::{Deserialize, Serialize};#[tokio::main]async fn main() { // Initialize tracing tracing_subscriber::fmt::init(); // Build our application with a route let app = Router::new() // `GET /` goes to `root` .route("/", get(root)) // `POST /users` goes to `create_user` .route("/users", post(create_user)); // Run our app with hyper let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); tracing::debug!("listening on {}", listener.local_addr().unwrap()); axum::serve(listener, app).await;}// Basic handler that responds with a static stringasync fn root() -> &'static str { "Hello, World!"}async fn create_user( // This argument tells axum to parse the request body // as JSON into a `CreateUser` type Json(payload): Json<CreateUser>,) -> (StatusCode, Json<User>) { // Insert your application logic here let user = User { id: 1337, username: payload.username, }; // This will be converted into a JSON response // with a status code of `201 Created` (StatusCode::CREATED, Json(user))}// The input to our `create_user` handler#[derive(Deserialize)]struct CreateUser { username: String,}// The output to our `create_user` handler#[derive(Serialize)]struct User { id: u64, username: String,}