typestar

JSON in and out in Rust

Json is both an extractor and a response, driven by serde on your types.

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

#[derive(Deserialize)]
struct RunInput {
    lang: String,
    tpm: u32,
}

#[derive(Serialize)]
struct RunSaved {
    stars: u8,
    lang: String,
}

async fn save(Json(input): Json<RunInput>) -> Json<RunSaved> {
    let stars = if input.tpm >= 100 { 3 } else { 1 };
    Json(RunSaved { stars, lang: input.lang })
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/api/results", post(save));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:8080")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

How it works

  1. Json<T> in an argument deserializes the request body.
  2. Json<T> in the return position serializes the reply.
  3. A bad body becomes a 422 before your handler runs.

Keywords and builtins used here

The run, in numbers

Lines
28
Characters to type
590
Tokens
174
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 99 seconds.

Type this snippet

Step 2 of 3 in Routes & handlers, step 2 of 9 in Web services with axum.

← Previous Next →

JSON in and out in other languages