Path operations and HTTP methods

Difficulty: Beginner

Question

What are path operations in FastAPI? How do you define routes for different HTTP methods?

Answer

Path operations are functions decorated with HTTP method decorators that handle requests to specific URL paths. FastAPI provides decorators for all standard HTTP methods.

The decorators are: `@app.get()`, `@app.post()`, `@app.put()`, `@app.patch()`, `@app.delete()`, `@app.options()`, `@app.head()`, `@app.trace()`.

Each decorator takes the path as the first argument and optional parameters like `status_code`, `response_model`, `tags`, `summary`, and `description` for documentation.

Code examples

Multiple HTTP methods

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

items = {}

@app.get("/items/{item_id}")
def get_item(item_id: int):
    return items.get(item_id)

@app.post("/items", status_code=201)
def create_item(item: Item):
    items[len(items)] = item
    return item

@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
    items[item_id] = item
    return item

@app.delete("/items/{item_id}", status_code=204)
def delete_item(item_id: int):
    items.pop(item_id, None)

Key points

Concepts covered

path operations, HTTP methods, decorators, route handlers