Skip to content
IT Vizag
← Production Python

▶ 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

Lesson 7 of 10 · 3 min read

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:

🔒 Code example: sign up free (above) to unlock it.

The API

main.py:

🔒 Code example: sign up free (above) to unlock it.

What's protecting you

  • Input validation: max_length=2000 stops 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

🔒 Code example: sign up free (above) to unlock it.

Fast, free and reliable, because the AI call is replaced.

Tip: Version your endpoint (/v1/classify). When you change the output shape later, apps using v1 keep working while new apps move to v2.

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.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend