Query parameters let users ask for specific data by adding extra details to a web address. This helps show only the data they want, making responses faster and clearer.
0
0
Why query parameters filter data in FastAPI
Introduction
When you want to let users search or filter a list of items, like products or articles.
When you want to control how much data is sent back, like showing only 10 results at a time.
When you want to sort data by a certain feature, like date or price.
When you want to get data that matches certain conditions, like all users from a specific city.
When you want to make your API flexible without creating many different URLs.
Syntax
FastAPI
from fastapi import FastAPI from typing import Optional app = FastAPI() @app.get("/items/") async def read_items(q: Optional[str] = None): if q: return {"filtered_query": q} return {"message": "No filter applied"}
Query parameters are defined as function parameters with default values.
Optional parameters mean the user can choose to add them or not.
Examples
This example shows a query parameter named
keyword that filters search results.FastAPI
from fastapi import FastAPI from typing import Optional app = FastAPI() @app.get("/search/") async def search_items(keyword: Optional[str] = None): if keyword: return {"search": keyword} return {"search": "all items"}
This example uses two query parameters:
category to filter products and limit to control how many products to show.FastAPI
from fastapi import FastAPI from typing import Optional app = FastAPI() @app.get("/products/") async def list_products(category: Optional[str] = None, limit: int = 10): return {"category": category, "limit": limit}
Sample Program
This FastAPI app returns all items by default. If you add a query parameter like ?category=fruit, it returns only items in that category.
FastAPI
from fastapi import FastAPI from typing import Optional app = FastAPI() items = [ {"id": 1, "name": "apple", "category": "fruit"}, {"id": 2, "name": "carrot", "category": "vegetable"}, {"id": 3, "name": "banana", "category": "fruit"} ] @app.get("/items/") async def get_items(category: Optional[str] = None): if category: filtered = [item for item in items if item["category"] == category] return {"filtered_items": filtered} return {"all_items": items}
OutputSuccess
Important Notes
Query parameters are always optional unless you make them required by removing the default value.
They help keep URLs clean and APIs flexible.
Use typing.Optional to indicate parameters that may or may not be provided.
Summary
Query parameters let users filter or customize data returned by an API.
They are added to the URL after a question mark and are easy to define in FastAPI functions.
Using query parameters makes your API more useful and efficient.