What is the purpose of field validation rules in FastAPI?
Field validation rules ensure that the data received in API requests meets expected formats and constraints before processing. This helps prevent errors and improves data quality.
Click to reveal answer
beginner
How do you declare a required string field with a minimum length of 3 in FastAPI using Pydantic?
Use Pydantic's Field with min_length parameter: <br><pre>from pydantic import BaseModel, Field
class Item(BaseModel):
name: str = Field(..., min_length=3)</pre>
Click to reveal answer
beginner
What does the ellipsis (...) mean when used as a default value in a Pydantic Field?
The ellipsis (...) means the field is required. FastAPI will return an error if this field is missing in the request.
Click to reveal answer
intermediate
How can you validate that an integer field is between 1 and 10 in FastAPI?
Use Field with ge (greater or equal) and le (less or equal) parameters: <br><pre>from pydantic import BaseModel, Field
class Item(BaseModel):
quantity: int = Field(..., ge=1, le=10)</pre>
Click to reveal answer
advanced
How do you add a custom error message for a field validation in FastAPI?
You can add a custom error message by using Pydantic validators or by customizing the Field with constraints and error messages inside a validator function.
Click to reveal answer
In FastAPI, what does Field(..., min_length=5) mean for a string field?
AThe field is required and must have at least 5 characters
BThe field is optional and must have at least 5 characters
CThe field is required and must have exactly 5 characters
DThe field is optional and must have exactly 5 characters
✗ Incorrect
The ellipsis (...) means the field is required, and min_length=5 means it must have at least 5 characters.
Which Pydantic Field parameters enforce a number to be between 10 and 20 inclusive?
Age=10, le=20
Bmin=10, max=20
Cgt=10, lt=20
Dmin_length=10, max_length=20
✗ Incorrect
ge means greater or equal, le means less or equal, so ge=10 and le=20 enforce the number between 10 and 20 inclusive.
What happens if a required field is missing in a FastAPI request?
AFastAPI sets the field to None
BFastAPI ignores the missing field
CFastAPI returns a validation error response
DFastAPI crashes
✗ Incorrect
FastAPI returns a validation error response indicating the required field is missing.
How do you specify a default value for a field in FastAPI?
AUse Field(...)
BAssign the value directly in the model, e.g., field: str = 'default'
CUse Field(default=None)
DYou cannot specify default values
✗ Incorrect
Assigning a value directly in the model sets a default value for that field.
Which of these is NOT a valid Pydantic Field constraint?
Amin_length
Bmax_length
Cge
Dmax_value
✗ Incorrect
max_value is not a valid Pydantic Field constraint; use le (less or equal) instead.
Explain how to use FastAPI and Pydantic to validate that a string field is required and has a minimum length.
Think about how you tell FastAPI a field must be there and how long it should be.
You got /4 concepts.
Describe how to validate numeric fields in FastAPI to ensure they fall within a specific range.
Consider how to say a number must be between two values.
You got /4 concepts.
Practice
(1/5)
1. What is the purpose of using Field with parameters like min_length or ge in FastAPI models?
easy
A. To validate and restrict input data before processing
B. To format the output data after processing
C. To create database tables automatically
D. To handle HTTP request routing
Solution
Step 1: Understand Field usage in FastAPI
Field is used to define extra validation rules on model fields.
Step 2: Recognize validation purpose
Parameters like min_length or ge ensure input data meets conditions before API logic runs.
Final Answer:
To validate and restrict input data before processing -> Option A
Quick Check:
Field validation = Input data check [OK]
Hint: Field with min_length or ge always validates input data [OK]
Common Mistakes:
Confusing validation with output formatting
Thinking Field creates database tables
Assuming Field controls routing
2. Which of the following is the correct way to enforce a string field to have at least 3 characters using FastAPI's Field?
easy
A. name: str = Field(length_min=3)
B. name: str = Field(min_length=3)
C. name: str = Field(min=3)
D. name: str = Field(minsize=3)
Solution
Step 1: Recall correct parameter name for minimum length
FastAPI uses min_length to set minimum string length.
Step 2: Match option with correct syntax
name: str = Field(min_length=3) uses min_length=3, which is correct syntax.
Final Answer:
name: str = Field(min_length=3) -> Option B
Quick Check:
min_length = min_length [OK]
Hint: Use min_length for strings, not min or length_min [OK]
Common Mistakes:
Using incorrect parameter names like min or length_min
Confusing min_length with min for numbers
Misspelling parameter names
3. Given this FastAPI model snippet:
from pydantic import BaseModel, Field
class User(BaseModel):
age: int = Field(ge=18, le=65)
user = User(age=70)
What will happen when creating user?
medium
A. An error is raised because age is greater than 65
B. User instance is created with age 70 without error
C. Age is automatically set to 65
D. Age is ignored and set to default 0
Solution
Step 1: Understand ge and le constraints
ge=18 means age must be >=18, le=65 means age must be <=65.
Step 2: Check provided age value
Age 70 is greater than 65, violating the le constraint.
Step 3: FastAPI/Pydantic behavior on violation
It raises a validation error when constraints are not met.
Final Answer:
An error is raised because age is greater than 65 -> Option A
Quick Check:
ge/le constraints cause error if violated [OK]
Hint: ge and le set min/max values; violation raises error [OK]
Common Mistakes:
Assuming values auto-correct to limits
Thinking invalid values are ignored
Confusing ge/le with min_length/max_length
4. Identify the error in this FastAPI model field validation:
from pydantic import BaseModel, Field
class Product(BaseModel):
code: str = Field(regex="[A-Z]{3}[0-9]{4}")
product = Product(code="abC1234")
medium
A. The code field should be an integer, not string
B. Field does not support regex parameter
C. The regex pattern is case-sensitive and input does not match
D. Missing default value for code field
Solution
Step 1: Analyze regex pattern
Pattern requires exactly 3 uppercase letters followed by 4 digits.
Step 2: Check input against pattern
Input "abC1234" has lowercase letters and does not fully match pattern.
Step 3: Understand validation result
Regex is case-sensitive by default, so input fails validation causing error.
Final Answer:
The regex pattern is case-sensitive and input does not match -> Option C
Quick Check:
Regex is case-sensitive unless flagged [OK]
Hint: Regex in Field is case-sensitive by default [OK]
Common Mistakes:
Assuming regex ignores case without flags
Thinking Field does not accept regex
Confusing data types for fields
5. You want to create a FastAPI model for a username that must be 5 to 10 characters long, only letters and digits allowed, and must start with a letter. Which Field validation is correct?
hard
A. username: str = Field(min_length=5, max_length=10, regex='^[0-9][a-zA-Z0-9]*$')
B. username: str = Field(min_length=5, max_length=10, regex='^[a-zA-Z]{5,10}$')
C. username: str = Field(min_length=5, max_length=10, regex='^[a-zA-Z0-9]{5,10}$')
D. username: str = Field(min_length=5, max_length=10, regex='^[a-zA-Z][a-zA-Z0-9]*$')
Solution
Step 1: Check length constraints
min_length=5 and max_length=10 ensure username length between 5 and 10.
Step 2: Analyze regex pattern
Regex '^[a-zA-Z][a-zA-Z0-9]*$' means username starts with a letter, followed by letters or digits.
Step 3: Verify other options
Options starting with a digit are incorrect. Options using regex '^[a-zA-Z0-9]{5,10}$' allow starting with digits. Options using '^[a-zA-Z]{5,10}$' exclude digits.
Final Answer:
username: str = Field(min_length=5, max_length=10, regex='^[a-zA-Z][a-zA-Z0-9]*$') -> Option D