0
0
FastAPIframework~30 mins

Why structured responses matter in FastAPI - See It in Action

Choose your learning style9 modes available
Why structured responses matter
📖 Scenario: You are building a simple web API using FastAPI. Your API will return information about books. To make it easy for users and other developers to understand and use your API, you want to send responses in a clear, consistent structure.
🎯 Goal: Create a FastAPI app that returns book data in a structured JSON format with keys title, author, and year. This helps clients know exactly what to expect in the response.
📋 What You'll Learn
Create a list of dictionaries with book details
Add a configuration variable for minimum publication year
Filter books published after the minimum year using a list comprehension
Return the filtered books as a JSON response using FastAPI
💡 Why This Matters
🌍 Real World
APIs often serve data to websites and apps. Structured responses ensure all clients get data in a predictable format.
💼 Career
Understanding how to build clear, structured API responses is essential for backend developers and full-stack engineers.
Progress0 / 4 steps
1
Create the initial book data
Create a list called books with these exact dictionaries: {'title': '1984', 'author': 'George Orwell', 'year': 1949}, {'title': 'Brave New World', 'author': 'Aldous Huxley', 'year': 1932}, and {'title': 'Fahrenheit 451', 'author': 'Ray Bradbury', 'year': 1953}.
FastAPI
Need a hint?

Use a list with dictionaries inside. Each dictionary has keys title, author, and year.

2
Add a minimum year filter
Create a variable called min_year and set it to 1940. This will be used to filter books published after this year.
FastAPI
Need a hint?

Just create a variable named min_year and assign the number 1940.

3
Filter books published after the minimum year
Create a new list called filtered_books using a list comprehension that includes only books from books where the year is greater than min_year.
FastAPI
Need a hint?

Use a list comprehension with for book in books and an if condition checking book['year'] > min_year.

4
Return the filtered books as a JSON response
Import FastAPI from fastapi and JSONResponse from fastapi.responses. Create an app instance called app. Define a GET route at /books that returns filtered_books wrapped in JSONResponse.
FastAPI
Need a hint?

Import FastAPI and JSONResponse. Create app = FastAPI(). Use @app.get('/books') decorator. Define async function get_books() that returns JSONResponse(content=filtered_books).