Challenge - 5 Problems
FastAPI Field Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2:00remaining
What is the output of this FastAPI endpoint with constrained fields?
Consider this FastAPI model and endpoint. What will be the response when sending {"age": 25, "name": "Anna"}?
FastAPI
from fastapi import FastAPI from pydantic import BaseModel, Field app = FastAPI() class User(BaseModel): name: str = Field(min_length=3, max_length=10) age: int = Field(gt=18, lt=30) @app.post("/user") async def create_user(user: User): return {"message": f"User {user.name} aged {user.age} created"}
Attempts:
2 left
💡 Hint
Check the constraints on name and age fields carefully.
✗ Incorrect
The name "Anna" has length 4, which is between 3 and 10. The age 25 is greater than 18 and less than 30. So the input passes validation and the endpoint returns the success message.
📝 Syntax
intermediate1:30remaining
Which option correctly defines a constrained string field in FastAPI?
You want a string field 'title' that must be at least 5 characters and at most 20 characters. Which code snippet is correct?
Attempts:
2 left
💡 Hint
Look for the correct parameter names for string length constraints in Pydantic Field.
✗ Incorrect
The correct parameters for string length constraints are min_length and max_length. Other options use invalid parameter names.
🔧 Debug
advanced2:00remaining
Why does this FastAPI model raise a validation error for input {"score": 101}?
Given this model, why does sending {"score": 101} cause a validation error?
FastAPI
from pydantic import BaseModel, Field class Result(BaseModel): score: int = Field(ge=0, le=100)
Attempts:
2 left
💡 Hint
Check the meaning of ge and le parameters in Field.
✗ Incorrect
The parameters ge=0 and le=100 mean the value must be between 0 and 100 inclusive. 101 is outside this range, so validation fails.
❓ state_output
advanced2:00remaining
What is the value of 'user' after parsing this input with the model?
Given this model and input, what will be the value of the 'user' variable?
FastAPI
from pydantic import BaseModel, Field class User(BaseModel): username: str = Field(min_length=3, max_length=8) active: bool = Field(default=True) input_data = {"username": "bob"} user = User(**input_data)
Attempts:
2 left
💡 Hint
Check the default value of the 'active' field.
✗ Incorrect
The 'active' field has a default value of True, so if not provided, it will be set to True automatically.
🧠 Conceptual
expert2:30remaining
Which statement about FastAPI field constraints is TRUE?
Select the correct statement about using Field constraints in FastAPI models.
Attempts:
2 left
💡 Hint
Think about when and how Pydantic validates data in FastAPI.
✗ Incorrect
Field constraints are enforced by Pydantic during runtime validation of incoming data, rejecting invalid inputs with errors.