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?
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}
Think about how Pydantic validates string length constraints.
FastAPI uses Pydantic to validate input data. If the string is shorter than the min_length, Pydantic raises a validation error. FastAPI returns a 422 error with details.
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).
Remember that constr is used for constrained strings in Pydantic.
The constr type accepts a regex parameter to enforce patterns. Using str with regex or pattern is invalid.
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?
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}
Consider how Pydantic handles max_length violations.
Pydantic raises a validation error if the string exceeds max_length. FastAPI returns a 422 error with details about the violation.
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?
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}
Think about how Pydantic enforces validation rules.
Using str alone does not enforce any constraints. To validate length or regex, use constr with parameters.
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?
Recall how FastAPI integrates with Pydantic for validation.
Pydantic performs validation and raises ValidationError on failure. FastAPI catches this and returns a 422 response with detailed error messages.