Routing and HTTP methods
Create your first FastAPI app and run it locally. Python examples show path parameters, route ordering, and GET, POST, PUT, and DELETE.
A web API in one minute#
A client sends an HTTP request. Your path function reads input and returns data. FastAPI validates input, runs your function, turns the result into JSON, and documents the contract.
python -m pip install "fastapi[standard]"
fastapi dev main.py # local reload
fastapi run main.py # production server
# Browse /docs (Swagger UI), /redoc, /openapi.json
from fastapi import FastAPI
app = FastAPI(title="Bookshop API")
@app.get("/books/{book_id}")
def read_book(book_id: int, preview: bool = False):
return {"book_id": book_id, "preview": preview}
# GET /books/42?preview=true → 200 JSON
# GET /books/oops → 422 validation error
A path operation is a function registered with a URL and HTTP method. Type hints drive validation and OpenAPI documentation. Use /docs to send test requests.
Routing and HTTP methods#
Use GET to read, POST to create, PUT to replace, PATCH to change part of a resource, and DELETE to remove. Route order matters for overlapping paths.
from fastapi import FastAPI, HTTPException, status
app = FastAPI()
books = {1: {"id": 1, "title": "Dune"}}
@app.get("/books/latest") # fixed path before /books/{id}
def latest():
return books[1]
@app.get("/books/{book_id}")
def get_book(book_id: int):
if book_id not in books:
raise HTTPException(404, detail="Book not found")
return books[book_id]
@app.post("/books", status_code=status.HTTP_201_CREATED)
def create_book(title: str):
book_id = max(books, default=0) + 1
books[book_id] = {"id": book_id, "title": title}
return books[book_id]
@app.delete("/books/{book_id}", status_code=204)
def delete_book(book_id: int):
if books.pop(book_id, None) is None:
raise HTTPException(404, "Book not found")
curl -i http://127.0.0.1:8000/books/1
curl -i -X POST 'http://127.0.0.1:8000/books?title=Dune'
curl -i -X DELETE http://127.0.0.1:8000/books/1
# That POST uses a query parameter; later, a Pydantic model
# moves structured data into a JSON request body.
| Result | Code | Meaning |
|---|---|---|
| Successful GET / PUT / PATCH | 200 | JSON result |
| Created | 201 | New resource |
| Deleted with no body | 204 | No response body |
| Bad request data | 422 | FastAPI input validation |
| Missing record | 404 | Your handler must raise this |
| Not authenticated / forbidden | 401 / 403 | Login required / insufficient rights |
Use status_code=204 only for responses without a body. Input conversion errors return 422 before the handler runs.
Help improve CodeRef
Allow Google Analytics to measure page visits and use of the guides? It uses cookies after you accept. Your choice won’t affect access to the site. Privacy notice