Bird
Raised Fist0
FastAPIframework~20 mins

Default values in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
FastAPI Default Values Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output when calling the endpoint without query parameters?
Consider this FastAPI endpoint using default values for query parameters. What will the response be if you call /items/42 without any query parameters?
FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    description: str = "No description provided"

@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = "default_query"):
    return {"item_id": item_id, "q": q}
A{"item_id": 42, "q": null}
B{"item_id": 42, "q": "default_query"}
C{"item_id": 42}
DError: Missing required query parameter 'q'
Attempts:
2 left
💡 Hint
Think about what happens when a query parameter has a default value and is not provided by the client.
📝 Syntax
intermediate
2:00remaining
Which option correctly sets a default value for a path parameter in FastAPI?
FastAPI path parameters cannot have default values. Which of the following code snippets correctly defines a path parameter and a query parameter with a default value?
FastAPI
from fastapi import FastAPI

app = FastAPI()

# Choose the correct snippet:
A
@app.get("/users/{user_id=1}")
async def get_user(user_id: int):
    return {"user_id": user_id}
B
@app.get("/users")
async def get_user(user_id: int = 1):
    return {"user_id": user_id}
C
@app.get("/users/{user_id}")
async def get_user(user_id: int, active: bool = True):
    return {"user_id": user_id, "active": active}
D
@app.get("/users/{user_id}")
async def get_user(user_id: int = 1):
    return {"user_id": user_id}
Attempts:
2 left
💡 Hint
Path parameters must always be provided in the URL path. Query parameters can have defaults.
❓ state_output
advanced
2:00remaining
What is the response when a request omits an optional query parameter with a default value?
Given this FastAPI endpoint, what will be the JSON response if the client calls /search without any query parameters?
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/search")
async def search_items(term: str = "all", limit: int = 10):
    return {"term": term, "limit": limit}
A{"term": "all", "limit": 10}
B{"term": null, "limit": null}
C{"term": "", "limit": 0}
D422 Unprocessable Entity error
Attempts:
2 left
💡 Hint
Check what happens when query parameters have default values and are not provided.
🔧 Debug
advanced
2:00remaining
Why does this FastAPI endpoint raise a validation error?
Examine this FastAPI endpoint. Why does calling /products without query parameters cause a 422 error?
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/products")
async def list_products(category: str):
    return {"category": category}
ABecause 'category' is a required query parameter without a default value
BBecause path parameters cannot have default values
CBecause the endpoint URL is missing a path parameter
DBecause the function is missing an async keyword
Attempts:
2 left
💡 Hint
Think about which parameters FastAPI expects from the client and which have defaults.
🧠 Conceptual
expert
3:00remaining
How does FastAPI handle default values for mutable types in query parameters?
Consider this FastAPI endpoint with a query parameter defaulting to an empty list. What is the correct way to define a default empty list for a query parameter to avoid unexpected behavior?
FastAPI
from fastapi import FastAPI, Query

app = FastAPI()

@app.get("/tags")
async def get_tags(tags: list[str] = []):
    return {"tags": tags}
AUse Optional type hint: tags: Optional[list[str]] = []
BSet default to None and check inside function: tags: list[str] = None
CKeep the default as an empty list directly: tags: list[str] = []
DUse Query with default_factory: tags: list[str] = Query(default_factory=list)
Attempts:
2 left
💡 Hint
Mutable default arguments can cause shared state issues in Python functions.

Practice

(1/5)
1. In FastAPI, what is the main purpose of setting a default value for a function parameter in an endpoint?
easy
A. To automatically convert the parameter to a string
B. To make the parameter optional and provide a fallback value if not supplied
C. To disable the endpoint if the parameter is missing
D. To force the client to always send a value for that parameter

Solution

  1. Step 1: Understand default values in FastAPI

    Default values allow parameters to be optional by providing a fallback if the client does not send a value.
  2. Step 2: Identify the effect on endpoint behavior

    When a default is set, the endpoint works even if the parameter is missing, using the default instead.
  3. Final Answer:

    To make the parameter optional and provide a fallback value if not supplied -> Option B
  4. Quick Check:

    Default value = optional parameter [OK]
