GET and POST requests for AI

Deploying AI into Production with FastAPI

Matt Eckerle

Software and Data Engineering Leader

Our instructor

Matt Eckerle

Matt Eckerle

 

 

  • Software and Data Engineering Leader
  • Enterprise Data Manager at Inari
  • Using FastAPI for ML since 2019
Deploying AI into Production with FastAPI

Course overview

 

 

  • FastAPI fundamentals
  • Request handling and integration
  • Input validation and security
  • Create and maintain production-ready APIs

 

 

Logo of FastAPI

Deploying AI into Production with FastAPI

Before we start

✓ Basic python: functions, classes, modules, data structures

✓ HTTP & REST API concepts

✓ Using the FastAPI framework

  • Handling GET and POST requests
  • Using Pydantic models

✓ Machine learning basics: create, save, predict

 

The word "basics" written in chalk

Deploying AI into Production with FastAPI

GET requests explained

  • Used to retrieve data
  • Path parameter - information in URL
  • Doesn't change server state

A Menu

GET https://example.com/?item_id=1

A diagram to understand GET requests

Deploying AI into Production with FastAPI

Implementing GET with path parameters

from fastapi import FastAPI

app = FastAPI()

@app.get("/item/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}
  • `@app.get` decorator defines endpoint.
  • {item_id} is a path parameter.
  • Type hint (int) for auto validation.
Deploying AI into Production with FastAPI

POST requests explained

  • Used to send data to server
  • Data in request body (usually JSON)
  • Can change server state

A restaurant order

POST https://example.com

A diagram to understand POST requests

Deploying AI into Production with FastAPI

Implementing POST with JSON data

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()
db = {}

class Item(BaseModel): name: str price: float
@app.post("/items", status_code=201)
def create_item(item: Item): db[item.name] = item.model_dump() return {"message": f"Created {item.name}"}

 

  • Pydantic model defines data structure
  • @app.post for POST endpoint
  • Automatic JSON parsing and validation
Deploying AI into Production with FastAPI

HTTP status codes

 

  • 200 OK: Default for success
  • 404 Not Found: Resource not found
  • 201 Success: Object created

An HTTP 200 status code indicating successful request

Deploying AI into Production with FastAPI

Raising HTTP exceptions

from fastapi import FastAPI, HTTPException
app = FastAPI()

@app.get("/item/{item_id}")
async def read_item(item_id: int):
    if item_id == 42:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"item_id": item_id}

@app.post("/items") async def create_item(item: Item): # Simulating item creation return {"message": f"Created {item.name}"}, 201
Deploying AI into Production with FastAPI

Let's practice!

Deploying AI into Production with FastAPI

Preparing Video For Download...