Skip to content
01Home 02Capability Matrix 03Tools 04Benchmark Rankings 05Tracks 06About Us
Code Under Repair · AI coverage organised as a matrix of capability × stage. Not sorted by tool, but by where you are right now.
Updated every Wednesday

Build a Python API With an LLM: A Step-by-Step Tutorial

Build your first Python LLM API in under an hour. This hands-on FastAPI tutorial covers OpenAI integration, API key security, request validation, error handling, and testing.

Nov 12, 2026
Build a Python API With an LLM: A Step-by-Step Tutorial LLM Apps & Agent Engineering

You do not need to build a complete AI application to start working with an LLM. A small Python API is enough to connect a model to your own software, accept user input, and return generated text through a standard HTTP endpoint.

In this tutorial, we will build that API with FastAPI and the OpenAI Python SDK. By the end, you will have a working POST /generate endpoint that accepts a prompt, sends it to an LLM, and returns the response as JSON.

The important part is not just making one successful API call. We will also handle input validation, keep API credentials out of source code, deal with provider errors, and test the endpoint. These are the small engineering decisions that turn a quick experiment into a useful starting point for a real application.


What We Are Building

The API will accept a request like this:

{
  "prompt": "Explain what a Python decorator does."
}

It will send the prompt to an LLM and return a response in this format:

{
  "text": "A Python decorator is a function that wraps another function..."
}

Our first version will have one endpoint, one request model, and one model-provider integration. We will deliberately keep the project small so you can understand every moving part before adding features such as conversation history, streaming, authentication, or database storage.


Step 1: Create the Python Project

Start with a new directory and create a virtual environment. Keeping dependencies isolated makes it easier to reproduce the project and avoid conflicts with other Python applications.

mkdir python-llm-api
cd python-llm-api

python -m venv .venv

# macOS / Linux
source .venv/bin/activate

# Windows PowerShell
.venv\Scripts\Activate.ps1

Install the packages:

pip install fastapi uvicorn openai python-dotenv

Each package has a specific job:

  • fastapi creates the HTTP API.

  • uvicorn runs the application locally.

  • openai provides the official Python client for the model API.

  • python-dotenv loads local environment variables from a .env file.

Create a file named .env in the project root:

OPENAI_API_KEY=your_api_key_here
OPENAI_MODEL=gpt-5.5

Replace the example key with your own API key. Do not commit this file to Git. Add it to .gitignore:

.env
.venv/
__pycache__/

Keeping credentials outside your Python source code is a basic security habit. If a key is accidentally committed or exposed, rotate it rather than assuming that deleting the file makes the old key safe.

Python project setup with environment configuration

Step 2: Create the FastAPI Application

Create main.py. We will define a request model first, then create the endpoint that handles incoming requests.

import os

from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException
from openai import AsyncOpenAI, APIError
from pydantic import BaseModel, Field

load_dotenv()

app = FastAPI(title="Python LLM API")


class GenerateRequest(BaseModel):
    prompt: str = Field(
        min_length=1,
        max_length=4000,
        description="The text sent to the language model"
    )


@app.post("/generate")
async def generate_text(request: GenerateRequest):
    api_key = os.getenv("OPENAI_API_KEY")

    if not api_key:
        raise HTTPException(
            status_code=503,
            detail="The model API is not configured."
        )

    client = AsyncOpenAI(
        api_key=api_key,
        timeout=30.0,
        max_retries=2
    )

    try:
        response = await client.responses.create(
            model=os.getenv("OPENAI_MODEL", "gpt-5.5"),
            instructions="You are a helpful and clear assistant.",
            input=request.prompt
        )

        if not response.output_text:
            raise HTTPException(
                status_code=502,
                detail="The model returned no text."
            )

        return {"text": response.output_text}

    except APIError as exc:
        raise HTTPException(
            status_code=502,
            detail="The model provider request failed."
        ) from exc

There are several decisions worth understanding here.

Why use a Pydantic request model?

Instead of accepting an unrestricted dictionary, GenerateRequest defines the shape of the incoming JSON. FastAPI uses this model to validate the request automatically. An empty prompt or a prompt longer than 4,000 characters is rejected before the model API is called.

Why use AsyncOpenAI?

FastAPI supports asynchronous endpoints. Using AsyncOpenAI lets the endpoint await the network request instead of blocking the event loop while waiting for the provider. This is a sensible default for an API that spends much of its time waiting on an external service.

Why return a generic provider error?

The API should not expose internal exception details or credentials to callers. The server can log detailed errors separately, while the client receives a controlled message. The example also sets a timeout and retry limit so the request does not wait indefinitely or retry without bounds.

FastAPI endpoint calling an OpenAI language model

Step 3: Run the API Locally

With main.py saved and your virtual environment active, start the development server:

uvicorn main:app --reload

You should see Uvicorn report that the server is running, usually at http://127.0.0.1:8000.

FastAPI also generates interactive API documentation automatically. Open:

http://127.0.0.1:8000/docs

Find the POST /generate endpoint, select "Try it out," and submit:

{
  "prompt": "Explain the difference between a list and a tuple in Python."
}

If your API key, model access, and network connection are configured correctly, the response should contain a generated answer in the text field.


Step 4: Test the Endpoint Outside the Browser

Interactive documentation is convenient, but you should also test the endpoint as another application would call it. Open a second terminal and run:

curl -X POST "http://127.0.0.1:8000/generate" \
  -H "Content-Type: application/json" \
  -d '{"prompt":"Give me three practical uses for Python APIs."}'

Check that the response is valid JSON and contains a non-empty text value. Then test invalid input:

curl -X POST "http://127.0.0.1:8000/generate" \
  -H "Content-Type: application/json" \
  -d '{"prompt":""}'

FastAPI should reject the empty prompt with a validation error instead of sending it to the model provider.

Also test the missing-key scenario by temporarily removing OPENAI_API_KEY from your environment and restarting the server. The endpoint should return the controlled configuration error. Restore the key afterward.

These tests check more than whether the model can generate text. They verify that your API handles invalid requests and configuration problems predictably.


Step 5: Understand What This First Version Does Not Solve

This is a working foundation, not a production-ready public service. Before exposing it to real users, address several important gaps:

  • Authentication: Add authentication so anonymous callers cannot freely use your model quota.

  • Rate limiting: Restrict request frequency and protect against automated abuse.

  • Usage limits: Set sensible input and output limits, and monitor provider usage and cost.

  • Logging: Record request IDs, latency, and error categories without logging API keys or unnecessary personal data.

  • Testing: Add automated tests that mock the model client so ordinary test runs do not consume API credits.

One architectural improvement is to move the model call into a separate service module when the application grows. That keeps HTTP validation and response handling separate from provider-specific logic, making it easier to test or switch model providers later.

Also remember that a successful HTTP response does not guarantee a useful answer. Model output can be incomplete, unexpected, or unsuitable for a particular task. Applications that depend on structured data should validate the output before using it.


Conclusion: Build the Smallest Working API, Then Make It Reliable

You now have the basic path from an HTTP request to an LLM response: FastAPI receives and validates input, the OpenAI Python SDK sends the request, and your endpoint returns the generated text as JSON.

The best next step is not to add five more features at once. First, run the example, test valid and invalid requests, and understand how configuration and provider errors behave. Then move the model call into a service, add automated tests, and introduce authentication and rate limits before making the API public.

A small API that you understand and can verify is a much better foundation than a complicated AI application you cannot confidently debug.

Build it. Break it. Understand it. Fix it.

Reader responses

No responses on this piece yet.

Write what you observed