Skip to content

Rest API with Swagger UIλ︎

Create an API service that provides a documented and interactive API using Open API.

Axum is the web framework, supported by Tokio async runtime and Serde for JSON serialisation.

Background references

What is a runtime in Rust

How to implement an async main function

NOTE: other web frameworks include Rocket, Warp, Actix

Create projectλ︎

Create a basic project using the Cargo tool.

cargo new hello-world --bin
Project configuration file
[package]
name = "hello-world"
version = "0.1.0"
edition = "2024"

[dependencies]

Dependenciesλ︎

Add library dependencies for Axium and other useful libraries

Cargo.toml
[dependencies]
axum = "0.8"
tokio = { version = "1.22.0", features = ["full"] }
serde = { version = "1.0.149", features = ["derive"] }

Updating Crates

LSP / Rustaceannvim will automatically detect newer versions of creates available.

SPC l a to select the "Update creates" code action. Or select "Update all creates" action if there are multiple creates with newer versions.

Create a web serverλ︎

Use the Rust standard library to define IP address for the web server and manage errors.

Use axum to define a router and routes to handle requests.

Edit the src/main.rs and replace the existing code

use std::{error::Error, net::SocketAddr};

use axum::{
    routing::get,
    Router,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let addr = SocketAddr::from(([127, 0, 0, 1], 8000));

    let app = Router::new().route("/", get(|| async { "Hello, Axum" }));

    println!("listening on {}", addr);

    axum::Server::bind(&addr)
        .serve(app.into_make_service())
        .await
        .unwrap();

    Ok(())
}

Run and test web serverλ︎

Start the Rust project in watch mode, so changes are automatically updated on save.

Install Bacon

cargo install --locked bacon

NOTE: bacon has a long list of crate library dependencies... downloading the internet!

cargo run
Bacon is the new cargo watch

Cargo-watch is no longer maintained, recommends bacon the background code checker instead.