0
0
FastAPIframework~5 mins

Optional query parameters in FastAPI

Choose your learning style9 modes available
Introduction

Optional query parameters let users send extra information in a web request, but they don't have to. This makes your app flexible and user-friendly.

When you want to filter results but don't require the filter every time.
When you want to allow users to sort data optionally.
When you want to add search keywords that users can skip.
When you want to provide pagination controls that users can omit.
When you want to accept extra info that changes output but isn't mandatory.
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 {"query": q}
    return {"query": "No query provided"}

Use Optional[type] from typing to mark a query parameter as optional.

Set the default value to None to make the parameter optional.

Examples
This example shows a simple optional string query parameter q. If not given, it returns a default message.
FastAPI
from fastapi import FastAPI
from typing import Optional

app = FastAPI()

@app.get("/search/")
async def search_items(q: Optional[str] = None):
    return {"search": q or "No search term"}
Here, category is optional and can be skipped. limit has a default value of 10 if not provided.
FastAPI
from fastapi import FastAPI
from typing import Optional

app = FastAPI()

@app.get("/products/")
async def get_products(category: Optional[str] = None, limit: int = 10):
    return {"category": category, "limit": limit}
Sample Program

This FastAPI app defines one endpoint /items/ with an optional query parameter q. If the user sends ?q=apple, it returns a message with the search term. If q is missing, it returns a default message.

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 {"message": f"You searched for: {q}"}
    return {"message": "No search query provided"}
OutputSuccess
Important Notes

Optional query parameters help keep your API flexible and easy to use.

Always set a default value (usually None) to make a parameter optional.

FastAPI automatically documents optional parameters in the API docs.

Summary

Optional query parameters let users send extra info but don't have to.

Use Optional[type] and default None to make parameters optional.

This makes your API flexible and user-friendly.