This guide will walk you through creating a simple REST API using Rust and the Axum framework. The API will have two endpoints:
GET /api/getUserData
: Retrieves user data from theusers
table based on the provideduser_id
parameter.POST /api/updateUser
: Updates user data in theusers
table based on the provideduser_id
,fullname
, andemail
parameters.
Prerequisites:
- Rust installed
- Basic understanding of Rust programming
- Familiarity with REST API concepts
Steps:
- Create a Rust project:
cargo new axum_api
- Install Axum and dependencies:
cargo add axum axum-server --version ^0.10
- Define data models: Create a
models.rs
file to define the data structures for users:
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct User {
user_id: i32,
fullname: String,
email: String,
}
- Implement database access (using PostgreSQL as an example):
// Add `sqlx` and `postgres` dependencies to `Cargo.toml`
cargo add sqlx postgres
// Create a `db.rs` file for database operations
use sqlx::{Connection, Pool};
use crate::models::User;
pub async fn get_user_data(pool: &Pool<Postgres>, user_id: i32) -> Option<User> {
sqlx::query_as!(User, "SELECT * FROM users WHERE user_id = $1", user_id)
.fetch_optional(pool)
.await
.unwrap()
}
pub async fn update_user(pool: &Pool<Postgres>, user: User) {
sqlx::query!("UPDATE users SET fullname = $1, email = $2 WHERE user_id = $3", user.fullname, user.email, user.user_id)
.execute(pool)
.await
.unwrap();
}
- Create route handlers: Create a
routes.rs
file to define the API routes and handlers:
use axum::{
extract::Query,
handler::{get, post},
Json,
};
use crate::{db::*, models::User};
#[get("/api/getUserData")]
pub async fn get_user_data_handler(Query(user_id): Query<i32>, pool: Extension<Pool<Postgres>>) -> Json<Option<User>> {
let user = get_user_data(&pool, user_id).await;
Json(user)
}
#[post("/api/updateUser")]
pub async fn update_user_handler(Json(user): Json<User>, pool: Extension<Pool<Postgres>>) {
update_user(&pool, user).await;
Json(user)
}
- Register routes and start the server: Create a
main.rs
file to register routes and start the server:
use axum::{
Extension,
Server,
service::{
create_router,
http_router,
middleware::CorsConfig,
TypedBody,
},
};
use crate::routes::*;
pub async fn run_server() {
let pool = Pool::connect("postgres://user:password@localhost:5432/db")
.await
.unwrap();
let app = http_router(
[
get_user_data_handler,
update_user_handler,
],
Extension(pool),
)
.with_middleware(Cors::new().allow_origin("*"));
let addr = std::net::SocketAddr::from_str("0.0.0.0:8080").unwrap();
println!("Starting server on {}", addr);
Server::bind_and_run(addr, app).await.unwrap();
}
- Run the API:
cargo run
The API will be running on http://localhost:8080
. You can test the endpoints using tools like Postman or curl
Leave a Reply