Hint: Default values make parameters optional with fallback [OK]
Common Mistakes:
  • Thinking default forces client to send value
  • Assuming default disables endpoint if missing
  • Confusing default with type conversion
2. Which of the following is the correct way to set a default value of 10 for a query parameter named limit in a FastAPI endpoint?
easy
A. def read_items(limit: int = 10):
B. def read_items(limit: int = Query(10)):
C. def read_items(limit: Query = 10):
D. def read_items(limit: int Query(10)):

Solution

  1. Step 1: Recall Python default parameter syntax

    Default values are set by assigning a value with = after the parameter name and type.
  2. Step 2: Check FastAPI query parameter defaults

    For simple defaults, just use limit: int = 10. Using Query() is optional for extra validation.
  3. Final Answer:

    def read_items(limit: int = 10): -> Option A
  4. Quick Check:

    Default value syntax = param: type = value [OK]
Hint: Use param: type = default for simple defaults [OK]
Common Mistakes:
  • Misplacing Query() without import or wrong syntax
  • Using Query without type annotation
  • Missing = sign for default assignment
3. Consider this FastAPI endpoint code:
from fastapi import FastAPI
app = FastAPI()

@app.get("/items/")
async def read_items(skip: int = 0, limit: int = 5):
    return {"skip": skip, "limit": limit}

What will be the JSON response when a client calls /items/ without any query parameters?
medium
A. {"skip": "0", "limit": "5"}
B. {"skip": null, "limit": null}
C. Error: missing required parameters
D. {"skip": 0, "limit": 5}

Solution

  1. Step 1: Identify default values for parameters

    Both skip and limit have default values: 0 and 5 respectively.
  2. Step 2: Understand behavior when no query parameters sent

    FastAPI uses default values when parameters are missing, so skip=0 and limit=5 are used.
  3. Final Answer:

    {"skip": 0, "limit": 5} -> Option D
  4. Quick Check:

    Defaults used when no query params [OK]
Hint: No query params? Defaults fill in automatically [OK]
Common Mistakes:
  • Expecting null instead of default values
  • Confusing string vs integer in response
  • Assuming error if parameters missing
4. What is wrong with this FastAPI endpoint code?
from fastapi import FastAPI
app = FastAPI()

@app.get("/users/")
def get_users(limit: int = Query(10)):
    return {"limit": limit}
medium
A. Missing import for Query
B. Default value must be a constant, not Query()
C. Function must be async
D. Query() cannot be used for default values

Solution

  1. Step 1: Check imports for Query

    The code uses Query(10) but does not import Query from fastapi.
  2. Step 2: Understand effect of missing import

    Without importing Query, Python raises a NameError because Query is undefined.
  3. Final Answer:

    Missing import for Query -> Option A
  4. Quick Check:

    Use from fastapi import Query if using Query() [OK]
Hint: Always import Query when using Query() defaults [OK]
Common Mistakes:
  • Forgetting to import Query
  • Thinking Query() is invalid default
  • Assuming async required for all endpoints
5. You want to create a FastAPI endpoint that accepts an optional query parameter category with a default value of "all". However, if the client sends an empty string "", you want to treat it as None (no category filter). Which approach correctly implements this behavior?
hard
A. def read_items(category: Optional[str] = None): if category is None: category = "all" return {"category": category}
B. def read_items(category: str = Query(default="all", min_length=1)): return {"category": category}
C. def read_items(category: str = "all"): if category == "": category = None return {"category": category}
D. def read_items(category: str = Query(default="all")): if category == "all": category = None return {"category": category}

Solution

  1. Step 1: Understand the requirement for empty string handling

    The parameter should default to "all" but treat empty string "" as None.
  2. Step 2: Analyze each option's logic

    def read_items(category: str = "all"): if category == "": category = None return {"category": category} sets default to "all" and explicitly checks if category is "", then sets it to None, matching the requirement.
  3. Final Answer:

    def read_items(category: str = "all"): if category == "": category = None return {"category": category} -> Option C
  4. Quick Check:

    Check empty string and convert to None manually [OK]
Hint: Check for empty string and convert to None inside function [OK]
Common Mistakes:
  • Relying on Query() to handle empty string conversion
  • Setting default None but not handling empty string
  • Confusing default "all" with None logic
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