Bird
Raised Fist0
FastAPIframework~20 mins

Basic query parameter declaration in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
FastAPI Query 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 accessing the endpoint with ?q=hello?

Consider this FastAPI endpoint:

from fastapi import FastAPI

app = FastAPI()

@app.get("/items/")
async def read_items(q: str):
    return {"query": q}

What will the response be when you visit /items/?q=hello?

FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/items/")
async def read_items(q: str):
    return {"query": q}
A{"query": null}
B{"query": "hello"}
C{"error": "Missing query parameter"}
D{"query": "q=hello"}
Attempts:
2 left
💡 Hint

Query parameters are passed after the ? in the URL and matched by name.

📝 Syntax
intermediate
2:00remaining
Which option correctly declares an optional query parameter with a default value?

In FastAPI, how do you declare a query parameter q that is optional and defaults to None?

Aasync def read_items(q: Optional[str]):
Basync def read_items(q: str):
Casync def read_items(q: str = None):
Dasync def read_items(q: str = ''):
Attempts:
2 left
💡 Hint

Optional parameters need a default value in Python function definitions.

❓ state_output
advanced
2:00remaining
What is the output when no query parameter is provided?

Given this FastAPI endpoint:

from fastapi import FastAPI

app = FastAPI()

@app.get("/search/")
async def search_items(q: str = "default"):
    return {"query": q}

What will be the response when you visit /search/ without any query parameters?

FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/search/")
async def search_items(q: str = "default"):
    return {"query": q}
A{"query": "default"}
B{"error": "Missing query parameter"}
C{"query": null}
D{"query": ""}
Attempts:
2 left
💡 Hint

Default values are used when no value is provided.

🔧 Debug
advanced
2:00remaining
Which option causes a runtime error when calling the endpoint?

Consider these FastAPI endpoint definitions. Which one will cause a runtime error when accessed without query parameters?

Aasync def get_data(q: Optional[str]): return {"q": q}
Basync def get_data(q: str = None): return {"q": q}
Casync def get_data(q: str = ""): return {"q": q}
Dasync def get_data(q: str): return {"q": q}
Attempts:
2 left
💡 Hint

Check if the parameter has a default value or is optional.

🧠 Conceptual
expert
3:00remaining
How does FastAPI handle multiple query parameters with the same name?

Given this endpoint:

from fastapi import FastAPI
from typing import List

app = FastAPI()

@app.get("/items/")
async def read_items(q: List[str] = []):
    return {"queries": q}

What will be the output when the URL is /items/?q=foo&q=bar&q=baz?

FastAPI
from fastapi import FastAPI
from typing import List

app = FastAPI()

@app.get("/items/")
async def read_items(q: List[str] = []):
    return {"queries": q}
A{"queries": []}
B{"queries": "foo,bar,baz"}
C{"queries": ["foo"]}
D{"queries": ["foo", "bar", "baz"]}
Attempts:
2 left
💡 Hint

FastAPI can collect multiple query parameters with the same name into a list.

Practice

(1/5)
1. In FastAPI, how do you declare a query parameter that is optional with a default value?
easy
A. By importing Query from fastapi and not setting a default value
B. By using a special decorator like @query_param
C. By defining the parameter inside the request body
D. By adding a function parameter with a default value, e.g., def read_item(q: str = None)

Solution

  1. Step 1: Understand query parameter declaration

    In FastAPI, query parameters are declared as function parameters in path operation functions.
  2. Step 2: Recognize optional parameters

    If a parameter has a default value (like None), it becomes optional and is treated as a query parameter.
  3. Final Answer:

    By adding a function parameter with a default value, e.g., def read_item(q: str = None) -> Option D
  4. Quick Check:

    Optional query param = default value [OK]
Hint: Optional query params have default values in function signature [OK]
Common Mistakes:
  • Thinking a decorator is needed for query params
  • Confusing query params with request body
  • Not setting a default value makes param required
2. Which of the following is the correct syntax to declare a required query parameter named item_id of type int in FastAPI?
easy
A. def read_item(item_id: int):
B. def read_item(item_id):
C. def read_item(item_id: str = 'default'):
D. def read_item(item_id: int = None):

Solution

  1. Step 1: Identify required query parameter syntax

    A required query parameter has no default value and must have a type annotation.
  2. Step 2: Check each option

    def read_item(item_id: int): declares item_id as an int without a default, making it required.
  3. Final Answer:

    def read_item(item_id: int): -> Option A
  4. Quick Check:

    Required param = no default value [OK]
Hint: No default means required query param [OK]
Common Mistakes:
  • Setting default None makes param optional
  • Using wrong type annotation
  • Omitting type annotation makes param a path param
3. What will be the output if you call the FastAPI endpoint defined as below without any query parameters?
from fastapi import FastAPI
app = FastAPI()

@app.get('/items/')
def read_items(q: str = 'default'):
    return {'q': q}
medium
A. {'q': None}
B. Error: missing required query parameter
C. {'q': 'default'}
D. {'q': ''}

Solution

  1. Step 1: Analyze the function parameter

    The parameter q has a default value of 'default', so it is optional.
  2. Step 2: Understand the call without query params

    When no query parameter is provided, FastAPI uses the default value 'default'.
  3. Final Answer:

    {'q': 'default'} -> Option C
  4. Quick Check:

    Default value used when query param missing [OK]
Hint: Default param value is returned if query missing [OK]
Common Mistakes:
  • Expecting None instead of default
  • Thinking missing param causes error
  • Assuming empty string is default
4. Identify the error in this FastAPI query parameter declaration:
from fastapi import FastAPI
app = FastAPI()

@app.get('/users/')
def get_user(user_id: int = None):
    return {'user_id': user_id}
medium
A. Default value None is invalid for int type without Optional
B. No error, this is a valid optional query parameter
C. Type hint should be Optional[int] from typing
D. Query parameter must be declared with Query()

Solution

  1. Step 1: Check parameter declaration

    Declaring user_id: int = None makes it optional with default None.
  2. Step 2: Verify FastAPI behavior

    FastAPI accepts this and treats user_id as an optional query parameter.
  3. Final Answer:

    No error, this is a valid optional query parameter -> Option B
  4. Quick Check:

    Default None with int type is allowed [OK]
Hint: Default None with int type is valid in FastAPI [OK]
Common Mistakes:
  • Assuming Optional[int] is required
  • Thinking Query() is mandatory
  • Confusing type hints with runtime errors
5. You want to declare two query parameters in FastAPI: q which is optional with default None, and limit which is required and an integer. Which is the correct function signature?
hard
A. def read_items(limit: int, q: str = None):
B. def read_items(q: str = None, limit: int):
C. def read_items(q: str, limit: int = None):
D. def read_items(q: str = None, limit: int = 10):

Solution

  1. Step 1: Understand parameter order rules

    In Python, parameters without defaults must come before those with defaults.
  2. Step 2: Apply to FastAPI query params

    limit is required (no default), so it must come before optional q with default None.
  3. Final Answer:

    def read_items(limit: int, q: str = None): -> Option A
  4. Quick Check:

    Required params before optional ones [OK]
Hint: Put required params before optional ones in function signature [OK]
Common Mistakes:
  • Placing optional param before required causes syntax error
  • Assigning default to required param
  • Mixing parameter order incorrectly
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