Sometimes you want to get several pieces of information from a user in a web request. Multiple query parameters let you do that easily.
Multiple query parameters in FastAPI
from fastapi import FastAPI from typing import List, Optional app = FastAPI() @app.get("/items/") async def read_items( q: Optional[str] = None, # single optional query tags: Optional[List[str]] = None # multiple values for same key ): return {"q": q, "tags": tags}
Use Python type hints to declare query parameters.
Optional parameters can have a default value like None.
q is required, page is optional with default 1.from fastapi import FastAPI app = FastAPI() @app.get("/search/") async def search(q: str, page: int = 1): return {"query": q, "page": page}
tags query parameters like ?tags=red&tags=blue.from fastapi import FastAPI from typing import List, Optional app = FastAPI() @app.get("/filter/") async def filter_items(tags: Optional[List[str]] = None): return {"tags": tags}
This FastAPI app defines a route /products/ that accepts multiple query parameters: category, price_min, price_max, and multiple tags. All are optional. You can call it like /products/?category=books&price_min=10&tags=fiction&tags=bestseller.
from fastapi import FastAPI from typing import List, Optional app = FastAPI() @app.get("/products/") async def get_products( category: Optional[str] = None, price_min: Optional[float] = None, price_max: Optional[float] = None, tags: Optional[List[str]] = None ): return { "category": category, "price_min": price_min, "price_max": price_max, "tags": tags }
Query parameters are always strings in URLs but FastAPI converts them to the types you specify.
Use Optional to make parameters not required.
For multiple values with the same key, use a list type like List[str].
Multiple query parameters let you get many inputs from a URL.
Use Python types and Optional to control required or optional parameters.
Use List types to accept multiple values for the same query key.