Input validation in FastAPI

Deploying AI into Production with FastAPI

Matt Eckerle

Software and Data Engineering Leader

Validating input data

Flowchart showing ML prediction with FastAPI

Deploying AI into Production with FastAPI

Why validate the input?

 

  • Validation for data integrity
  • Prevent errors in the application
  • Integrates with Pydantic
  • Provided powerful tools for data validation

 

A logo of Pydantic

Deploying AI into Production with FastAPI

Pydantic for pre-defined function

Field validation using pydantic

Deploying AI into Production with FastAPI

Custom validation with pydantic

Custom validation using pydantic

Deploying AI into Production with FastAPI

Graceful error reporting

Error reporting during validation

Deploying AI into Production with FastAPI

Pydantic field validators

  • User registration endpoint

  • Validating the username entered by users:

from pydantic import BaseModel, Field
class User(BaseModel):
    username: str = Field(..., min_length=3, max_length=50)
Deploying AI into Production with FastAPI

Adding custom validators

class User(BaseModel):
    username: str = Field(..., 
                          min_length=3, 
                          max_length=50)
    age: int

@validator('age') def age_criteria(cls, age): if age < 13: raise ValueError('User must be at least 13') return age
Deploying AI into Production with FastAPI

Custom validators in action

Valid request:

{"username": "john_doe", "age": 25}
Valid user: username='john_doe' age=25

Invalid request:

{"username": "too_young", "age": 10}
Validation error for {'username': 'too_young', 'age': 10}: User must be at least 13
Deploying AI into Production with FastAPI

Putting it all together

Error reporting during validation

  • Field validator for username
  • Custom validator for age
  • Error message if failing validation
Deploying AI into Production with FastAPI

Putting it all together

@app.post("/users")
def create_user(user: User):
    return {"message": "User created",
            "user": user.dict()}

Output:

{
  "message": "User created successfully",
    "user": {
          "username": "john_doe", 
           "age": 25
    }
}
Deploying AI into Production with FastAPI

Let's practice!

Deploying AI into Production with FastAPI

Preparing Video For Download...