Bird
Raised Fist0
FastAPIframework~10 mins

Boolean query parameters in FastAPI - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Boolean query parameters
Client sends HTTP GET request
↓
FastAPI receives request
↓
Extract query parameters
↓
Parse boolean query parameter
↓
True value
↓
Use in endpoint logic
↓
Return response based on boolean
FastAPI reads the query parameter as a string, converts it to a boolean, then uses it in the endpoint logic to decide the response.
Execution Sample
FastAPI
from fastapi import FastAPI, Query

app = FastAPI()

@app.get("/items")
async def read_items(show_details: bool = Query(False)):
    return {"show_details": show_details}
This code defines a GET endpoint that reads a boolean query parameter 'show_details' and returns its value.
Execution Table
StepRequest URLQuery Parameter ValueParsed BooleanActionResponse
1/items?show_details=truetrueTrueUse True in logic{"show_details": true}
2/items?show_details=falsefalseFalseUse False in logic{"show_details": false}
3/items?show_details=11TrueUse True in logic{"show_details": true}
4/items?show_details=00FalseUse False in logic{"show_details": false}
5/itemsNone (default)False (default)Use default False{"show_details": false}
6/items?show_details=unexpectedunexpectedError (validation)Reject request{"detail": [{"loc": ["query", "show_details"], "msg": "value is not a valid boolean", "type": "type_error.bool"}]}
💡 Execution stops after response is returned or validation error occurs.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5After 6
show_detailsFalse (default)TrueFalseTrueFalseFalseValidation Error
Key Moments - 2 Insights
Why does 'show_details=1' become True but 'show_details=unexpected' causes an error?
FastAPI accepts '1' and 'true' as valid True values but rejects strings that don't match boolean formats, causing validation error as shown in execution_table row 6.
What happens if the query parameter is missing?
The default value False is used automatically, as shown in execution_table row 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the parsed boolean value when the URL is '/items?show_details=0'?
ATrue
BFalse
CValidation Error
DNone
💡 Hint
Check execution_table row 4 under 'Parsed Boolean' column.
At which step does the request get rejected due to invalid boolean?
AStep 6
BStep 3
CStep 1
DStep 5
💡 Hint
Look for 'Error (validation)' in the 'Action' column in execution_table.
If the default value in the code changed to True, what would be the response for '/items' with no query parameter?
AValidation error
B{"show_details": false}
C{"show_details": true}
DEmpty response
💡 Hint
Refer to variable_tracker and execution_table row 5 for default behavior.
Concept Snapshot
FastAPI boolean query parameters:
- Use bool type in function signature
- Use Query() for defaults and metadata
- Accepts true/false, 1/0 as valid inputs
- Invalid strings cause validation error
- Default used if parameter missing
Full Transcript
In FastAPI, boolean query parameters are read as strings from the URL and converted to Python booleans. The parameter is defined in the endpoint function with type bool and optionally a default using Query(). When a request comes in, FastAPI tries to parse the query parameter value into a boolean. Values like 'true', '1' become True; 'false', '0' become False. If the parameter is missing, the default value is used. If the value cannot be parsed as a boolean, FastAPI returns a validation error. This behavior lets you control endpoint logic based on simple true/false flags sent in the URL.

Practice

(1/5)
1. What does a Boolean query parameter in FastAPI represent?
easy
A. A true or false flag passed in the URL to control API behavior
B. A number used to count API requests
C. A string that describes the API endpoint
D. A list of items sent in the request body

Solution

  1. Step 1: Identify the purpose of Boolean query parameters

    Boolean query parameters are flags that can be true or false, used to control how the API behaves.
  2. Step 2: Identify the correct description

    Only "A true or false flag passed in the URL to control API behavior" describes a true/false flag passed via URL query parameters.
  3. Final Answer:

    A true or false flag passed in the URL to control API behavior -> Option A
  4. Quick Check:

    Boolean query parameter = true/false flag [OK]
Hint: Boolean query parameters are true/false flags in the URL [OK]
Common Mistakes:
  • Confusing Boolean parameters with numbers or strings
  • Thinking Boolean parameters come from request body
  • Assuming Boolean parameters are lists
2. Which of the following is the correct way to declare an optional Boolean query parameter in FastAPI?
easy
A. def read_items(active: bool = Query(None)):
B. def read_items(active: Optional[bool] = Query(None)):
C. def read_items(active: str = Query(None)):
D. def read_items(active: int = Query(None)):

