Path operations and HTTP methods

Difficulty: Beginner

Question

What is a path operation in FastAPI, and how do you define endpoints for GET, POST, PUT, PATCH and DELETE?

Answer

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.

Anatomy of a path operation

  • Path: the URL part after the domain, e.g. /orders/{order_id}. Curly braces mark path parameters.
  • Operation: the HTTP method. FastAPI provides decorators for get, post, put, patch, delete, options, head and trace.
  • Function: the handler. Its parameters tell FastAPI what to read from the request and its return value becomes the response body (serialized to JSON by default).
  • Decorator arguments: metadata and behaviour such as status_code=201, response_model, tags, summary, dependencies and deprecated=True.

Choosing the right method

MethodTypical useIdempotentCommon status
GETRead a resource or listYes200
POSTCreate a resource or trigger an actionNo201
PUTReplace a resource completelyYes200
PATCHUpdate some fieldsNot guaranteed200
DELETERemove a resourceYes204

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.

How FastAPI matches a request

  1. At startup, every decorator registers a route with its path, method and handler.
  2. When a request arrives, routes are checked in the order they were declared.
  3. The first route whose path pattern and method match wins. If the path matches but the method does not, the client gets 405 Method Not Allowed; if nothing matches, 404.
  4. FastAPI extracts parameters, validates them, runs dependencies, calls your function and serializes the return value.

Gotchas that come up in interviews

  • Route order: declare /users/me before /users/{user_id}. Otherwise me is captured as user_id and fails integer validation with a 422.
  • Status codes: POST returns 200 unless you set status_code=201. For 204 responses, return nothing; a body with 204 is invalid HTTP.
  • Same function name twice: Python lets you redefine a function, but it confuses the generated operationId. Keep handler names unique.
  • One function, many methods: use @app.api_route("/x", methods=["GET", "HEAD"]) only when you really need it; separate handlers are clearer.

In real projects

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.

How a request reaches a path operation. FastAPI matches path and method, validates inputs, then calls your function.
  1. HTTP request: PATCH /orders/42 with a JSON body.
  2. Route matching: Routes checked in declaration order.
  3. Parameter validation: Path, query and body parsed by type hints.
  4. Path operation function: Your handler runs with typed arguments.
  5. JSON response: Return value serialized with the status code.

Code examples

CRUD endpoints for one resource

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.

Route order matters

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.

Key points

  • Path operation = path + HTTP method + handler function
  • Routes are matched in declaration order; put fixed paths before parameterised ones
  • POST defaults to 200, so set status_code=201 explicitly for creation
  • 204 responses must not include a body
  • Use model_dump(exclude_unset=True) to implement PATCH correctly

Common follow-up questions

  • What is the difference between PUT and PATCH, and how would you implement PATCH in FastAPI?
  • Which HTTP methods are idempotent and why does it matter for retries?
  • How would you make a POST payment endpoint safe to retry?
  • What does FastAPI return when the path matches but the method does not?

Interview tips

  • Use the official term 'path operation function'; it signals you have read the docs
  • Bring up route ordering with the /users/me example; it is a classic bug interviewers like
  • Connect methods to idempotency and retries, not just CRUD names

Concepts covered

path operations, HTTP methods, decorators, status_code, route order

More FastAPI Interview questions