Bird
Raised Fist0
FastAPIframework~20 mins

Field validation rules in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Field Validation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when a FastAPI endpoint receives invalid data for a field with a length constraint?

Consider a FastAPI model with a field defined as name: str = Field(..., min_length=3, max_length=5). What will the API response be if a client sends {"name": "Jo"}?

FastAPI
from fastapi import FastAPI
from pydantic import BaseModel, Field

app = FastAPI()

class User(BaseModel):
    name: str = Field(..., min_length=3, max_length=5)

@app.post("/users/")
async def create_user(user: User):
    return user
AThe API returns a 422 Unprocessable Entity error with a message about the name being too short.
BThe API accepts the data and returns the user object with the name "Jo".
CThe API returns a 400 Bad Request error without details.
DThe API ignores the length constraints and truncates the name to 3 characters.
Attempts:
2 left
💡 Hint

Think about how Pydantic validates fields before the endpoint logic runs.

📝 Syntax
intermediate
2:00remaining
Which option correctly applies a regex pattern validation to a FastAPI model field?

You want to ensure a field email matches a simple email pattern using FastAPI and Pydantic. Which code snippet correctly applies this validation?

Aemail: str = Field(..., regex=r"^[\w\.-]+@[\w\.-]+\.\w+$")
Bemail: str = Field(..., pattern=r"^[\w\.-]+@[\w\.-]+\.\w+$")
Cemail: str = Field(..., match=r"^[\w\.-]+@[\w\.-]+\.\w+$")
Demail: str = Field(..., validate=r"^[\w\.-]+@[\w\.-]+\.\w+$")
Attempts:
2 left
💡 Hint

Check the correct keyword argument for regex validation in Pydantic's Field.

❓ state_output
advanced
2:00remaining
What is the value of the field after validation with a default and a custom validator?

Given this FastAPI model, what will be the value of username if the client sends {} (empty JSON)?

FastAPI
from pydantic import BaseModel, Field, validator

class User(BaseModel):
    username: str = Field("guest", min_length=3)

    @validator('username')
    def uppercase_username(cls, v):
        return v.upper()
ANone
B"GUEST"
CValidationError because min_length=3 is not met
D"guest"
Attempts:
2 left
💡 Hint

Think about how default values and validators interact in Pydantic.

🔧 Debug
advanced
2:00remaining
Why does this FastAPI field validation fail with a TypeError?

Examine the code below. Why does it raise a TypeError when trying to validate the age field?

FastAPI
from pydantic import BaseModel, Field

class Person(BaseModel):
    age: int = Field(..., gt=0, lt="100")
AThe <code>age</code> field must be optional to use <code>gt</code> and <code>lt</code>.
BThe <code>gt</code> parameter cannot be used with <code>lt</code>.
CThe <code>Field</code> function does not accept <code>gt</code> or <code>lt</code> parameters.
DThe <code>lt</code> parameter must be an integer, not a string.
Attempts:
2 left
💡 Hint

Check the types of the parameters passed to Field.

🧠 Conceptual
expert
2:00remaining
Which statement about FastAPI field validation with Pydantic is true?

Choose the correct statement about how FastAPI uses Pydantic for field validation.

AField constraints like <code>min_length</code> are enforced only at runtime inside endpoint functions.
BPydantic validators run before default values are applied to fields.
CCustom validators can modify field values after built-in validations pass.
DFastAPI ignores Pydantic field validations if the request body is empty.
Attempts:
2 left
💡 Hint

Think about the order of validation and transformation in Pydantic models.

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

  1. Step 1: Understand Field usage in FastAPI

    Field is used to define extra validation rules on model fields.
  2. Step 2: Recognize validation purpose

    Parameters like min_length or ge ensure input data meets conditions before API logic runs.
  3. Final Answer:

    To validate and restrict input data before processing -> Option A
  4. 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

  1. Step 1: Recall correct parameter name for minimum length

    FastAPI uses min_length to set minimum string length.
  2. Step 2: Match option with correct syntax

    name: str = Field(min_length=3) uses min_length=3, which is correct syntax.
  3. Final Answer:

    name: str = Field(min_length=3) -> Option B
  4. 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

  1. Step 1: Understand ge and le constraints

    ge=18 means age must be >=18, le=65 means age must be <=65.
  2. Step 2: Check provided age value

    Age 70 is greater than 65, violating the le constraint.
  3. Step 3: FastAPI/Pydantic behavior on violation

    It raises a validation error when constraints are not met.
  4. Final Answer:

    An error is raised because age is greater than 65 -> Option A
  5. 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

  1. Step 1: Analyze regex pattern

    Pattern requires exactly 3 uppercase letters followed by 4 digits.
  2. Step 2: Check input against pattern

    Input "abC1234" has lowercase letters and does not fully match pattern.
  3. Step 3: Understand validation result

    Regex is case-sensitive by default, so input fails validation causing error.
  4. Final Answer:

    The regex pattern is case-sensitive and input does not match -> Option C
  5. 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

  1. Step 1: Check length constraints

    min_length=5 and max_length=10 ensure username length between 5 and 10.
  2. Step 2: Analyze regex pattern

    Regex '^[a-zA-Z][a-zA-Z0-9]*$' means username starts with a letter, followed by letters or digits.
  3. 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.
  4. Final Answer:

    username: str = Field(min_length=5, max_length=10, regex='^[a-zA-Z][a-zA-Z0-9]*$') -> Option D
  5. Quick Check:

    Start letter + length + allowed chars = username: str = Field(min_length=5, max_length=10, regex='^[a-zA-Z][a-zA-Z0-9]*$') [OK]
Hint: Start letter regex: ^[a-zA-Z], then allowed chars [OK]
Common Mistakes:
  • Allowing username to start with digit
  • Not enforcing length limits
  • Using regex that excludes digits or letters 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