Module 4 Exercises: Mastering Routing and Payloads

Module 4 Exercises: Mastering Routing and Payloads

Practical exercises to harden your skills in identifying path vs query parameters and designing robust request bodies.

Module 4 Exercises: Mastering Routing and Payloads

Routing is the bridge between the user and your data. These exercises will push you to design clear, type-safe, and self-documenting APIs.


Exercise 1: The Multi-Parameter Challenge

You are building a Library Management System. You need to design a single endpoint that allows a user to:

  1. Identify a specific Category (e.g., "History") in the URL path.
  2. Optionally Search within that category using a query parameter q.
  3. Optionally Filter by publication year with an integer query parameter year.

Goal: Write the function signature for this endpoint.


Exercise 2: Defining the Schema

Design a Pydantic BaseModel for a Support Ticket. The ticket should have:

  • subject (String, required, minimum 5 characters)
  • description (String, required)
  • priority (Integer, default is 3)
  • tags (A list of strings, default is an empty list)

Use the Query or Body logic if needed for validation (though for a school model, standard field definitions are fine).


Exercise 3: Validating the Body

Look at the following JSON payload sent by a client. Based on the rules of FastAPI, will this request result in a Success or a 422 Error?

Pydantic Model:

class Profile(BaseModel):
    username: str
    age: int
    is_active: bool = True

Client Payload:

{
  "username": "fastguy",
  "age": "25"
}

Self-Correction / Discussion

Exercise 1 Answer:

@app.get("/categories/{category_name}")
async def list_books(
    category_name: str, 
    q: Optional[str] = None, 
    year: Optional[int] = None
):
    return {"category": category_name, "query": q, "year": year}

Exercise 2 Answer:

from pydantic import BaseModel, Field

class Ticket(BaseModel):
    subject: str = Field(..., min_length=5)
    description: str
    priority: int = 3
    tags: list[str] = []

Exercise 3 Answer:

Success! Even though "25" is a string in the JSON, FastAPI (via Pydantic) will see that the model expects an int and will attempt to convert it. Since "25" can be safely converted to the integer 25, the validation passes.


Summary of Module 4

You have mastered the mechanics of communication:

  • Path Parameters: For identifying resources.
  • Query Parameters: For filtering and options.
  • Request Bodies: For sending complex data.

In Module 5: Data Validation and Serialization, we will deep dive into Pydantic, the engine that makes all of this validation possible, and learn how to shape our output as precisely as our input.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn