▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
Serving an AI model behind an API
Wrap an AI call in an endpoint with validation.
🎬 Video version coming soon — read it now
Let's combine Python Meets AI with FastAPI: an endpoint that classifies customer feedback. Any website or app can then use AI without knowing anything about models or API keys.
Why put AI behind your own API?
- The API key stays on your server, never in a website or mobile app where anyone could extract it
- You control prompts, models, limits and costs in one place
- You can validate, log and cache every request
- You can switch AI providers without changing the apps that use your API
The service
service.py, the logic, testable without the web layer:
The API
main.py:
What's protecting you
- Input validation:
max_length=2000stops someone pasting a whole novel and running up your bill - response_model: the API only ever returns the declared shape
- Typed error handling: AI failures become clean HTTP errors (503 or 502), not stack traces shown to users, and they're logged with a traceback for you
- /health: hosting platforms call it to check that your service is alive
Notice the plain def endpoint: FastAPI runs sync endpoints in a thread pool, so a slow AI call doesn't block other requests. You could also use AsyncAnthropic with async def, as in Async & Performance.
Before going public
- Rate-limit users (for example with the slowapi package) so one client can't spend your budget
- Require an API key of your own from callers, checked in a dependency
- Set a spending limit at the AI provider
- Log usage (tokens per request) without logging the private text itself
Test without the real model
Fast, free and reliable, because the AI call is replaced.
In one line
Wrap the AI call in a service, expose it through a validated FastAPI endpoint that keeps the key on the server, handle AI errors cleanly, and test with a fake.
Share with a friend