0
0
FastAPIframework~5 mins

Multiple query parameters in FastAPI

Choose your learning style9 modes available
Introduction

Sometimes you want to get several pieces of information from a user in a web request. Multiple query parameters let you do that easily.

When a user can filter a list by several options, like color and size.
When you want to get multiple search terms from a user.
When you want to accept optional settings in a URL.
When you want to pass several values for the same key, like tags.
When you want to keep URLs simple and readable with many small inputs.
Syntax
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.

Examples
This example shows two query parameters: q is required, page is optional with default 1.
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/search/")
async def search(q: str, page: int = 1):
    return {"query": q, "page": page}
This example accepts multiple tags query parameters like ?tags=red&tags=blue.
FastAPI
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}
Sample Program

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.

FastAPI
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
    }
OutputSuccess
Important Notes

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].

Summary

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.