Deploying AI into Production with FastAPI
Matt Eckerle
Software and Data Engineering Leader
class Order(BaseModel):
item1: str
item2: str
item3: str
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]
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!"}
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