Rust Axum API

An Axum todo API exposes health, runtime, list, and create routes from a compact Rust project. Tokay builds the source and serves it at a live URL as one Web Service.

Last updated

AI agent? Start with llms.txt.

This example deploys a Tokio and Axum Service from the same Cargo files used locally. Tokay builds the Cargo project in release mode, supplies PORT, and starts the Axum server.

Runtime
Rust
Framework
Axum
Service types
Web Service
Resources
None
Required secrets
None

What it does

Open the root route and the API identifies itself as the Rust service.

Request /todos for the three sample tasks. Post a title to add another item. A blank title receives a validation error and leaves the list unchanged.

The /health route gives monitors a small JSON response.

Deploy it

Bring this folder to Tokay any way you like. Hand it to your AI assistant, drag the unzipped folder in under Add code, or push it with Git. Tokay figures out the rest.

Haven't connected your assistant yet? Set it up once, then ask it to deploy this example. Agents can use Tokay MCP at https://mcp.tokay.io/mcp or the Tokay API, and our agent instructions cover both.

New to Tokay? The getting started guide walks you through your first deploy.

Try it

Send one write to your deployed API, then read the collection back.

export APP_URL="https://your-app.tokay.app"
curl -X POST "$APP_URL/todos" \
  -H 'Content-Type: application/json' \
  -d '{"title":"ship the next thing"}'
curl "$APP_URL/todos"

The list now contains your title. A later deployment starts from the samples again, which makes the boundary between process memory and durable storage easy to see.

How it works

You only bring the Cargo project. Tokay compiles the release, supplies PORT, and starts the Axum listener while your Tokio and Serde code is unchanged.

Secrets

The service needs no secrets. All four routes are available without an outside account.

Grow from here

Browse the Tokay examples catalog when you want saved data or a Background Worker.

src/main.rs Raw

use std::{env, sync::Arc};

use axum::{
    Json, Router,
    extract::State,
    http::StatusCode,
    routing::get,
};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use tokio::{net::TcpListener, sync::Mutex};

#[derive(Clone, Serialize)]
struct Todo {
    id: usize,
    title: String,
}

#[derive(Deserialize)]
struct TodoInput {
    title: String,
}

type Todos = Arc<Mutex<Vec<Todo>>>;

async fn hello() -> Json<Value> {
    Json(json!({
        "message": "Hello from Axum",
        "runtime": "Rust",
    }))
}

async fn health() -> Json<Value> {
    Json(json!({ "ok": true }))
}

async fn list_todos(State(todos): State<Todos>) -> Json<Vec<Todo>> {
    Json(todos.lock().await.clone())
}

async fn create_todo(
    State(todos): State<Todos>,
    Json(input): Json<TodoInput>,
) -> Result<(StatusCode, Json<Todo>), (StatusCode, Json<Value>)> {
    let title = input.title.trim();
    if title.is_empty() {
        return Err((
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "title is required" })),
        ));
    }

    let mut todos = todos.lock().await;
    let todo = Todo {
        id: todos.last().map_or(1, |item| item.id + 1),
        title: title.to_owned(),
    };
    todos.push(todo.clone());
    Ok((StatusCode::CREATED, Json(todo)))
}

#[tokio::main]
async fn main() {
    let todos = Arc::new(Mutex::new(vec![
        Todo { id: 1, title: "deploy this ✓".into() },
        Todo { id: 2, title: "add a database".into() },
        Todo { id: 3, title: "tell a friend".into() },
    ]));

    let app = Router::new()
        .route("/", get(hello))
        .route("/health", get(health))
        .route("/todos", get(list_todos).post(create_todo))
        .with_state(todos);

    let port = env::var("PORT").unwrap_or_else(|_| "3000".to_owned());
    let listener = TcpListener::bind(format!("0.0.0.0:{port}"))
        .await
        .expect("bind listener");
    println!("Axum API listening on port {port}");
    axum::serve(listener, app).await.expect("serve API");
}

Cargo.toml Raw

[package]
name = "tokay-rust-axum-api"
version = "1.0.0"
edition = "2024"
rust-version = "1.95"

[dependencies]
axum = "0.8.8"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tokio = { version = "1.49", features = ["macros", "rt-multi-thread", "net"] }

Built from revision 259b82f

Guide: Deploy a Rust app