0
0
FastAPIframework~30 mins

Boolean query parameters in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Boolean Query Parameters in FastAPI
📖 Scenario: You are building a simple web API using FastAPI. Your API will have an endpoint that returns a greeting message. You want to add a boolean query parameter to control whether the greeting is formal or casual.
🎯 Goal: Create a FastAPI app with a GET endpoint /greet that accepts a boolean query parameter called formal. If formal is true, the endpoint returns a formal greeting. If formal is false or missing, it returns a casual greeting.
📋 What You'll Learn
Create a FastAPI app instance named app
Add a GET endpoint /greet with a boolean query parameter formal
Use formal: bool = False to set the default value
Return {"message": "Good evening, sir."} if formal is true
Return {"message": "Hey there!"} if formal is false
💡 Why This Matters
🌍 Real World
Boolean query parameters are common in APIs to toggle features or options, such as filtering results or changing response styles.
💼 Career
Understanding how to handle boolean query parameters in FastAPI is essential for backend developers building flexible and user-friendly APIs.
Progress0 / 4 steps
1
Create FastAPI app instance
Import FastAPI from fastapi and create an app instance called app.
FastAPI
Need a hint?

Use app = FastAPI() to create the app instance.

2
Add GET endpoint with boolean query parameter
Add a GET endpoint /greet to app. Define a function greet that takes a boolean query parameter formal with default value False.
FastAPI
Need a hint?

Use @app.get("/greet") decorator and define formal: bool = False in the function parameters.

3
Implement conditional greeting logic
Inside the greet function, return {"message": "Good evening, sir."} if formal is True. Otherwise, return {"message": "Hey there!"}.
FastAPI
Need a hint?

Use an if statement to check formal and return the correct message.

4
Add type hints and docstring for clarity
Add a docstring to the greet function explaining that formal controls the greeting style. Ensure the function has a return type hint of dict.
FastAPI
Need a hint?

Add a docstring inside the function and a return type hint -> dict.