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