0
0
FastAPIframework~30 mins

Optional query parameters in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Optional Query Parameters in FastAPI
📖 Scenario: You are building a simple web API for a bookstore. You want to allow users to search for books by title. Additionally, users can optionally filter the search results by author name if they want.
🎯 Goal: Create a FastAPI app with an endpoint /books/ that accepts a required query parameter title and an optional query parameter author. The endpoint should return a JSON list of books matching the title and, if provided, the author.
📋 What You'll Learn
Create a FastAPI app instance named app
Define a GET endpoint at /books/
Use a required query parameter title of type str
Use an optional query parameter author of type str with default null
Return a filtered list of books matching the title and optionally the author
💡 Why This Matters
🌍 Real World
APIs often need to accept optional filters to let users narrow down search results without requiring all filters.
💼 Career
Understanding optional query parameters is essential for backend developers building flexible and user-friendly APIs.
Progress0 / 4 steps
1
Create the initial data list of books
Create a list called books with these dictionaries exactly: {'title': 'The Hobbit', 'author': 'J.R.R. Tolkien'}, {'title': '1984', 'author': 'George Orwell'}, {'title': 'The Silmarillion', 'author': 'J.R.R. Tolkien'}
FastAPI
Need a hint?

Use a list of dictionaries. Each dictionary has keys 'title' and 'author'.

2
Create the FastAPI app and import required modules
Import FastAPI from fastapi and create an app instance called app
FastAPI
Need a hint?

Use from fastapi import FastAPI and then app = FastAPI().

3
Define the GET endpoint with required and optional query parameters
Define a GET endpoint /books/ using @app.get("/books/"). Create a function read_books with parameters title: str and author: str | null = null to accept required title and optional author query parameters.
FastAPI
Need a hint?

Use @app.get("/books/") and define read_books with parameters title: str and author: str | null = null.

4
Filter and return books matching title and optional author
Inside read_books, create a list results that includes books from books where book['title'] contains title (case insensitive). If author is not null, further filter results to include only books where book['author'] contains author (case insensitive). Return results.
FastAPI
Need a hint?

Use list comprehensions to filter books by title and optionally by author. Use str.lower() for case-insensitive matching.