📖 Scenario: You are building a simple web API that returns items based on a query parameter. You want to make sure the query parameter is validated properly to avoid errors and unexpected results.
🎯 Goal: Create a FastAPI app with a GET endpoint /items/ that accepts a query parameter q. Validate that q is a string with a minimum length of 3 and a maximum length of 10 characters.
📋 What You'll Learn
Create a FastAPI app instance named app
Define a GET endpoint /items/ that accepts a query parameter q
Use FastAPI's Query to validate q with min_length=3 and max_length=10
Return a JSON response with the key query and the value of q
💡 Why This Matters
🌍 Real World
Validating query parameters is essential in web APIs to ensure clients send correct and expected data, preventing errors and improving API reliability.
💼 Career
Backend developers often use FastAPI or similar frameworks to build APIs that require input validation to maintain data integrity and security.
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
Import Query for parameter validation
Import Query from fastapi to use for query parameter validation.
FastAPI
Hint
Add Query to the import statement from fastapi.
3
Define GET endpoint with validated query parameter
Define a GET endpoint /items/ using @app.get("/items/"). Create a function read_items that accepts a query parameter q of type str. Use Query to validate q with min_length=3 and max_length=10.
FastAPI
Hint
Use Query(..., min_length=3, max_length=10) to require and validate the query parameter.
4
Complete the FastAPI app with proper async function
Ensure the endpoint function read_items is declared as async and returns a dictionary with the key query and the value of q.
FastAPI
Hint
Make sure the function is async and returns the query parameter in a dictionary.
Practice
(1/5)
1. What is the main purpose of using Query() in FastAPI for query parameters?
easy
A. To validate and enforce rules on query parameter values
B. To create new API endpoints automatically
C. To handle database connections
D. To format the response data
Solution
Step 1: Understand the role of Query()
Query() is used in FastAPI to add validation rules to query parameters, such as minimum length or value ranges.
Step 2: Identify what Query() does not do
It does not create endpoints, handle databases, or format responses; it only validates input parameters.
Final Answer:
To validate and enforce rules on query parameter values -> Option A
Quick Check:
Query() validates parameters = B [OK]
Hint: Query() is for input rules, not endpoints or data handling [OK]
Common Mistakes:
Thinking Query() creates API routes
Confusing Query() with response formatting
Assuming Query() manages database connections
2. Which of the following is the correct syntax to require a query parameter q with a minimum length of 3 in FastAPI?
easy
A. Query(q: str, min_length=3)
B. q: Query = str(min_length=3)
C. q = Query(str, min_length=3)
D. q: str = Query(min_length=3)
Solution
Step 1: Recall FastAPI query parameter syntax
In FastAPI, you declare a query parameter with its type and assign it to Query() with validation rules, e.g., q: str = Query(min_length=3).
Step 2: Check each option's syntax correctness
q: str = Query(min_length=3) matches the correct pattern. Options B, C, and D misuse type annotations or function calls.
Final Answer:
q: str = Query(min_length=3) -> Option D
Quick Check:
Correct syntax = A [OK]
Hint: Type then = Query(...) with rules inside [OK]
Common Mistakes:
Swapping type and Query() order
Calling Query() incorrectly as a function
Missing type annotation before Query()
3. Given this FastAPI endpoint code, what will be the response if the query parameter age is set to 15?
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(age: int = Query(..., ge=18)):
return {"age": age}
medium
A. {"age": 15}
B. 422 Unprocessable Entity error
C. 500 Internal Server Error
D. {"age": null}
Solution
Step 1: Understand the validation rule
The query parameter age requires a value greater or equal to 18 (ge=18).
Step 2: Check the input value against the rule
Input age=15 is less than 18, so FastAPI will reject it with a 422 validation error.
Final Answer:
422 Unprocessable Entity error -> Option B
Quick Check:
age < 18 triggers 422 error = C [OK]
Hint: ge=18 means age must be 18 or more [OK]
Common Mistakes:
Assuming invalid input returns null or default
Expecting server error instead of validation error
Ignoring validation and returning input as is
4. Identify the error in this FastAPI query parameter validation code:
A. There is no error; the code correctly requires the query parameter with min_length validation
B. min_length should be max_length
C. Query() cannot be used with strings
D. Function must be synchronous, not async
Solution
Step 1: Check if query parameter is required
Query(min_length=5) implicitly sets default=Ellipsis, making q required with string length validation.
Step 2: Understand FastAPI requirement for required params
Explicit ... is not needed; the code correctly validates required query parameters. No error.
Final Answer:
There is no error; the code correctly requires the query parameter with min_length validation -> Option A
Quick Check:
Required param needs Query(...) = A [OK]
Hint: Query(min_length=5) makes param required implicitly [OK]
Common Mistakes:
Thinking Query(min_length=5) makes param optional
Confusing min_length with max_length
Thinking async is invalid for FastAPI endpoints
5. You want to create a FastAPI endpoint that accepts a query parameter tags which must be a list of strings, each at least 2 characters long. Which is the correct way to validate this?
hard
A. tags: list[str] = Query(..., min_length=2)
B. tags: list[str] = Query(..., min_items=1, min_length=2)
C. tags: list[str] = Query(..., min_items=1), with custom validation for string length