saigon.fastapi

saigon.fastapi.handlers

saigon.fastapi.handlers.EmptyRequestBody

alias of EmptyContent

saigon.fastapi.handlers.EmptyResponseBody

alias of EmptyContent

class saigon.fastapi.handlers.RequestHandler

Bases: ABC, Generic

Abstract base class for handling incoming requests and generating responses.

This generic class provides a structured way to define request handlers, enforcing types for both the incoming request body (RequestType) and the outgoing response body (ResponseType). It includes a central handle_request method that wraps the abstract _handle method, providing common logic for handling empty bodies, checking for None responses, and robust exception management.

Type Variables:
RequestType: A Pydantic BaseModel representing the structure of the

incoming request body. Can be EmptyRequestBody if no body is expected.

ResponseType: A Pydantic BaseModel representing the structure of the

outgoing response body. Can be EmptyResponseBody if no content is expected in the response.

handle_request(request_body=None, *args, **kwargs)

Processes the incoming request, calls the internal handler, and manages responses.

This method serves as a wrapper around the _handle method, providing:

  • Defaulting request_body to EmptyRequestBody if None.

  • Type checking to ensure the _handle method returns a non-None response if ResponseType is not EmptyResponseBody.

  • Centralized error handling for HTTPException and generic exceptions, mapping them to appropriate HTTP status codes.

Parameters:
  • request_body (Optional[RequestType | EmptyRequestBody]) – The incoming request body, an instance of RequestType or EmptyRequestBody. Defaults to None, in which case EmptyRequestBody() is used.

  • *args – Positional arguments to pass to the _handle method.

  • **kwargs – Keyword arguments to pass to the _handle method.

Returns:

The processed response, an instance of ResponseType.

Return type:

ResponseType

Raises:

HTTPException

  • If _handle returns None and the expected ResponseType is not EmptyResponseBody (raises HTTP_404_NOT_FOUND). - If a generic Exception occurs during _handle execution (raises HTTP_500_INTERNAL_SERVER_ERROR). - If _handle itself raises an HTTPException.

saigon.fastapi.headers

class saigon.fastapi.headers.HeaderContext(**data)

Bases: BaseModel, Generic

classmethod from_identity_id(identity_id)

Creates a RequestContext instance using a given identity UUID and generates a new request ID.

This factory method is useful when you need to construct a RequestContext for internal use or testing, providing only the user’s identity.

Parameters:

identity_id (uuid.UUID) – The UUID of the user’s identity.

Returns:

A new RequestContext instance.

Return type:

Self

property headers: dict

Returns the request context attributes as a dictionary suitable for HTTP headers.

The keys in the returned dictionary will use their aliased names (e.g., ‘X-Cognito-AuthProvider’, ‘X-Api-RequestId’).

Returns:

A dictionary of the request context headers.

Return type:

dict

identity_id: TypeVar(IdentityId, bound= UUID | str)
request_id: Optional[str]
classmethod serialize_identity_id(identity_id, _)

Serializes the identity_id UUID into its string representation for output.

Parameters:
  • identity_id (uuid.UUID) – The UUID object of the identity.

  • _ (Any) – Pydantic’s SerializationInfo object (unused here).

Returns:

The string representation of the UUID.

Return type:

str

saigon.fastapi.headers.custom_request_context(type_name, identity_id_alias='X-Api-IdentityId', request_id_alias='X-Api-RequestId', identity_id_validator=None, request_id_validator=None)

Creates a RequestContext model by overriding the attribute aliases and validators.

You can select any combination of elements to override. The non-overridden will remain as defined in the default model.

Parameters:
  • identity_id_alias (Optional[str]) – Overriding alias for identity_id

  • request_id_alias (Optional[str]) – Overriding alias for request_id

  • identity_id_validator (Optional[Callable]) – Overriding validator for identity_id

  • request_id_validator (Optional[Callable[[Any], TypeVar(IdentityId)]]) – (Optional[Callable]): Overriding validator for request_id

Returns:

A model subclass of RequestContext with the overriding values

Return type:

HeaderContext[IdentityId]

saigon.fastapi.utils

saigon.fastapi.utils.DefaultRouteContextDependency = Depends(dependency)

A FastAPI dependency that injects and sets the AppContext for a request.

This dependency should be added to FastAPI route functions or APIRouter`s to ensure `AppContext is available and configured for the request.

class saigon.fastapi.utils.LogMiddleware(app, logger, context_type=<class 'saigon.fastapi.headers.HeaderContext'>)

Bases: BaseHTTPMiddleware, Generic

Middleware for FastAPI applications that enhances logging and request context.

This middleware provides two main functionalities:

  1. Wraps the dispatch method with asynclogcontext, making a request-specific log context available for all endpoint implementations.

  2. Encloses the call_next call within log messages, indicating the reception and return of a request and response, respectively. It also populates the log context with request_id and caller_id from incoming headers.

To use this middleware, add it to your FastAPI application:

Example:

app.add_middleware(LogMiddleware, logger=my_logger)
async dispatch(request, call_next)

