Advanced input validation and error handling

Deploying AI into Production with FastAPI

Matt Eckerle

Software and Data Engineering Leader

Why we need advanced input

 

  • API for restaurant orders
  • Variable number of items

 

class Order(BaseModel):
    item1: str
    item2: str
    item3: str

A restaurant

Deploying AI into Production with FastAPI

Nested Pydantic models

from pydantic import BaseModel

class Foo(BaseModel):
    count: int

class Bar(BaseModel):
    foo: Foo
>>> m = Bar(foo={'count': 4})
>>> print(m)
foo=Foo(count=4)
from pydantic import BaseModel
from typing import List

class OrderItem(BaseModel): name: str quantity: int
class RestaurantOrder(BaseModel): customer_name: str items: List[OrderItem]
Deploying AI into Production with FastAPI

Custom model validators

from fastapi import FastAPI
from fastapi.exceptions import (
    RequestValidationError
)
from pydantic import (
    BaseModel,
    model_validator,
)

from typing import List class OrderItem(BaseModel): name: str quantity: int
class RestaurantOrder(BaseModel):
    customer_name: str
    items: List[OrderItem]

@model_validator(mode="after")
def validate_after(self): if len(self.items) == 0: raise RequestValidationError( "No items in order!" ) return self
{"detail":"No items in order!"}
Deploying AI into Production with FastAPI

Global exception handlers

from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
from fastapi.responses import PlainTextResponse

app = FastAPI() @app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc): msg = "Input validation error. See the documentation: http://127.0.0.1:8000/docs" return PlainTextResponse(msg, status_code=422)
Input validation error. See the documentation: http://127.0.0.1:8000/docs
Deploying AI into Production with FastAPI

Let's practice!

Deploying AI into Production with FastAPI

Preparing Video For Download...