String validation helps make sure the text data you get is the right size and format. This stops errors and keeps your app safe.
String validation (min, max, regex) in FastAPI
from pydantic import BaseModel, constr class User(BaseModel): name: constr(min_length=3, max_length=20, regex=r'^[a-zA-Z]+$')
constr is used to add string rules like minimum length, maximum length, and regex pattern.
The regex pattern must be a raw string (start with r') to avoid errors.
from pydantic import BaseModel, constr class User(BaseModel): username: constr(min_length=5, max_length=15)
from pydantic import BaseModel, constr class User(BaseModel): code: constr(regex=r'^\d{4}$')
from pydantic import BaseModel, constr class User(BaseModel): password: constr(min_length=8, regex=r'^(?=.*[A-Z])(?=.*\d).+$')
This FastAPI app defines a User model with a username that must be 3-12 characters long and only contain letters, numbers, or underscores. When you send a POST request to /users/ with a valid username, it confirms the username is valid.
from fastapi import FastAPI from pydantic import BaseModel, constr from fastapi.responses import JSONResponse app = FastAPI() class User(BaseModel): username: constr(min_length=3, max_length=12, regex=r'^[a-zA-Z0-9_]+$') @app.post('/users/') async def create_user(user: User): return JSONResponse(content={"message": f"User '{user.username}' is valid!"})
If validation fails, FastAPI automatically returns a clear error message to the client.
Use regex carefully to avoid overly complex patterns that are hard to read.
Always test your validation rules with different inputs to be sure they work as expected.
Use constr from Pydantic to add string validation rules in FastAPI models.
You can set minimum and maximum length and check patterns with regex.
FastAPI handles errors automatically if input does not match the rules.
Practice
constr function in FastAPI's Pydantic models help you do?Solution
Step 1: Understand
constrpurposeconstris a Pydantic type used to validate string fields with constraints like length and regex.Step 2: Compare options
Only Validate string fields with rules like minimum length, maximum length, and regex patterns correctly describesconstrusage for string validation.Final Answer:
Validate string fields with rules like minimum length, maximum length, and regex patterns -> Option AQuick Check:
constr = string validation [OK]
- Confusing constr with integer validation
- Thinking constr manages database or docs
- Assuming constr auto-generates API docs
Solution
Step 1: Recall correct syntax for constr
The correct parameters aremin_lengthandmax_lengthinsideconstr().Step 2: Check options
Only name: constr(min_length=3, max_length=10) usesconstr(min_length=3, max_length=10)correctly. Options A, B, and D use wrong parameter names or types.Final Answer:
name: constr(min_length=3, max_length=10) -> Option CQuick Check:
Use min_length and max_length in constr [OK]
- Using min and max instead of min_length and max_length
- Trying to add length constraints directly to str type
- Mixing parameter names
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')?Solution
Step 1: Analyze regex pattern
The regexr'^[a-zA-Z]+$'allows only letters, no digits.Step 2: Check input username
Input 'abc123' contains digits '123', violating the regex.Final Answer:
Validation error because username contains digits -> Option DQuick Check:
Regex restricts digits, so error occurs [OK]
- Ignoring regex and only checking length
- Assuming digits are allowed by regex
- Confusing length errors with pattern errors
from pydantic import BaseModel, constr
class Item(BaseModel):
code: constr(min_length=5, max=10)Solution
Step 1: Check parameter names in constr
The correct parameter for maximum length ismax_length, notmax.Step 2: Identify error in code
Usingmax=10causes a syntax or validation error because it's invalid.Final Answer:
max should be max_length to specify maximum string length -> Option BQuick Check:
Use max_length, not max, in constr [OK]
- Using max instead of max_length
- Confusing min_length with min
- Thinking constr is for int fields
password that must be between 8 and 16 characters and include at least one digit. Which is the correct way to define it?Solution
Step 1: Check length parameters
Usemin_length=8andmax_length=16inconstrfor length limits.Step 2: Verify regex for digit inclusion
The regexr'^(?=.*\\d).+$'ensures at least one digit is present.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 invalidminandmax. password: str(min_length=8, max_length=16, regex=r'^(?=.*\\d).+$') wrongly applies regex tostrtype.Final Answer:
password: constr(min_length=8, max_length=16, regex=r'^(?=.*\\d).+$') -> Option AQuick Check:
Use constr with min_length, max_length, and digit regex [OK]
- Using min and max instead of min_length and max_length
- Using regex that excludes digits
- Trying to add regex to plain str type
Ready to prove it?
Pass the test and this pattern moves unknown