Solution

  1. Step 1: Recall FastAPI syntax for optional Boolean query parameters

    Use Optional[bool] with Query(None) to allow the parameter to be true, false, or missing.
  2. Step 2: Match the correct function signature

    def read_items(active: Optional[bool] = Query(None)): correctly uses Optional[bool] and Query(None) for an optional Boolean query parameter.
  3. Final Answer:

    def read_items(active: Optional[bool] = Query(None)): -> Option B
  4. Quick Check:

    Optional[bool] with Query(None) = correct syntax [OK]
Hint: Use Optional[bool] with Query(None) for optional Booleans [OK]
Common Mistakes:
  • Using bool without Optional for optional parameters
  • Using str or int instead of bool
  • Omitting Query import or default value
3. Given this FastAPI endpoint code, what will be the output if the URL is /items?active=true?
from fastapi import FastAPI, Query
from typing import Optional

app = FastAPI()

@app.get('/items')
async def read_items(active: Optional[bool] = Query(None)):
    return {"active": active}
medium
A. Error: invalid query parameter
B. {"active": "true"}
C. {"active": null}
D. {"active": true}

Solution

  1. Step 1: Understand FastAPI Boolean query parsing

    FastAPI automatically converts query strings like 'true' to Python boolean True.
  2. Step 2: Check the returned dictionary

    The function returns {"active": active}, so with active=true in URL, it returns {"active": true} as JSON.
  3. Final Answer:

    {"active": true} -> Option D
  4. Quick Check:

    Query 'true' converts to True boolean [OK]
Hint: FastAPI converts 'true' string to True boolean automatically [OK]
Common Mistakes:
  • Expecting string 'true' instead of boolean true
  • Assuming missing parameter returns false
  • Thinking it causes an error
4. Identify the error in this FastAPI endpoint that uses a Boolean query parameter:
from fastapi import FastAPI, Query

app = FastAPI()

@app.get('/items')
async def read_items(active: bool = Query()):
    return {"active": active}
medium
A. The return statement must convert active to string
B. Boolean query parameters cannot be used in FastAPI
C. Query() requires a default value for optional parameters
D. The function must be synchronous, not async

Solution

  1. Step 1: Check Query parameter usage

    Query() without a default value means the parameter is required. For optional, a default like None is needed.
  2. Step 2: Identify the missing default

    Since active is bool and no default is given, FastAPI expects the query parameter always present, else error.
  3. Final Answer:

    Query() requires a default value for optional parameters -> Option C
  4. Quick Check:

    Query() needs default for optional params [OK]
Hint: Use Query(None) for optional Boolean parameters [OK]
Common Mistakes:
  • Omitting default value for optional query parameters
  • Thinking async is not allowed
  • Trying to convert Boolean to string manually
5. You want to create a FastAPI endpoint that filters items by an optional Boolean query parameter available. If available is true, return only available items; if false, only unavailable items; if missing, return all items. Which code correctly implements this behavior?
hard
A. from fastapi import FastAPI, Query from typing import Optional app = FastAPI() items = [{"name": "item1", "available": True}, {"name": "item2", "available": False}] @app.get('/items') async def read_items(available: Optional[bool] = Query(None)): if available is None: return items return [item for item in items if item["available"] == available]
B. from fastapi import FastAPI app = FastAPI() @app.get('/items') async def read_items(available: bool = False): return {"available": available}
C. from fastapi import FastAPI, Query app = FastAPI() @app.get('/items') async def read_items(available: bool = Query()): return {"available": available}
D. from fastapi import FastAPI, Query from typing import Optional app = FastAPI() @app.get('/items') async def read_items(available: Optional[str] = Query(None)): return {"available": available}

Solution

  1. Step 1: Analyze the required filtering behavior

    If available is None, return all items; else filter by matching available status.
  2. Step 2: Check code correctness

    from fastapi import FastAPI, Query from typing import Optional app = FastAPI() items = [{"name": "item1", "available": True}, {"name": "item2", "available": False}] @app.get('/items') async def read_items(available: Optional[bool] = Query(None)): if available is None: return items return [item for item in items if item["available"] == available] uses Optional[bool] with Query(None) and filters items correctly based on available value.
  3. Final Answer:

    from fastapi import FastAPI, Query from typing import Optional app = FastAPI() items = [{"name": "item1", "available": True}, {"name": "item2", "available": False}] @app.get('/items') async def read_items(available: Optional[bool] = Query(None)): if available is None: return items return [item for item in items if item["available"] == available] -> Option A
  4. Quick Check:

    Optional[bool] with filtering logic = correct [OK]
Hint: Use Optional[bool] and check None to handle missing query param [OK]
Common Mistakes:
  • Using bool without Optional for optional parameter
  • Not filtering items based on Boolean value
  • Using string type instead of Boolean
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard