0
0
FastAPIframework~30 mins

Default values in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Default Values in FastAPI Query Parameters
📖 Scenario: You are building a simple web API that returns information about books. Sometimes users want to filter books by genre, but if they don't specify a genre, the API should return all books.
🎯 Goal: Create a FastAPI app with a GET endpoint /books that accepts an optional query parameter genre with a default value of "all". The endpoint should return a list of books filtered by the genre if specified, or all books if the genre is "all".
📋 What You'll Learn
Create a list variable called books containing dictionaries with keys title and genre.
Create a variable called default_genre with the value "all".
Create a GET endpoint /books with a query parameter genre that defaults to default_genre.
Filter the books list by genre if it is not "all", otherwise return all books.
💡 Why This Matters
🌍 Real World
APIs often need to handle optional filters with default values to provide flexible data retrieval for users.
💼 Career
Understanding default values in query parameters is essential for backend developers building user-friendly and robust APIs.
Progress0 / 4 steps
1
Create the initial books data
Create a list called books with these exact dictionaries: {"title": "The Hobbit", "genre": "fantasy"}, {"title": "1984", "genre": "dystopian"}, and {"title": "Python 101", "genre": "education"}.
FastAPI
Need a hint?

Use a list with dictionaries. Each dictionary has keys title and genre.

2
Add a default genre variable
Create a variable called default_genre and set it to the string "all".
FastAPI
Need a hint?

Just assign the string "all" to default_genre.

3
Create the FastAPI app and GET endpoint with default query parameter
Import FastAPI and Query from fastapi. Create a FastAPI app called app. Define a GET endpoint /books with a query parameter genre that defaults to default_genre using Query(default_genre).
FastAPI
Need a hint?

Use Query(default_genre) to set the default value for the query parameter.

4
Filter books by genre or return all
Inside the get_books function, return a list of books filtered by genre if genre is not "all". Otherwise, return the full books list.
FastAPI
Need a hint?

Use a list comprehension to filter books by genre.