APPECODE
APPECODE

How to Build a Lightning-Fast API in Rust Using Axum

Learn how to build a fast API in Rust using Axum. This Rust tutorial covers setup, endpoints, async routing, request handling and high-performance API design.

Development Tutorial Details

Software: Rust

Difficulty Level: Normal

Tags: AxumRust

Created: May 05, 2025

Created By: Team APPECODE

Partner With APPECODE! Let’s Work Together!

Let APPECODE implement your vision and take your project from idea to done.

How to Build a Lightning-Fast API in Rust Using Axum

This hands-on development tutorial teaches you how to unlock the power of Rust for web development by building a fast, secure API using the Axum framework. This tutorial walks you through the complete process — from setting up your Rust environment to deploying a production-ready API. Ideal for developers looking to combine safety and performance in their backend services.

Let’s begin.

Tutorial Information

This tutorial assumes you already have an applicable development environment set up.

This tutorial walks you through the process of creating a RUST API. This tutorial is ideal for developers looking to combine safety and performance in their backend services. This tutorial will help you unlock the power of Rust for web development by building a fast, secure API using the Axum framework. 

What Is Axum and Why Use It?

Axum is a modern web framework built in and for Rust. It’s designed for high-performance, type-safe web services, and is powered by Tokio and Hyper under the hood. Axum is a great fit for developers who want low-level control without giving up readability or safety. You’ll use Axum to define routes, handle requests, and return responses in a clean and efficient way.

Prerequisites

  • Install Rust from rustup.rs
  • Basic understanding of HTTP requests and Rust syntax
  • Terminal access to run commands and edit files
  • Optional: Postman or curl to test your API endpoints

Step 1: Set Up a New Rust Project

Open your terminal and type the following command to create a new Rust project directory named rust_axum_api:
cargo new rust_axum_api
cd rust_axum_api
This creates a new folder with a default Rust setup including a Cargo.toml file and a src/main.rs source file.

Step 2: Add Dependencies

Open the Cargo.toml file in a code editor. Under the [dependencies] section, paste the following dependencies:
[dependencies]
axum = "0.7"
tokio = { version = "1", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["fmt", "env-filter"] }
This tells Cargo (Rust’s package manager) to fetch and compile these libraries so you can use them in your project.

Step 3: Build a Basic GET Endpoint

Open the src/main.rs file and replace its contents with the following code:
use axum::{ routing::get, Json, Router };
use serde::Serialize;
use std::net::SocketAddr;
use tracing_subscriber;

#[derive(Serialize)]
struct User {
    id: u32,
    name: String,
}

async fn get_user() -> Json<User> {
    let user = User { id: 1, name: "Jane Doe".to_string() };
    Json(user)
}

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt::init();
    let app = Router::new().route("/user", get(get_user));
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    println!("API running at http://{}", addr);
    axum::Server::bind(&addr)
        .serve(app.into_make_service())
        .await
        .unwrap();
}
This creates a simple API endpoint at /user that returns a JSON object with an id and name. You defined a data structure, created a route, and started an HTTP server on port 3000.

Step 4: Test the API

Back in your terminal, run the following command to start your API server:
cargo run
In another terminal window, test your GET endpoint using:
curl http://localhost:3000/user
You should see a JSON response: {"id":1,"name":"Jane Doe"}

Step 5: Add a POST Endpoint

Add the following code below your existing functions in main.rs:
use axum::extract::Json as ExtractJson;
use axum::routing::post;
use serde::{Deserialize, Serialize};

#[derive(Deserialize)]
struct CreateUser {
    name: String,
}

async fn create_user(ExtractJson(payload): ExtractJson<CreateUser>) -> Json<User> {
    let user = User {
        id: 2,
        name: payload.name,
    };
    Json(user)
}
Then update your router definition inside main() to handle POST requests:
let app = Router::new()
    .route("/user", get(get_user).post(create_user));
This lets your server accept POST requests with JSON bodies and respond with a new user object.

Step 6: Add a Health Check

Still inside main.rs, add the following function at the bottom to create a basic health check:
use axum::response::Html;

async fn health_check() -> Html<&'static str> {
    Html("<h1>Healthy</h1>")
}
Update your router to include:
.route("/health", get(health_check))
This provides a simple HTML response that you can use to check if the server is running.

Step 7: Add Logging

Axum uses the tracing crate for async-friendly logging. Add this inside your get_user function to log each request:
use tracing::info;

async fn get_user() -> Json<User> {
    info!("GET /user called");
    ...
}
You’ll now see messages in your terminal each time a request is received.

Step 8: Production Considerations

To prepare your project for production, consider the following improvements:
  • Build with optimizations: cargo build --release
  • Deploy with Docker, systemd, or a cloud platform
  • Add middleware for authentication and rate limiting
  • Use an actual database like PostgreSQL with sqlx or diesel

Conclusion

This tutorial guided you through building a small but complete API using Rust and Axum. You now understand how to define routes, handle GET and POST requests, return JSON, log activity, and prepare for deployment. This foundation allows you to scale your API to real-world applications with authentication, databases, and more complex business logic.

Team APPECODE

This concludes this APPECODE development tutorial. Thanks for coding with us today. You now have the tools and techniques to apply the demonstrated skills in real development scenarios. Whether you’re refining a feature or launching something big, APPECODE is here to guide your technical journey every step of the way. Team APPECODE is all about helping devs like you grow with real-world, hands-on examples. Have questions or project ideas? Let’s keep the conversation going—your next big breakthrough could be one line away.

x

At APPECODE, our mission is to revolutionize the way software is designed, developed, and delivered. We empower businesses to innovate, streamline processes, and achieve their goals through cutting-edge technology and custom software solutions. With a relentless focus on quality, creativity, and collaboration, we aim to transform ideas into scalable, user-centric applications that drive real-world impact.

Whether it’s building powerful tools, enhancing user experiences, or pushing the boundaries of what’s possible in software development, APPECODE is committed to excellence, innovation, and delivering value every step of the way. Partner with us and allow us to implement your vision —seamlessly, intelligently, beautifully and on time!

Ready to implement your vision?