This chatbot API example shows how to build a small Python chat endpoint with FastAPI, accept JSON messages, validate requests and return a reply. You can test it without purchasing model credits, then connect a language model once the interface works. The example focuses on the API itself rather than building an entire chatbot interface.
If you choose Google as your model provider, start with our guide on getting a Gemini API key.
If you use Anthropic as your model provider, consult our Claude API keys guide.
If your application needs programmatic access to document notebooks rather than a generic model endpoint, consult our NotebookLM API guide.
If an existing chatbot depends on the retired Assistants endpoints, follow our OpenAI Assistants API migration guide.
If you need to connect the endpoint to a hosted OpenAI model, see our OpenAI API platform guide.
For the wider context of model interfaces and application-level validation, see our AI API guide.
When a hosted model request fails, use our OpenAI API status and troubleshooting guide.
For an example of combining recorded-audio transcription with a text-model request, see our ChatGPT and Whisper API guide.
To learn the underlying response logic before exposing it through an endpoint, see our Python chatbot code guide.
What does a chatbot API request look like?
A chatbot API accepts a message or conversation context and returns an answer. The application controls the request format, input validation, model configuration and access permissions. A model API is the separate service that performs language generation. You can build your own chat endpoint around a hosted model or a local inference server.
This example uses a POST request to /chat with a JSON object containing a bounded list of messages. Each message has a role and content. The first version returns a deterministic demonstration reply so you can test the API without a model key or paid request.
{"messages": [{"role": "user", "content": "Hello"}]}
{"reply": "Demo: Hello"}
For the broader design of a chatbot, including knowledge retrieval and human escalation, see our generative AI chatbot development guide.
Set up a local Python project
Create an empty folder, set up a virtual environment and install FastAPI, an ASGI server and the testing dependencies. On macOS or Linux:
python3 -m venv .venv
source .venv/bin/activate
python -m pip install fastapi uvicorn httpx pytest
On Windows PowerShell, activate the environment with .venv\Scripts\Activate.ps1. The example targets modern Python with built-in generic type annotations and Pydantic 2. Record the tested package versions before deployment.
Build the chat endpoint
Save the following in app.py. The role restriction prevents clients from directly submitting a system or developer instruction as a message role. Pydantic checks the input structure and length; application code rejects whitespace-only content and requests that do not end with a user message.
from typing import Literal
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
app = FastAPI()
class Message(BaseModel):
role: Literal["user", "assistant"]
content: str = Field(min_length=1, max_length=1000)
class ChatRequest(BaseModel):
messages: list[Message] = Field(min_length=1, max_length=12)
@app.post("/chat")
def chat(req: ChatRequest):
if req.messages[-1].role != "user":
raise HTTPException(400, "Last message must be from user")
if any(not m.content.strip() for m in req.messages):
raise HTTPException(400, "Empty message")
return {"reply": "Demo: " + req.messages[-1].content}
The response is intentionally a demonstration, not an AI answer. These basic validations do not prevent prompt injection inside user text or establish the truth of an assistant message supplied by a client. In a production system, retrieve authoritative conversation history from an authenticated server-side store.
Run the server and send a request
Start the local server, binding it to the loopback interface. This endpoint has no authentication and should not be exposed publicly.
python -m uvicorn app:app --host 127.0.0.1 --port 8000
In a second terminal, send an example request. The following curl syntax is for a POSIX-style shell; Windows users can use the interactive API documentation at 127.0.0.1:8000/docs instead.
curl -X POST http://127.0.0.1:8000/chat \
-H 'Content-Type: application/json' \
-d '{"messages":[{"role":"user","content":"Hello"}]}'
The expected response is the JSON demonstration reply shown above. Try changing the message content. Submitting an empty message list should return a validation error with HTTP status 422.
Test valid and invalid requests
FastAPI’s TestClient can exercise the endpoint without running a network server. Save this as test_app.py alongside app.py.
from fastapi.testclient import TestClient
from app import app
client = TestClient(app)
def test_valid_message():
result = client.post("/chat", json={
"messages": [{"role": "user", "content": "Hello"}]
})
assert result.status_code == 200
assert result.json() == {"reply": "Demo: Hello"}
def test_invalid_messages():
cases = [
([], 422),
([{"role": "system", "content": "Hi"}], 422),
([{"role": "assistant", "content": "Hi"}], 400),
([{"role": "user", "content": " "}], 400),
]
for messages, expected in cases:
result = client.post("/chat", json={"messages": messages})
assert result.status_code == expected
Run python -m pytest -q. Guilds AI executed the equivalent five request cases locally using TestClient: all five returned their expected status codes (200, 422, 422, 400, 400), and the valid request returned the expected reply. No paid model call was made. These tests establish basic endpoint behavior, not model quality or production security.
Connect the endpoint to a language model
Once the request contract works, replace the demonstration reply with a server-side model adapter. Choose a model available to your account and configure it on the server. The adapter translates your validated messages into the provider’s request format and extracts the returned text. Keep your provider credentials in a server-side secret store or environment variable, not in the browser or the JSON request.
A real provider call can fail because of network errors, usage limits, unavailable models or exhausted billing capacity. Configure timeouts and bounded retries, and return an appropriate error without leaking credentials or raw upstream diagnostics. Limit output tokens and total input size based on the chosen model. A message-count limit alone does not establish a token budget.
If you operate the model yourself, our LLM serving guide explains how inference infrastructure handles concurrent requests. For managed APIs, read the provider’s current API reference and data-handling terms before sending real information.
What changes before production?
Require authentication and check that a conversation belongs to the requesting user. Prefer server-controlled conversation history and fixed or allow-listed model settings rather than trusting every field received from a browser. Apply per-user quotas, body-size limits, concurrency controls and budgets.
Treat retrieved documents and user content as untrusted input. Any connected tool needs independent authorization and validated arguments. Protect stored conversations and avoid recording confidential prompts in ordinary logs. The generative AI API data security guide covers retention, encryption and access controls.
Finally, test realistic model answers using independently reviewed examples, track latency and failures, and decide when to show a fallback or escalate. Streaming and persistent memory can improve the user experience, but add them only after the basic request and authorization boundaries are reliable.
Frequently asked questions
Is a chatbot API the same as an LLM API? Not necessarily. Your chatbot endpoint may add validation, conversation state and business logic around one or more model APIs.
Can I test a chatbot API without an API key? Yes. A deterministic or mocked model adapter lets you test request handling locally. Actual model generation requires a suitable local model or authorized provider access.
Does the API automatically remember earlier messages? No. Your application must send relevant history, retrieve saved context, or use an approved provider-managed conversation mechanism.
Can I publish this example as a public API? Not as written. Add authentication, access controls, request limits, operational monitoring and appropriate data protection first.

