Bird
Raised Fist0
FastAPIframework~10 mins

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

Choose your learning style10 modes available
Concept Flow - Optional query parameters
Request received
↓
Check query parameters
↓
Is optional param present?
No→Use default or None
|Yes↓
Use provided param value
↓
Process request with param
↓
Send response
When a request comes in, FastAPI checks if the optional query parameter is given. If yes, it uses it; if not, it uses a default or None.
Execution Sample
FastAPI
from fastapi import FastAPI
from typing import Optional

app = FastAPI()

@app.get("/items/")
def read_items(q: Optional[str] = None):
    return {"q": q}
This code defines an endpoint with an optional query parameter 'q'. If 'q' is not provided, it defaults to None.
Execution Table
StepRequest URLQuery Param 'q'Parameter Value UsedResponse
1/items/NoneNone{"q": null}
2/items/?q=appleappleapple{"q": "apple"}
3/items/?q=empty stringempty string{"q": ""}
4/items/?other=123NoneNone{"q": null}
5Request ends---
💡 Request processing ends after sending response with parameter value or None if missing.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
qNoneNone"apple"""NoneVaries per request
Key Moments - 2 Insights
Why does 'q' become None when the query parameter is missing?
Because the function defines 'q' as Optional[str] with default None, FastAPI assigns None when 'q' is not in the URL (see execution_table step 1 and 4).
What happens if the query parameter 'q' is present but empty like '?q='?
FastAPI treats it as an empty string, not None (see execution_table step 3). So 'q' is '' (empty string), which is different from None.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'q' at step 2?
ANone
B"" (empty string)
C"apple"
D123
💡 Hint
Check the 'Parameter Value Used' column at step 2 in the execution_table.
At which step does 'q' have an empty string value?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look for 'empty string' in the 'Query Param q' column in the execution_table.
If you remove 'Optional' and set 'q: str = None', what will happen when 'q' is missing?
AFastAPI will raise an error for missing required parameter
BFastAPI will accept None as valid
CFastAPI will treat 'q' as empty string
DFastAPI will ignore 'q' and proceed
💡 Hint
Refer to how FastAPI treats required vs optional parameters in the variable_tracker and key_moments.
Concept Snapshot
Optional query parameters in FastAPI:
- Use typing.Optional[type] with default None
- If param missing, value is None
- If param present but empty, value is empty string
- Allows flexible API calls without errors
- Example: def read_items(q: Optional[str] = None)
Full Transcript
This example shows how FastAPI handles optional query parameters. When a request comes in, FastAPI checks if the query parameter 'q' is present. If it is, FastAPI uses its value. If not, it uses None because 'q' is defined as Optional[str] with default None. If the parameter is present but empty, FastAPI treats it as an empty string. This behavior allows APIs to accept flexible inputs without errors. The execution table traces requests with different URLs and shows how 'q' changes. The variable tracker follows 'q' across steps. Key moments clarify why None is used when missing and how empty strings differ. The quiz tests understanding of these behaviors.

Practice

(1/5)
1. What does it mean when a query parameter in FastAPI is optional?
easy
A. The parameter is required but can be empty
B. The parameter must always be included in the request
C. The user can choose to include it or not in the request
D. The parameter is ignored by FastAPI

Solution

  1. Step 1: Understand optional parameters in APIs

    Optional means the user does not have to provide the parameter for the request to work.
  2. Step 2: Apply to FastAPI query parameters

    FastAPI allows parameters to be optional by giving them a default value like None.
  3. Final Answer:

    The user can choose to include it or not in the request -> Option C
  4. Quick Check:

    Optional query parameter = user choice [OK]
Hint: Optional means user may skip it without error [OK]
Common Mistakes:
  • Thinking optional means parameter is always required
  • Confusing optional with ignored parameters
  • Assuming optional means empty string is required
2. Which of the following is the correct way to declare an optional query parameter named q of type str in FastAPI?
easy
A. def read_items(q: Optional[str] = None):
B. def read_items(q: str = None):
C. def read_items(q: str):
D. def read_items(q: Optional[str]):

Solution

  1. Step 1: Recall syntax for optional query parameters

    FastAPI uses Optional[type] with a default value None to mark parameters optional.
  2. Step 2: Check each option

    def read_items(q: Optional[str] = None): uses Optional[str] and default None, which is correct syntax.
  3. Final Answer:

    def read_items(q: Optional[str] = None): -> Option A
  4. Quick Check:

    Optional[str] + = None = correct syntax [OK]
Hint: Use Optional[type] with = None for optional params [OK]
Common Mistakes:
  • Omitting the default None value
  • Using Optional without import
  • Setting type to str without Optional
3. Given this FastAPI endpoint code:
from typing import Optional
from fastapi import FastAPI

app = FastAPI()

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

What will be the JSON response when the client calls /items/ without any query parameters?
medium
A. {"query": null}
B. {"query": "No query"}
C. An error occurs because q is missing
D. {"query": ""}

Solution

  1. Step 1: Understand default value of q

    q is Optional[str] with default None, so if missing, q is None.
  2. Step 2: Check the if condition

    If q is None (falsey), the function returns {"query": "No query"}.
  3. Final Answer:

    {"query": "No query"} -> Option B
  4. Quick Check:

    Missing q returns "No query" [OK]
Hint: Missing optional param uses default None [OK]
Common Mistakes:
  • Expecting error when param is missing
  • Assuming null is returned instead of string
  • Confusing empty string with None
4. Identify the error in this FastAPI endpoint code that tries to make q optional:
from fastapi import FastAPI

app = FastAPI()

@app.get("/search/")
def search(q: str = None):
    return {"q": q}
medium
A. q should be typed as Optional[str] when default is None
B. Function must be async to use optional parameters
C. Missing import of Optional from typing
D. Default value None is not allowed for query parameters

Solution

  1. Step 1: Check parameter typing and default

    q has type str but default None, which conflicts because None is not str.
  2. Step 2: Correct typing for optional parameter

    Use Optional[str] from typing to allow None as a valid default.
  3. Final Answer:

    q should be typed as Optional[str] when default is None -> Option A
  4. Quick Check:

    Type must match default None with Optional[str] [OK]
Hint: Match type with default None using Optional[type] [OK]
Common Mistakes:
  • Not importing Optional but using it
  • Making function async unnecessarily
  • Using None default without Optional type
5. You want to create a FastAPI endpoint that accepts an optional integer query parameter page with a default of 1, but if the user sends page=0, it should return an error. How would you declare page to achieve this behavior?
hard
A. page: Optional[int] = 1 with extra validation to reject 0
B. page: int without default and require user to send page > 0
C. page: Optional[int] = None and set page = 1 inside function if None
D. page: int = 1 and check inside function if page == 0 to raise error

Solution

  1. Step 1: Understand default and validation needs

    Default 1 means page is not optional, but user can omit it to get 1.
  2. Step 2: Handle invalid value 0

    Use int with default 1, then inside function check if page == 0 and raise error.
  3. Final Answer:

    page: int = 1 and check inside function if page == 0 to raise error -> Option D
  4. Quick Check:

    Default + validation inside function = page: int = 1 and check inside function if page == 0 to raise error [OK]
Hint: Use default param + check value inside function [OK]
Common Mistakes:
  • Making page Optional[int] = 1 (invalid syntax)
  • Not validating 0 value inside function
  • Requiring page without default when default needed
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