Request and response models

Deploying AI into Production with FastAPI

Matt Eckerle

Software and Data Engineering Leader

Request and response structures in APIs

Request structure
  • Data sent by the client to the API
  • Typically includes:
    • HTTP method (GET, POST, etc.)
    • Headers
    • Query parameters
    • Request body

http://localhost:8000/users/? [email protected]

  • :8000: The port number. FastAPI typically uses 8000 by default.
  • /users/: The path to the specific endpoint we're accessing.
  • ?: Indicates the start of the query parameters.
  • `[email protected]`: The query parameter. In this case, we're passing an email address to the endpoint.
Deploying AI into Production with FastAPI

Response structure

  • Data sent back by the API to the client
    • JSON response payload with user information
  • Typically includes:
    • Status code (200 OK, 404 Not Found, etc.)
    • Headers
    • Response body (data requested or operation result)
HTTP/1.1 200 OK
date: Fri, 18 Oct 2024 12:34:56 GMT
server: uvicorn
content-length: 76
content-type: application/json

{
  "username": "johndoe",
  "email": "[email protected]",
  "age": 30
}
Deploying AI into Production with FastAPI

Pydantic model

  • Creation of User
  • Use of Pydantic
from pydantic import BaseModel
class User(BaseModel):
    username: str
    email: str
    age: int
  • Inherits from BaseModel
  • Defines attributes with type annotations
  • Automatic validation based on types
Deploying AI into Production with FastAPI

Validation error

from pydantic import ValidationError
try:
    invalid_user = User(username="john_doe", email="[email protected]", 
                        age="thirty")
    print("Invalid User:", invalid_user)
except ValidationError as e:
    print("Validation Error:", e)
Validation Error: 1 validation error for User age
Input should be a valid integer, unable to parse string as an integer 
[type=int_parsing, input_value='thirty', input_type=str]
Deploying AI into Production with FastAPI

Using Pydantic models in FastAPI

from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()

class User(BaseModel): username: str email: str age: int
@app.post("/users", response_model=User)
async def create_user(user: User): return user
  • Model used as response_model
  • Model used as parameter type hint
  • Automatic request validation
  • De/serialization of request/response
  • Generate API docs
Deploying AI into Production with FastAPI

Request and response formats

curl -X 'POST' \
  'http://localhost:8000/users/' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "username": "john_doe",
  "email": "[email protected]",
  "age": 30
  }'

 

{
  "username": "john_doe",
  "email": "[email protected]",
  "age": 30
}
Deploying AI into Production with FastAPI

Let's practice!

Deploying AI into Production with FastAPI

Preparing Video For Download...