Responses: Json & Status Codes

1. Welcome and Icebreaker:

What’s the most useful HTTP status code you’ve encountered, and why?

2. Outline the Session:

Agenda:

  1. Concept Explanation: Returning JSON and setting status codes in Axum.
  2. Live Coding: Send JSON responses and custom status codes.
  3. Tasks: Practice by customizing responses.

Learning Outcomes:

  • Return JSON responses from handlers.
  • Set custom HTTP status codes in Axum.

Expectations: Try returning different status codes and see how clients react!

3. Concept Explanation:

Axum makes it easy to return JSON responses using the axum::Json type. Your response struct must derive serde::Serialize. You can also set custom status codes by returning a tuple (StatusCode, Json<T>).

This is useful for indicating success, creation, errors, etc.

4. Live Coding Demonstration:

use axum::{Json, Router, routing::get, http::StatusCode};
use serde::Serialize;

#[derive(Serialize)]
struct ApiResponse {
    message: String,
}

async fn hello_json() -> (StatusCode, Json<ApiResponse>) {
    let response = ApiResponse {
        message: "Hello, JSON!".to_string(),
    };
    (StatusCode::OK, Json(response))
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/json", get(hello_json));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Best Practices:

  • Use clear, consistent response structures.
  • Set appropriate status codes for each response.

Common Pitfalls:

  • Forgetting to derive Serialize for response structs.
  • Returning the wrong status code for the situation.

5. Tasks

  • Add a /created endpoint that returns a 201 Created status with a JSON message.
  • Try returning different status codes for different situations (e.g., 400 for errors).
  • Create a response struct with multiple fields and return it as JSON.