0
0
FastAPIframework~5 mins

Basic query parameter declaration in FastAPI

Choose your learning style9 modes available
Introduction

Query parameters let users send extra information in the URL to customize what the server returns.

When you want to filter results, like searching for books by author name.
When you want to sort data, like showing newest items first.
When you want to paginate results, like showing page 2 of a list.
When you want to pass optional settings without changing the URL path.
Syntax
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/items/")
async def read_items(q: str = None):
    return {"query": q}

Query parameters are declared as function parameters with default values.

If you give a default value, the parameter is optional.

Examples
Here, q is a required query parameter. The user must provide it in the URL.
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/search/")
async def search(q: str):
    return {"query": q}
Here, q is optional. If the user does not provide it, q will be None.
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/search/")
async def search(q: str = None):
    return {"query": q}
Here, q has a default value of "default" if not provided by the user.
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/items/")
async def read_items(q: str = "default"):
    return {"query": q}
Sample Program

This program creates a simple API endpoint /items/ that accepts an optional query parameter q. If the user provides q, it returns a message showing what was searched. Otherwise, it says no query was provided.

FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/items/")
async def read_items(q: str = None):
    if q:
        return {"message": f"You searched for: {q}"}
    else:
        return {"message": "No search query provided."}
OutputSuccess
Important Notes

Query parameters appear after a question mark in the URL, like /items/?q=book.

FastAPI automatically converts query parameters to the declared type, like int or str.

Use None as a default to make parameters optional.

Summary

Query parameters let users send extra info in the URL to customize responses.

Declare them as function parameters with default values in FastAPI.

Parameters with defaults are optional; without defaults are required.