home ~ projects ~ socials

Accept And Return JSON Data Via POST Requests With Rust's axum

This is the first working example from my grimoire server. Needs a little cleanup (e.g. refine the structs and use an &str instead of include_str for the home page)

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

#[derive(Deserialize, Debug)]
struct MakeNoteInput {
    notes: String,
    tags: String,
    title: String,
    url: String,
}

#[derive(Serialize)]
struct MakeNoteResponse {
    id: String,
    url: String,
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(serve_home_page))
        .route("/api/make-note", post(handle_make_note));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:4545").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

async fn serve_home_page() -> response::Html<&'static str> {
    let response = include_str!("files/index.html");
    response::Html(response)
}

async fn handle_make_note(
    extract::Json(payload): extract::Json<MakeNoteInput>,
) -> response::Json<MakeNoteResponse> {
    dbg!(&payload.notes);
    dbg!(&payload.tags);
    dbg!(&payload.title);
    dbg!(&payload.url);
    let response = MakeNoteResponse {
        id: "asdf".to_string(),
        url: payload.url.clone(),
    };
    response::Json(response)
}
-- end of line --