📖 Scenario: You are building a simple web API using FastAPI. Your API will greet users by their name, which will be provided as a query parameter in the URL.
🎯 Goal: Create a FastAPI app that accepts a query parameter called name and returns a greeting message including that name.
📋 What You'll Learn
Create a FastAPI app instance named app
Define a GET endpoint at path /greet
Declare a query parameter named name of type str in the endpoint function
Return a dictionary with a key message and value "Hello, {name}!" where {name} is the query parameter value
💡 Why This Matters
🌍 Real World
APIs often need to accept user input via query parameters to customize responses, such as filtering data or personalizing messages.
💼 Career
Understanding how to declare and use query parameters in FastAPI is essential for backend developers building web APIs.
Progress0 / 4 steps
1
Create FastAPI app instance
Import FastAPI from fastapi and create an app instance called app.
FastAPI
Hint
Use app = FastAPI() to create the app instance.
2
Define GET endpoint at /greet
Add a GET endpoint to app with the path /greet using the @app.get("/greet") decorator. Define a function called greet with no parameters yet.
FastAPI
Hint
Use @app.get("/greet") above the function greet.
3
Add query parameter name
Modify the greet function to accept a query parameter called name of type str.
FastAPI
Hint
Add name: str inside the parentheses of the greet function.
4
Return greeting message
Return a dictionary with key message and value "Hello, {name}!" using an f-string inside the greet function.
FastAPI
Hint
Use return {"message": f"Hello, {name}!"} to send the greeting.
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
Step 1: Understand query parameter declaration
In FastAPI, query parameters are declared as function parameters in path operation functions.
Step 2: Recognize optional parameters
If a parameter has a default value (like None), it becomes optional and is treated as a query parameter.
Final Answer:
By adding a function parameter with a default value, e.g., def read_item(q: str = None) -> Option D
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
Step 1: Identify required query parameter syntax
A required query parameter has no default value and must have a type annotation.
Step 2: Check each option
def read_item(item_id: int): declares item_id as an int without a default, making it required.
Final Answer:
def read_item(item_id: int): -> Option A
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?
The parameter q has a default value of 'default', so it is optional.
Step 2: Understand the call without query params
When no query parameter is provided, FastAPI uses the default value 'default'.
Final Answer:
{'q': 'default'} -> Option C
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
Step 1: Check parameter declaration
Declaring user_id: int = None makes it optional with default None.
Step 2: Verify FastAPI behavior
FastAPI accepts this and treats user_id as an optional query parameter.
Final Answer:
No error, this is a valid optional query parameter -> Option B
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
Step 1: Understand parameter order rules
In Python, parameters without defaults must come before those with defaults.
Step 2: Apply to FastAPI query params
limit is required (no default), so it must come before optional q with default None.
Final Answer:
def read_items(limit: int, q: str = None): -> Option A
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 unknownstrongwhile earning +1 Grip toward your certificate.