Required query parameters make sure your API gets the information it needs to work properly.
0
0
Required query parameters in FastAPI
Introduction
When you want users to provide specific data in the URL to get a response.
When your API endpoint needs a value to filter or search results.
When you want to avoid missing important information in requests.
When you want to enforce that certain inputs are always given by the client.
Syntax
FastAPI
from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items(q: str = Query(...)): return {"q": q}
Use Query(...) to mark a query parameter as required.
The ... inside Query means this parameter must be provided.
Examples
This example requires the query parameter
term. If missing, FastAPI returns an error.FastAPI
from fastapi import FastAPI, Query app = FastAPI() @app.get("/search/") async def search_items(term: str = Query(...)): return {"term": term}
This requires
category with at least 3 characters.FastAPI
from fastapi import FastAPI, Query app = FastAPI() @app.get("/filter/") async def filter_items(category: str = Query(..., min_length=3)): return {"category": category}
Sample Program
This FastAPI app has one endpoint /items/ that requires a query parameter q. If you call /items/?q=hello, it returns {"q": "hello"}. If you call /items/ without q, FastAPI returns an error saying the query parameter is missing.
FastAPI
from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items(q: str = Query(...)): return {"q": q}
OutputSuccess
Important Notes
Required query parameters help catch missing data early by returning clear errors.
You can add validation like min_length or regex inside Query() for better control.
Summary
Use Query(...) to make query parameters required in FastAPI.
This ensures clients always send needed data in the URL.
FastAPI automatically returns an error if required query parameters are missing.