Rust Web APIs — Building REST APIs with Axum, SQLx, and Validated Input
DodaTech
Updated 2026-06-28
1 min read
In this tutorial, you will learn about Rust Web APIs. We cover key concepts, practical examples, and best practices to help you master this topic.
Rust web APIs combine Axum for routing, SQLx for database access, and serde for JSON with validation and OpenAPI documentation.
What You'll Learn
- Axum request handlers
- SQLx database queries
- Request validation
- OpenAPI docs
Why It Matters
Rust APIs are fast and type-safe. DodaZIP uses Axum for its REST API.
Real-World Use
High-performance APIs, data services, Microservices.
[dependencies]
axum = "0.7"
tokio = { version = "1", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
sqlx = { version = "0.7", features = ["runtime-tokio", "postgres"] }
tower-http = { version = "0.5", features = ["cors"] }
use axum::{
extract::{Path, Query, State},
http::StatusCode,
response::IntoResponse,
routing::get,
Json, Router,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use sqlx::PgPool;
#[derive(Serialize, Deserialize)]
struct User {
id: i32,
name: String,
email: String,
}
#[derive(Deserialize)]
struct CreateUser {
name: String,
email: String,
}
async fn list_users(State(pool): State<Arc<PgPool>>) -> impl IntoResponse {
let users = sqlx::query_as::<_, User>("SELECT * FROM users")
.fetch_all(&*pool).await;
Json(users.unwrap_or_default())
}
async fn create_user(
State(pool): State<Arc<PgPool>>,
Json(input): Json<CreateUser>,
) -> impl IntoResponse {
let user = sqlx::query_as::<_, User>(
"INSERT INTO users (name, email) VALUES ($1, $2) RETURNING *"
)
.bind(&input.name)
.bind(&input.email)
.fetch_one(&*pool).await;
match user {
Ok(u) => (StatusCode::CREATED, Json(u)).into_response(),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
}
}
← Previous
Rust Testing Advanced — Integration Tests, Benchmarks, Property-Based Testing, and Mocking
Next →
Rust Ecosystem — Community, Frameworks, and Tools for Rust Development
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro