API Calculator
Send in two numbers as part of the path /2/3 and get back a JSON struct
with the two values and the sum of the numbers.
[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, extract::Path, response::Json, routing::get};
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Calc {
a: u32,
b: u32,
sum: u32,
}
async fn handle_main_page(Path((a, b)): Path<(u32, u32)>) -> Json<Calc> {
let data = Calc { a, b, sum: a + b };
Json(data)
}
fn create_router() -> Router {
Router::new().route("/{a}/{b}", 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() {
check("/2/3", Calc { a: 2, b: 3, sum: 5 }).await;
check(
"/7/3",
Calc {
a: 7,
b: 3,
sum: 10,
},
)
.await;
}
async fn check(uri: &str, expected: Calc) {
let response = create_router()
.oneshot(Request::builder().uri(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 result: Calc = serde_json::from_slice(&bytes).unwrap();
assert_eq!(result, expected);
}
}