Difficulty: Beginner
What is a path operation in FastAPI, and how do you define endpoints for GET, POST, PUT, PATCH and DELETE?
A path operation is the combination of a URL path and an HTTP method, such as GET /orders/{order_id}, plus the Python function that handles it. In FastAPI you declare one with a decorator like @app.get(), @app.post(), @app.put(), @app.patch() or @app.delete() placed on a function, which FastAPI calls the path operation function.
/orders/{order_id}. Curly braces mark path parameters.get, post, put, patch, delete, options, head and trace.status_code=201, response_model, tags, summary, dependencies and deprecated=True.| Method | Typical use | Idempotent | Common status |
|---|---|---|---|
| GET | Read a resource or list | Yes | 200 |
| POST | Create a resource or trigger an action | No | 201 |
| PUT | Replace a resource completely | Yes | 200 |
| PATCH | Update some fields | Not guaranteed | 200 |
| DELETE | Remove a resource | Yes | 204 |
Idempotent means repeating the request leaves the server in the same state. That matters for retries: a mobile client on flaky 4G can safely retry a PUT, but retrying a POST to /payments might charge a customer twice unless you use an idempotency key.
405 Method Not Allowed; if nothing matches, 404./users/me before /users/{user_id}. Otherwise me is captured as user_id and fails integer validation with a 422.status_code=201. For 204 responses, return nothing; a body with 204 is invalid HTTP.operationId. Keep handler names unique.@app.api_route("/x", methods=["GET", "HEAD"]) only when you really need it; separate handlers are clearer.Handlers are grouped with APIRouter per resource (/orders, /payments, /users) and kept thin: validate input, call a service layer, return a schema. Business rules live in services so they can be tested without HTTP.
from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price_paise: int
class ItemPatch(BaseModel):
name: str | None = None
price_paise: int | None = None
items: dict[int, Item] = {}
@app.get("/items/{item_id}")
def get_item(item_id: int) -> Item:
if item_id not in items:
raise HTTPException(status_code=404, detail="Item not found")
return items[item_id]
@app.post("/items", status_code=status.HTTP_201_CREATED)
def create_item(item: Item) -> dict:
new_id = len(items) + 1
items[new_id] = item
return {"id": new_id, **item.model_dump()}
@app.put("/items/{item_id}")
def replace_item(item_id: int, item: Item) -> Item:
items[item_id] = item # full replacement
return item
@app.patch("/items/{item_id}")
def update_item(item_id: int, patch: ItemPatch) -> Item:
stored = items[item_id]
changes = patch.model_dump(exclude_unset=True) # only fields the client sent
items[item_id] = stored.model_copy(update=changes)
return items[item_id]
@app.delete("/items/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_item(item_id: int) -> None:
items.pop(item_id, None) # 204 must not have a body
PUT replaces the whole object while PATCH uses exclude_unset to apply only the fields that were sent. DELETE returns 204 with no body.
from fastapi import FastAPI
app = FastAPI()
@app.get("/users/me") # declared first, so it wins for /users/me
def read_me():
return {"user": "current user"}
@app.get("/users/{user_id}")
def read_user(user_id: int):
return {"user_id": user_id}
If the two routes were swapped, GET /users/me would match the parameterised route and fail with a 422 because 'me' is not an integer.
path operations, HTTP methods, decorators, status_code, route order