Boolean query parameters let users send true or false values in URLs. This helps control how the server responds.
Boolean query parameters in 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.
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"}
debug defaults to false if not given.from fastapi import FastAPI app = FastAPI() @app.get("/debug/") async def debug_mode(debug: bool = False): return {"debug": debug}
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.
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"}
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.
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.