Filtering and sorting help you get just the data you want from a list or database. It makes your app faster and easier to use.
0
0
Filtering and sorting in FastAPI
Introduction
You want to show only items that match a search term.
You want to order a list of products by price or name.
You want users to find data by date or category.
You want to reduce the amount of data sent to the user.
You want to create a simple API that returns filtered results.
Syntax
FastAPI
from fastapi import FastAPI, Query from typing import List, Optional app = FastAPI() @app.get("/items/") async def read_items( q: Optional[str] = Query(None, min_length=3, max_length=50), sort_by: Optional[str] = Query(None, regex="^(name|price)$") ): # Your filtering and sorting logic here pass
Use Query to declare query parameters with validation.
Optional parameters can be used to filter or sort if provided.
Examples
This example shows filtering by category and sorting by price or name.
FastAPI
from fastapi import FastAPI, Query from typing import Optional app = FastAPI() @app.get("/products/") async def get_products( category: Optional[str] = Query(None), sort_by: Optional[str] = Query(None, regex="^(price|name)$") ): return {"category": category, "sort_by": sort_by}
This example sorts a fixed list of items by the given field.
FastAPI
from fastapi import FastAPI app = FastAPI() items = [ {"name": "apple", "price": 5}, {"name": "banana", "price": 3}, {"name": "carrot", "price": 4} ] @app.get("/items/") async def read_items(sort_by: str = "name"): sorted_items = sorted(items, key=lambda x: x[sort_by]) return sorted_items
Sample Program
This FastAPI app has an endpoint /items/ that lets you filter items by a search term q and sort them by name or price. If you don't provide q, it returns all items sorted.
FastAPI
from fastapi import FastAPI, Query from typing import Optional app = FastAPI() items = [ {"name": "apple", "price": 5}, {"name": "banana", "price": 3}, {"name": "carrot", "price": 4} ] @app.get("/items/") async def read_items( q: Optional[str] = Query(None, min_length=1), sort_by: Optional[str] = Query("name", regex="^(name|price)$") ): # Filter items by name containing q if q is given filtered = [item for item in items if q.lower() in item["name"]] if q else items # Sort filtered items by sort_by key sorted_items = sorted(filtered, key=lambda x: x[sort_by]) return sorted_items
OutputSuccess
Important Notes
Use Optional with query parameters to make them optional.
Use Query to add validation like minimum length or regex patterns.
Sorting keys should be checked to avoid errors if invalid keys are passed.
Summary
Filtering lets you get only the data you want by checking conditions.
Sorting arranges data in order, like alphabetically or by number.
FastAPI makes it easy to add filtering and sorting with query parameters.