FastAPI / Chapter 1 of 8

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.

2 topicsUpdated
01 / 28

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.

RouteA URL and an HTTP method choose the Python function.
RequestPath, query, body, headers, cookies, or files supplied by the client.
ResponseA status code, headers, and usually JSON sent back.
Client request→Route + validation→Python function→JSON response
ShellInstall and start
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
Pythonmain.py — complete first app
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
Path operations

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.

02 / 28

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.

PythonPath operations, order, and status codes
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")
ShellTry the API
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.
ResultCodeMeaning
Successful GET / PUT / PATCH200JSON result
Created201New resource
Deleted with no body204No response body
Bad request data422FastAPI input validation
Missing record404Your handler must raise this
Not authenticated / forbidden401 / 403Login required / insufficient rights
Status codes

Use status_code=204 only for responses without a body. Input conversion errors return 422 before the handler runs.