Understanding the OPTIONS Method in FastAPI
FastAPI provides the options method to define a path operation for the HTTP OPTIONS request method. This is particularly useful when you want to inform clients about the communication options available on the server, such as allowed methods, headers, and other metadata. It is a common part of REST APIs and often used in CORS (Cross-Origin Resource Sharing) configurations.
Signature of the options Method
def options(
path: str,
*,
response_model: Any = Default(None),
status_code: int | None = None,
tags: List[str | Enum] | None = None,
dependencies: Sequence[Depends] | None = None,
summary: str | None = None,
description: str | None = None,
response_description: str = "Successful Response",
responses: Dict[int | str, Dict[str, Any]] | None = None,
deprecated: bool | None = None,
operation_id: str | None = None,
response_model_include: IncEx | None = None,
response_model_exclude: IncEx | None = None,
response_model_by_alias: bool = True,
response_model_exclude_unset: bool = False,
response_model_exclude_defaults: bool = False,
response_model_exclude_none: bool = False,
include_in_schema: bool = True,
response_class: type[Response] = Default(JSONResponse),
name: str | None = None,
callbacks: List[BaseRoute] | None = None,
openapi_extra: Dict[str, Any] | None = None,
generate_unique_id_function: Callable[[APIRoute], str] = Default(generate_unique_id)
) -> Callable:
Explanation of Parameters
Here’s a breakdown of the parameters, along with examples:
path: str
The URL path where this operation will be available. Example: "/items/".
response_model: Any
A model that defines the structure of the response. If specified, FastAPI will validate and serialize the response to match the model.
class ItemOptions(BaseModel):
additions: List[str]
@router.options("/items/", response_model=ItemOptions)
def get_item_options():
return {"additions": ["Aji", "Guacamole"]}
status_code: int | None
The HTTP status code returned by this endpoint. Defaults to 200.
@router.options("/items/", status_code=204)
def get_item_options():
return {}
tags: List[str | Enum] | None
A list of tags for grouping operations in the OpenAPI documentation.
@router.options("/items/", tags=["items", "options"])
def get_item_options():
return {"additions": ["Aji", "Guacamole"]}
dependencies: Sequence[Depends] | None
Dependencies that must be resolved before executing the function.
def verify_token(token: str = Depends(oauth2_scheme)):
# Token verification logic
pass
@router.options("/items/", dependencies=[Depends(verify_token)])
def get_item_options():
return {"additions": ["Aji", "Guacamole"]}
summary: str | None
A short summary for the API operation. Useful for documentation.
@router.options("/items/", summary="Retrieve item options")
def get_item_options():
return {"additions": ["Aji", "Guacamole"]}
description: str | None
A longer description for the operation. Can use Markdown.
def verify_token(token: str = Depends(oauth2_scheme)):
# Token verification logic
pass
@router.options("/items/", dependencies=[Depends(verify_token)])
def get_item_options():
return {"additions": ["Aji", "Guacamole"]}
summary: str | None
A short summary for the API operation. Useful for documentation.
@router.options("/items/", summary="Retrieve item options")
def get_item_options():
return {"additions": ["Aji", "Guacamole"]}
description: str | None
A longer description for the operation. Can use Markdown.
@router.options("/items/", description="Provides available additions for items.")
def get_item_options():
return {"additions": ["Aji", "Guacamole"]}
response_description: str
A description of the response. Defaults to "Successful Response".
@router.options("/items/", response_description="A dictionary of additions available for items.")
def get_item_options():
return {"additions": ["Aji", "Guacamole"]}
responses: Dict[int | str, Dict[str, Any]] | None
Custom response descriptions for different status codes.
@router.options("/items/", responses={404: {"description": "Not Found"}})
def get_item_options():
return {"additions": ["Aji", "Guacamole"]}
deprecated: bool | None
Marks the endpoint as deprecated in the OpenAPI schema.
@router.options("/items/", deprecated=True)
def get_item_options():
return {"additions": ["Aji", "Guacamole"]}
operation_id: str | None
A unique identifier for the operation in the OpenAPI schema.
@router.options("/items/", operation_id="get_item_options_id")
def get_item_options():
return {"additions": ["Aji", "Guacamole"]}
include_in_schema: bool
Whether to include this operation in the OpenAPI schema. Defaults to True.
@router.options("/items/", include_in_schema=False)
def get_item_options():
return {"additions": ["Aji", "Guacamole"]}
response_class: type[Response]
The custom response class for the operation. Defaults to JSONResponse.
@router.options("/items/", response_class=PlainTextResponse)
def get_item_options():
return "Available options: Aji, Guacamole"
Complete Example
from fastapi import APIRouter, FastAPI
from pydantic import BaseModel
app = FastAPI()
router = APIRouter()
class ItemOptions(BaseModel):
additions: list[str]
@router.options(
"/items/",
response_model=ItemOptions,
tags=["items"],
summary="Get item options",
description="Retrieve available additions for items using OPTIONS.",
response_description="Successful Response"
)
def get_item_options():
return {"additions": ["Aji", "Guacamole"]}
app.include_router(router)
Output
{
"additions": ["Aji", "Guacamole"]
}
This covers the basic and advanced usage of the options method in FastAPI. You can customize the behavior to fit your API needs while adhering to HTTP standards and documenting effectively with OpenAPI.
Thank you for taking the time to read! Follow me for more insights and updates, and let’s continue to grow and learn together.