FastAPI Form Validation with Pydantic
Validate form data in FastAPI using Pydantic models with custom validators, field constraints, and automatic error response generation. Includes email.
Code
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, EmailStr, field_validator
app = FastAPI()
class UserForm(BaseModel):
email: EmailStr
password: str
name: str
@field_validator('password')
@classmethod
def validate_password(cls, v):
if len(v) < 8:
raise ValueError('Password must be at least 8 characters')
if not any(c.isupper() for c in v):
raise ValueError('Password must contain uppercase')
return v
@app.post('/register')
async def register(user: UserForm):
return {'email': user.email, 'name': user.name}Inside the snippet
FastAPI Form Validation with Pydantic comes down to the class UserForm and the functions validate_password and register.
Asynchronous boundaries use await, so failures surface as exceptions at the call site rather than being swallowed. The import line is the dependency contract: FastAPI, HTTPException, BaseModel, EmailStr, field_validator come from fastapi and nothing else. When the guard condition holds, ValueError is thrown rather than a bogus value returned.
What comes back is a new object, not a reference to anything passed in.
Watch out for
- Dependency check:
fastapiandpydantic— not built-in, must be present in the project. - The guard
len(v) < 8short-circuits the flow with an earlyraisewhen its condition holds.
Putting it to use
The main signature reads def validate_password(cls, v)
validate_password is the public entry point; everything else in the file exists to support it.
Core lines
return {'email': user.email, 'name': user.name}
def validate_password(cls, v):
if len(v) < 8:
raise ValueError('Password must be at least 8 characters')
if not any(c.isupper() for c in v):
raise ValueError('Password must contain uppercase')
return v
Interactive Tools for This Topic
FAQ
- Does `validate_password` modify its input?
- The input survives unchanged; what you get back is a newly constructed value.
- How are precondition violations signaled?
- The code refuses to continue: `ValueError` is thrown while the state is still recoverable.
- What does this need from the package registry?
- These are real dependencies: `fastapi` and `pydantic`. Without them the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.