0
0
FastAPIframework~30 mins

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

Choose your learning style9 modes available
Multiple query parameters
📖 Scenario: You are building a simple web API using FastAPI. Your API will accept multiple query parameters from the URL to filter a list of items.Imagine you have a store with products, and you want users to search products by category and price range using query parameters.
🎯 Goal: Create a FastAPI app that accepts two query parameters: category and max_price. The app should return a filtered list of products matching the category and with price less than or equal to max_price.
📋 What You'll Learn
Create a list of products as dictionaries with keys 'name', 'category', and 'price'.
Add query parameters category (string) and max_price (float) to the GET endpoint.
Filter the products list based on the query parameters.
Return the filtered list as JSON response.
💡 Why This Matters
🌍 Real World
APIs often need to accept multiple query parameters to filter or search data, like searching products by category and price.
💼 Career
Understanding how to handle multiple query parameters in FastAPI is essential for backend web development and building flexible APIs.
Progress0 / 4 steps
1
DATA SETUP: Create the products list
Create a list called products with these exact dictionaries: {'name': 'Apple', 'category': 'fruit', 'price': 1.2}, {'name': 'Banana', 'category': 'fruit', 'price': 0.5}, {'name': 'Carrot', 'category': 'vegetable', 'price': 0.8}, {'name': 'Steak', 'category': 'meat', 'price': 5.0}.
FastAPI
Need a hint?

Use a list of dictionaries exactly as shown.

2
CONFIGURATION: Import FastAPI and create app
Import FastAPI from fastapi and create an app instance called app.
FastAPI
Need a hint?

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

3
CORE LOGIC: Create GET endpoint with query parameters
Create a GET endpoint at /items/ using @app.get("/items/"). Define a function read_items with two query parameters: category: str and max_price: float. Inside the function, filter products to include only items where item['category'] == category and item['price'] <= max_price. Return the filtered list.
FastAPI
Need a hint?

Use a list comprehension to filter products by category and max_price.

4
COMPLETION: Add type hints and async keyword
Ensure the endpoint function read_items is declared with async def and has type hints for category: str and max_price: float. Confirm the function returns the filtered list of products.
FastAPI
Need a hint?

Make sure the function is async and has correct type hints.