Dispatches the incoming request and processes the response.

This method sets up an asynchronous log context, extracts request IDs and caller IDs from headers to populate the context, logs the start and end of the request processing, and passes control to the next middleware or endpoint.

Parameters:
  • request (Request) – The incoming Starlette request object.

  • call_next (Callable) – The next callable in the middleware chain.

Returns:

The Starlette response object.

Return type:

Response

class saigon.fastapi.utils.RouteContext(*, header_context: ContextType, background_tasks: BackgroundTasks | None = None)

Bases: BaseModelNoExtra, Generic

Represents the application context for a given request.

This class extends RequestContext by adding request-specific utilities like BackgroundTasks and makes the context globally accessible via a ContextVar. It is designed to be injected as a dependency into FastAPI routes.

background_tasks

FastAPI’s BackgroundTasks instance, allowing tasks to be run after the HTTP response has been sent. This field is excluded from Pydantic models (e.g., when dumping to JSON).

Type:

Optional[BackgroundTasks]

saigon.fastapi.utils.create_app(api_router, logger, root_path='/v1', health_path='/', context_type=<class 'saigon.fastapi.headers.HeaderContext'>, **kwargs)

Factory function to create and configure a FastAPI application.

This function sets up the basic FastAPI application, adds necessary middleware, registers exception handlers, includes the provided API router, and configures health check endpoints and operation ID simplification.

Parameters:
  • api_router (APIRouter) – The API router containing all defined endpoints for the application.

  • logger (logging.Logger) – The logger instance to be used by the LogMiddleware.

  • root_path (Optional[str]) – The root path for the application. Defaults to ‘/v1’.

  • health_path (Optional[str | None]) – The path for the health check endpoint. If set to None, no health endpoint is added. Defaults to ‘/’.

  • context_type (Optional[Type[HeaderContext]]) – Custom RequestContext to install as a dependency for the RouteContext

  • **kwargs – Additional keyword arguments to pass directly to the FastAPI constructor.

Returns:

The configured FastAPI application instance.

Return type:

FastAPI

saigon.fastapi.utils.route_context()

Retrieves the current application context from the ContextVar.

This function provides a way to access the AppContext instance that was set up by AppContext.from_route for the current request.

Returns:

The AppContext instance for the current request.

Return type:

AppContext

saigon.fastapi.utils.use_route_names_as_operation_ids(app)

Simplifies FastAPI operation IDs by setting them to the route’s name.

This function iterates through all registered routes in a FastAPI application and, for APIRoute instances, sets their operation_id to their name. This helps in generating API clients with simpler and more readable function names.

This function should be called only after all desired routes have been added to the FastAPI application.

Parameters:

app (FastAPI) – The FastAPI application instance.

Return type:

None

saigon.fastapi.utils.validate_query_date_range(start_time=None, end_time=None)

Validates and constructs a TimeRange object from ‘StartTime’ and ‘EndTime’ query parameters.

If both start_time and end_time are None, it returns None. If only start_time is provided, end_time defaults to the current UTC datetime. If only end_time is provided, start_time defaults to the Unix epoch (datetime.min). Otherwise, a TimeRange object is created with the provided or defaulted times.

Parameters:
  • start_time (Annotated[datetime, Query], optional) – The start of the time range. Corresponds to the ‘StartTime’ query parameter. Defaults to None.

  • end_time (Annotated[datetime, Query], optional) – The end of the time range. Corresponds to the ‘EndTime’ query parameter. Defaults to None.

Returns:

A TimeRange object if either start_time or end_time

is provided, otherwise None.

Return type:

TimeRange | None

saigon.fastapi.utils.validate_query_pagination_params(query_id=None, next_token=None, max_frame_count=None)

Validates and constructs QueryDataParams from pagination query parameters.

This dependency function processes optional QueryId, NextToken, and MaxCount query parameters, combining them into a QueryDataParams object suitable for pagination logic.

Parameters:
  • query_id (Annotated[str, Query], optional) – The ID of a previous query for pagination. Corresponds to the ‘QueryId’ query parameter. Defaults to None.

  • next_token (Annotated[str, Query], optional) – The token for the next page of results. Corresponds to the ‘NextToken’ query parameter. Defaults to None.

  • max_frame_count (Annotated[int, Query], optional) – The maximum number of items to return in a single response. Must be greater than 0. Corresponds to the ‘MaxCount’ query parameter. Defaults to None.

Returns:

An object containing the parsed pagination parameters.

Return type:

QueryDataParams

saigon.fastapi.utils.validation_error_exception_handler(_, exc)

Custom exception handler for Pydantic’s ValidationError.

This handler intercepts ValidationError instances, ensuring that they return a 422 Unprocessable Entity HTTP response with structured error details, consistent with FastAPI’s default Pydantic error responses. For any other exception type, it returns a generic 500 Internal Server Error.

Parameters:
  • _ (Request) – The incoming request object (unused).

  • exc (Exception) – The exception that was caught.

Returns:

A FastAPI JSONResponse with an appropriate status code

and error details.

Return type:

JSONResponse