Bird
Raised Fist0
FastAPIframework~20 mins

String validation (min, max, regex) in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
String Validation Mastery
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 a string shorter than the minimum length?

Consider this FastAPI model using Pydantic for validation:

from pydantic import BaseModel, constr

class User(BaseModel):
    username: constr(min_length=5, max_length=10)

@app.post('/user')
async def create_user(user: User):
    return {'username': user.username}

If a client sends {"username": "abc"}, what will FastAPI do?

FastAPI
from fastapi import FastAPI
from pydantic import BaseModel, constr

app = FastAPI()

class User(BaseModel):
    username: constr(min_length=5, max_length=10)

@app.post('/user')
async def create_user(user: User):
    return {'username': user.username}
AAccept the input and return the username as is
BReturn a 400 Bad Request error with a generic message
CIgnore the username field and return an empty string
DReturn a 422 Unprocessable Entity error because the string is too short
Attempts:
2 left
💡 Hint

Think about how Pydantic validates string length constraints.

📝 Syntax
intermediate
2:00remaining
Which Pydantic field declaration correctly enforces a regex pattern for a string?

Choose the correct way to declare a Pydantic model field that only accepts strings matching the pattern ^[a-z]{3}\d{2}$ (three lowercase letters followed by two digits).

Acode: username: constr(regex='^[a-z]{3}\d{2}$')
Bcode: username: str(regex='^[a-z]{3}\d{2}$')
Ccode: username: constr(pattern='^[a-z]{3}\d{2}$')
Dcode: username: str(pattern='^[a-z]{3}\d{2}$')
Attempts:
2 left
💡 Hint

Remember that constr is used for constrained strings in Pydantic.

❓ state_output
advanced
2:00remaining
What is the response when a string exceeds the max_length in a FastAPI request?

Given this Pydantic model:

class Item(BaseModel):
    code: constr(min_length=2, max_length=4)

@app.post('/items')
async def create_item(item: Item):
    return {'code': item.code}

If the client sends {"code": "ABCDE"}, what will be the HTTP status code and response?

FastAPI
from fastapi import FastAPI
from pydantic import BaseModel, constr

app = FastAPI()

class Item(BaseModel):
    code: constr(min_length=2, max_length=4)

@app.post('/items')
async def create_item(item: Item):
    return {'code': item.code}
A400 Bad Request with a generic error message
B200 OK with the code returned as "ABCDE"
C422 Unprocessable Entity with validation error about max_length
D500 Internal Server Error due to validation failure
Attempts:
2 left
💡 Hint

Consider how Pydantic handles max_length violations.

🔧 Debug
advanced
2:00remaining
Why does this FastAPI endpoint accept invalid strings despite constraints?

Examine this code snippet:

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Data(BaseModel):
    code: str

@app.post('/data')
async def post_data(data: Data):
    return {'code': data.code}

The developer wants to enforce min_length=3 and a regex pattern ^[A-Z]+$ on code, but the endpoint accepts any string. Why?

FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Data(BaseModel):
    code: str

@app.post('/data')
async def post_data(data: Data):
    return {'code': data.code}
AThe field uses plain str type without constraints, so no validation is applied
BFastAPI does not support string validation on POST requests
CThe regex pattern must be applied in the endpoint function, not the model
DThe code field is missing a default value, so validation is skipped
Attempts:
2 left
💡 Hint

Think about how Pydantic enforces validation rules.

🧠 Conceptual
expert
3:00remaining
How does FastAPI handle regex validation errors internally when using Pydantic's constr?

When a FastAPI endpoint receives a string that fails the regex validation defined by constr(regex=...), what is the internal process FastAPI follows before returning a response?

AFastAPI ignores the regex failure and returns the string as is
BPydantic raises a ValidationError, FastAPI catches it and returns a 422 response with error details
CFastAPI raises a 500 Internal Server Error due to unhandled exception
DThe regex validation is performed by FastAPI middleware, which returns a 400 error on failure
Attempts:
2 left
💡 Hint

Recall how FastAPI integrates with Pydantic for validation.

Practice

(1/5)
1. What does the constr function in FastAPI's Pydantic models help you do?
easy
A. Validate string fields with rules like minimum length, maximum length, and regex patterns
B. Create integer fields with range validation
C. Automatically generate API documentation
D. Handle database connections

Solution

  1. Step 1: Understand constr purpose

    constr is a Pydantic type used to validate string fields with constraints like length and regex.
  2. Step 2: Compare options

    Only Validate string fields with rules like minimum length, maximum length, and regex patterns correctly describes constr usage for string validation.
  3. Final Answer:

    Validate string fields with rules like minimum length, maximum length, and regex patterns -> Option A
  4. Quick Check:

    constr = string validation [OK]
