Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

API Hello World

Return a simple JSON with a fixed string.

We create a struct to represent the data and use the serde-based Json serializer of axum to serialized the data and to set the content-type to application/json.

[package]
name = "api-calculator"
version = "0.1.0"
edition = "2024"

[dependencies]
axum = "0.8.8"
serde = { version = "1.0.228", features = ["derive"] }
tokio = { version = "1.50.0", features = ["full"] }

[dev-dependencies]
headers = "0.4.1"
http-body-util = "0.1.3"
serde_json = "1.0"
tower = { version = "0.5.3", features = ["util"] }

Code

use axum::{Router, response::Json, routing::get};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct Message {
    text: String,
}

async fn handle_main_page() -> Json<Message> {
    let data = Message {
        text: String::from("Hello World!"),
    };
    Json(data)
}

fn create_router() -> Router {
    Router::new().route("/", get(handle_main_page))
}

#[tokio::main]
async fn main() {
    let app = create_router();

    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("listening on http://{}", listener.local_addr().unwrap());
    axum::serve(listener, app).await.unwrap();
}

#[cfg(test)]
mod tests;

Tests

#![allow(unused)]
fn main() {
use axum::{body::Body, http::Request, http::StatusCode};
use http_body_util::BodyExt;
use tower::ServiceExt;

use super::*;

#[tokio::test]
async fn test_main_page() {
    let response = create_router()
        .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);

    let content_type = response.headers().get("content-type").unwrap();
    assert_eq!(content_type.to_str().unwrap(), "application/json");

    let body = response.into_body();
    let bytes = body.collect().await.unwrap().to_bytes();
    let message: Message = serde_json::from_slice(&bytes).unwrap();

    assert_eq!(
        message,
        Message {
            text: String::from("Hello World!")
        }
    );
}
}