The idea
A REST API exposes your app’s data and actions as resources at URLs: /documents, /documents/42, /documents/42/chunks. HTTP methods say what to do: GET reads, POST creates, PUT or PATCH updates, DELETE removes. Requests and responses carry JSON.
Good APIs are predictable: plural nouns for collections, IDs in the path, filters in the query string (?status=ready), consistent error shapes, and correct status codes. Version them (/v1/) so you can change them without breaking clients.
FastAPI builds REST APIs from typed Python functions and generates interactive OpenAPI docs automatically.
Your AI features reach users, frontends and other services through an API. It is the product’s front door.
Words to know
- ResourceA thing the API exposes, addressed by a URL.
- EndpointA method + path pair, like GET /documents/{id}.
- OpenAPIA standard description of an API, used for docs and clients.
Try it without code
Call a public API
- Open https://api.github.com/repos/fastapi/fastapi in a browser.
- That is a GET on a resource returning JSON.
- Look at the response headers in the browser’s developer tools.
Use it in code
A small documents API with FastAPI.
# pip install "fastapi[standard]"
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI(title="Docs API")
DOCS: dict[int, dict] = {}
class DocIn(BaseModel):
title: str
body: str
@app.post("/v1/documents", status_code=201)
def create(doc: DocIn):
doc_id = len(DOCS) + 1
DOCS[doc_id] = {"id": doc_id, **doc.model_dump()}
return DOCS[doc_id]
@app.get("/v1/documents/{doc_id}")
def get(doc_id: int):
if doc_id not in DOCS:
raise HTTPException(404, "Document not found")
return DOCS[doc_id]Add list (with ?q= search), update and delete endpoints and try them from the /docs page.
Common mistakes
- Verbs in URLs (/getDocument).
- Returning 200 with an error message in the body.