Hint: Remember constr is for string validation rules [OK]
Common Mistakes:
  • Confusing constr with integer validation
  • Thinking constr manages database or docs
  • Assuming constr auto-generates API docs
2. Which of the following is the correct way to define a string field in a Pydantic model with minimum length 3 and maximum length 10?
easy
A. name: str(min_length=3, max_length=10)
B. name: constr(min=3, max=10)
C. name: constr(min_length=3, max_length=10)
D. name: str(min=3, max=10)

Solution

  1. Step 1: Recall correct syntax for constr

    The correct parameters are min_length and max_length inside constr().
  2. Step 2: Check options

    Only name: constr(min_length=3, max_length=10) uses constr(min_length=3, max_length=10) correctly. Options A, B, and D use wrong parameter names or types.
  3. Final Answer:

    name: constr(min_length=3, max_length=10) -> Option C
  4. Quick Check:

    Use min_length and max_length in constr [OK]
Hint: Use min_length and max_length, not min or max [OK]
Common Mistakes:
  • Using min and max instead of min_length and max_length
  • Trying to add length constraints directly to str type
  • Mixing parameter names
3. Given this Pydantic model snippet:
from pydantic import BaseModel, constr

class User(BaseModel):
    username: constr(min_length=4, max_length=8, regex=r'^[a-zA-Z]+$')

What happens if you try to create User(username='abc123')?
medium
A. Validation error because username is too long
B. User instance created successfully
C. Validation error because username is too short
D. Validation error because username contains digits

Solution

  1. Step 1: Analyze regex pattern

    The regex r'^[a-zA-Z]+$' allows only letters, no digits.
  2. Step 2: Check input username

    Input 'abc123' contains digits '123', violating the regex.
  3. Final Answer:

    Validation error because username contains digits -> Option D
  4. Quick Check:

    Regex restricts digits, so error occurs [OK]
Hint: Regex restricts characters; digits cause validation error [OK]
Common Mistakes:
  • Ignoring regex and only checking length
  • Assuming digits are allowed by regex
  • Confusing length errors with pattern errors
4. Identify the error in this FastAPI Pydantic model field:
from pydantic import BaseModel, constr

class Item(BaseModel):
    code: constr(min_length=5, max=10)
medium
A. code field must be an int, not constr
B. max should be max_length to specify maximum string length
C. constr cannot be used for string validation
D. min_length should be min to specify minimum length

Solution

  1. Step 1: Check parameter names in constr

    The correct parameter for maximum length is max_length, not max.
  2. Step 2: Identify error in code

    Using max=10 causes a syntax or validation error because it's invalid.
  3. Final Answer:

    max should be max_length to specify maximum string length -> Option B
  4. Quick Check:

    Use max_length, not max, in constr [OK]
Hint: Use max_length, not max, for string max length [OK]
Common Mistakes:
  • Using max instead of max_length
  • Confusing min_length with min
  • Thinking constr is for int fields
5. You want to create a FastAPI model field password that must be between 8 and 16 characters and include at least one digit. Which is the correct way to define it?
hard
A. password: constr(min_length=8, max_length=16, regex=r'^(?=.*\\d).+$')
B. password: constr(min_length=8, max_length=16, regex=r'^[a-zA-Z]+$')
C. password: constr(min=8, max=16, regex=r'^(?=.*\\d).+$')
D. password: str(min_length=8, max_length=16, regex=r'^(?=.*\\d).+$')

Solution

  1. Step 1: Check length parameters

    Use min_length=8 and max_length=16 in constr for length limits.
  2. Step 2: Verify regex for digit inclusion

    The regex r'^(?=.*\\d).+$' ensures at least one digit is present.
  3. Step 3: Validate option correctness

    password: constr(min_length=8, max_length=16, regex=r'^(?=.*\\d).+$') correctly combines length and regex. password: constr(min_length=8, max_length=16, regex=r'^[a-zA-Z]+$')'s regex disallows digits. password: constr(min=8, max=16, regex=r'^(?=.*\\d).+$') uses invalid min and max. password: str(min_length=8, max_length=16, regex=r'^(?=.*\\d).+$') wrongly applies regex to str type.
  4. Final Answer:

    password: constr(min_length=8, max_length=16, regex=r'^(?=.*\\d).+$') -> Option A
  5. Quick Check:

    Use constr with min_length, max_length, and digit regex [OK]
Hint: Use constr with min_length, max_length, and digit regex [OK]
Common Mistakes:
  • Using min and max instead of min_length and max_length
  • Using regex that excludes digits
  • Trying to add regex to plain str type
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