0
0
FastAPIframework~30 mins

Why query parameters filter data in FastAPI - See It in Action

Choose your learning style9 modes available
Why Query Parameters Filter Data
📖 Scenario: You are building a simple web API for a bookstore. Customers want to see books filtered by genre using query parameters in the URL.
🎯 Goal: Create a FastAPI app that returns a list of books. Add a query parameter to filter books by genre.
📋 What You'll Learn
Create a list of books with title and genre
Add a query parameter called genre to filter books
Return all books if no genre is specified
Use FastAPI's Query for the genre parameter
💡 Why This Matters
🌍 Real World
Filtering data with query parameters is common in web APIs to let users get only the data they want.
💼 Career
Understanding query parameters and filtering is essential for backend developers building APIs.
Progress0 / 4 steps
1
Create the initial list of books
Create a list called books with these dictionaries exactly: {'title': 'The Hobbit', 'genre': 'Fantasy'}, {'title': '1984', 'genre': 'Dystopian'}, {'title': 'The Catcher in the Rye', 'genre': 'Classic'}.
FastAPI
Need a hint?

Use a list with dictionaries for each book.

2
Add FastAPI app and import Query
Import FastAPI and Query from fastapi. Create an app instance called app.
FastAPI
Need a hint?

Use from fastapi import FastAPI, Query and app = FastAPI().

3
Create the route with genre query parameter
Create a GET route /books with a function get_books that has a query parameter genre of type str | None with default None using Query(None). Inside the function, filter books to only those with matching genre if genre is not None, else return all books.
FastAPI
Need a hint?

Use a list comprehension to filter books by genre.

4
Add response model and complete the app
Import List and Dict from typing. Add a response model to @app.get as List[Dict[str, str]] to show the output is a list of dictionaries with string keys and values.
FastAPI
Need a hint?

Use response_model=List[Dict[str, str]] in the route decorator.