Practical outcome
You will understand the complete request-response journey and create the first endpoint for our Enterprise AI Assistant API.
Change the request and inspect the endpoint result
Start with a real product problem
You have a useful Python function that answers a question. It works on your laptop, but a web interface, mobile app or another service cannot call a function inside your local file.
A web API gives that capability a network-accessible contract. A client sends an HTTP request; the API validates it, runs Python code and returns an HTTP response.
01Web or mobile client → HTTP request → FastAPI → Python function → JSON responseFastAPI is a Python framework for building APIs using standard type hints. Those declarations power input parsing, validation, generated OpenAPI documentation and editor assistance.
The five parts of an endpoint
| Part | Example | Meaning |
|---|---|---|
| Method | GET | What kind of operation is requested |
| Path | /health | Which resource or capability |
| Input | query, path, header or JSON body | Data supplied by the client |
| Output | JSON body | Data returned by the server |
| Status | 200 OK | Machine-readable outcome |
An endpoint is not only a Python function. It is this complete public contract.
Create the first application
01python -m venv .venv02# Activate the environment, then install:03pip install "fastapi[standard]"
Create main.py:
01from fastapi import FastAPI0203app = FastAPI(04title="Enterprise AI Assistant API",05version="0.1.0",06)0708@app.get("/health")09def health_check():10return {"status": "healthy"}
Run it locally:
01fastapi dev main.pyOpen /docs to see the interactive API documentation generated from the OpenAPI contract. Use it to explore during development—not as proof that the business logic is correct.
Trace the request precisely
When the browser requests GET /health:
- The HTTP server receives the network request.
- FastAPI compares the method and path with registered routes.
- It calls
health_check(). - The returned dictionary is serialised as JSON.
- The server responds with status
200and a JSON content type.
01HTTP/1.1 200 OK02content-type: application/json0304{"status":"healthy"}
Add a path parameter
01@app.get("/documents/{document_id}")02def get_document(document_id: int):03return {04"document_id": document_id,05"title": "Employee Handbook",06}
In /documents/42, 42 is part of the resource identity. Because the annotation is int, /documents/abc is rejected before your function runs.
Add a query parameter
01@app.get("/documents")02def list_documents(limit: int = 10, department: str | None = None):03return {"limit": limit, "department": department, "items": []}
/documents?limit=5&department=hr filters or controls the collection. Query parameters are normally better for search, filtering, sorting and pagination than resource identity.
Choose the HTTP method by intent
| Method | Typical intent | AI assistant example |
|---|---|---|
GET | Read without changing state | Check health or fetch a conversation |
POST | Create or start work | Submit a question |
PUT | Replace a resource | Replace document metadata |
PATCH | Partially update | Rename a conversation |
DELETE | Remove | Delete an indexed document |
Do not use GET /ask?question=... for private prompts. URLs can appear in browser history, proxy logs and analytics. A request body is still sensitive, but it avoids placing the prompt in the URL.
Real-time analogy: a restaurant counter
The menu is the API contract
The menu lists what you can order, the name of each item and what you receive. Your order is the request. The counter routes it to the correct kitchen station. The prepared dish is the response, and the receipt communicates the outcome.
Walking into the kitchen and calling a private Python function directly would tightly couple the customer to internal operations. The counter creates a stable boundary even when the kitchen changes.
Common mistakes
Common mistakes
- Treating a route function as the complete API contract.
- Using
GETfor operations that create data or trigger expensive AI work. - Returning
200 OKfor every outcome, including failures. - Placing API keys, tokens or private prompts in URLs.
- Assuming generated documentation replaces API tests.
Interview bit
Why use FastAPI for an AI backend?
FastAPI lets me express HTTP contracts with standard Python type hints and integrates validation, dependency injection, OpenAPI documentation and asynchronous request handling. For AI applications, it provides a clear boundary around model, RAG and agent capabilities while allowing me to validate input, stream output and secure each endpoint.
Key takeaways
Key takeaways
- An API makes a capability available through a defined network contract.
- An endpoint includes method, path, input, output, status and failure behaviour.
- Type annotations help FastAPI parse and validate incoming values.
- Paths identify resources; query parameters commonly filter or control reads.
- A health endpoint proves reachability, not full application health.
Frequently asked questions
Do I need asynchronous code for every FastAPI route? No. Use async def when the route awaits compatible non-blocking operations. A normal def route is valid for synchronous work.
Is generated API documentation a replacement for tests? No. It helps people explore the contract, while tests verify that success, validation and failure behaviour remain correct.
Should private prompts be placed in query parameters? Avoid it. URLs may appear in logs and history; use a validated request body and still treat the prompt as sensitive data.
Interactive Knowledge Check
Choose an answer, inspect the explanation and explain the idea in your own words.