Skip to main content

Path Operation Decorators

Path operation decorators are the primary mechanism in the FastAPI class for defining API endpoints. These decorators correspond to standard HTTP methods and are used to register functions (path operations) that handle incoming requests to specific URL paths.

In this codebase, the FastAPI class (found in fastapi/applications.py) inherits from Starlette and provides a suite of decorator methods that wrap an internal routing.APIRouter instance.

Core HTTP Method Decorators

The FastAPI class implements decorators for all standard HTTP methods. Each decorator takes a path as its first argument and a variety of configuration parameters.

The most commonly used decorators include:

  • @app.get(path)
  • @app.post(path)
  • @app.put(path)
  • @app.delete(path)
  • @app.patch(path)

Additional methods like @app.options(), @app.head(), and @app.trace() are also available for specialized use cases.

Basic Usage Example

A path operation is defined by decorating a function with one of these methods. The function can be a standard def or an async def.

from fastapi import FastAPI

app = FastAPI()

@app.get("/items/")
def read_items():
return [{"name": "Empanada"}, {"name": "Arepa"}]

Path Operation Configuration

The decorators accept several parameters to configure the behavior and metadata of the endpoint.

Status Codes

You can define the default HTTP status code for a successful response using the status_code parameter. This is particularly useful for POST requests that should return 201 Created.

# From docs_src/path_operation_configuration/tutorial001_py310.py
@app.post("/items/", status_code=status.HTTP_201_CREATED)
async def create_item(item: Item) -> Item:
return item

Tags and Organization

The tags parameter accepts a list of strings or Enums. These are used by OpenAPI (and the /docs UI) to group related operations together.

# From docs_src/path_operation_configuration/tutorial006_py310.py
@app.get("/items/", tags=["items"])
async def read_items():
return [{"name": "Foo", "price": 42}]

Summary and Description

Metadata for the API documentation can be provided in two ways:

  1. Explicit Parameters: Using summary and description in the decorator.
  2. Docstrings: If no description is provided in the decorator, FastAPI automatically extracts the docstring from the decorated function.
# From docs_src/path_operation_configuration/tutorial005_py310.py
@app.post(
"/items/",
summary="Create an item",
response_description="The created item",
)
async def create_item(item: Item) -> Item:
"""
Create an item with all the information:

- **name**: each item must have a name
- **description**: a long description
- **price**: required
"""
return item

Response Management

The response_model is one of the most powerful features of path operation decorators. It serves four primary purposes:

  1. Documentation: Defines the JSON Schema for the response in OpenAPI.
  2. Serialization: Converts the returned object (e.g., an ORM model) into the type defined in the response_model.
  3. Filtering: Ensures only the fields defined in the model are sent to the client.
  4. Validation: Validates the outgoing data.

[!IMPORTANT] If the data returned by your function does not match the response_model, FastAPI will raise a 500 Internal Server Error. This is because a mismatch is considered a developer error—a violation of the contract defined by the API.

Custom Response Classes

By default, FastAPI uses JSONResponse. You can override this globally for the app or specifically for a path operation using the response_class parameter.

from fastapi import FastAPI, Response
from fastapi.responses import JSONResponse

@app.head("/items/", status_code=204, response_class=JSONResponse)
def get_items_headers(response: Response):
response.headers["X-Cat-Dog"] = "Alone in the world"

Advanced Metadata and Visibility

Several parameters allow you to control how the operation appears in the generated schema:

  • deprecated: When set to True, the endpoint will be marked as deprecated in the documentation.
  • include_in_schema: When set to False, the endpoint will still function but will not appear in the OpenAPI schema or /docs.
  • operation_id: A unique string used to identify the operation. If not provided, it is generated automatically using the function name.
@app.get("/elements/", tags=["items"], deprecated=True)
async def read_elements():
return [{"item_id": "Foo"}]

Internal Implementation

When you call a decorator like @app.get(), the FastAPI instance delegates the registration to its internal APIRouter (stored in self.router).

The FastAPI class implementation for these decorators follows a consistent pattern:

# Simplified pattern from fastapi/applications.py
def get(self, path: str, **kwargs):
return self.router.get(path, **kwargs)

This delegation ensures that the application instance and any included routers (via app.include_router()) share the same underlying routing logic and configuration capabilities.