0
0
FastAPIframework~5 mins

Boolean query parameters in FastAPI

Choose your learning style9 modes available
Introduction

Boolean query parameters let users send true or false values in URLs. This helps control how the server responds.

To enable or disable a feature in an API call, like showing extra details.
To filter results, for example, only show active items when true.
To toggle options, such as turning on debug mode via URL.
To decide if a response should include sensitive data or not.
To control pagination or sorting behavior with simple true/false flags.
Syntax
FastAPI
from fastapi import FastAPI, Query
from typing import Optional

app = FastAPI()

@app.get("/items/")
async def read_items(show_details: Optional[bool] = Query(False)):
    if show_details:
        return {"message": "Showing detailed info"}
    return {"message": "Showing basic info"}

Use Optional[bool] with Query to declare a boolean query parameter.

FastAPI automatically converts query strings like ?show_details=true or ?show_details=false to Python booleans.

Examples
This example shows a boolean query parameter that can be true, false, or not provided.
FastAPI
from fastapi import FastAPI, Query
from typing import Optional

app = FastAPI()

@app.get("/users/")
async def get_users(active: Optional[bool] = Query(None)):
    if active is None:
        return {"users": "all users"}
    elif active:
        return {"users": "only active users"}
    else:
        return {"users": "only inactive users"}
Here, the boolean parameter debug defaults to false if not given.
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/debug/")
async def debug_mode(debug: bool = False):
    return {"debug": debug}
Sample Program

This FastAPI app has a GET endpoint at /items/. It accepts a boolean query parameter show_details. If true, it returns a message with detailed info. Otherwise, it returns basic info.

FastAPI
from fastapi import FastAPI, Query
from typing import Optional

app = FastAPI()

@app.get("/items/")
async def read_items(show_details: Optional[bool] = Query(False)):
    if show_details:
        return {"message": "Showing detailed info"}
    return {"message": "Showing basic info"}
OutputSuccess
Important Notes

Boolean query parameters accept values like true, false, 1, 0 (case insensitive).

If you want the parameter to be optional, use Optional[bool] and set a default like None or False.

FastAPI handles the conversion automatically, so you get a Python boolean in your function.

Summary

Boolean query parameters let users control API behavior with true/false flags.

FastAPI converts query strings to Python booleans automatically.

Use Optional[bool] with Query to declare them clearly.