birchrest.routes package

Submodules

birchrest.routes.controller module

class birchrest.routes.controller.Controller[source]

Bases: object

Base class for defining a collection of routes and subcontrollers for an HTTP API.

The Controller class allows organizing routes and middleware in a structured manner. It collects routes defined on its methods, handles subcontrollers, and resolves the base path for each route. Each method decorated with HTTP method decorators (like GET, POST, etc.) is treated as a route, and the controller can apply middleware or mark routes as protected.

Attributes:

_base_path (str): The base path that is prefixed to all routes in this controller. _middlewares (List[MiddlewareFunction]): The list of middleware applied to this controller. _is_protected (str): Indicates if routes in this controller require protection (e.g., authentication). routes (List[Route]): The list of routes collected from the controller’s methods. controllers (List[Controller]): The list of subcontrollers attached to this controller.

collect_routes() Generator[Route, None, None][source]

Collect and yield all routes defined in this controller and its subcontrollers.

This method generates all routes defined in the controller, including those in any attached subcontrollers, recursively.

Yield:

The routes defined in this controller and its subcontrollers.

resolve_paths(prefix: str = '', middlewares: List[Callable[[Request, Response, Callable[[], Awaitable[None]]], Awaitable[None]]] = []) None[source]

Resolve and apply the base paths and middleware to all routes in this controller.

This method resolves the complete path for each route in the controller by combining the provided prefix with the controller’s base path. It also ensures that any middleware applied to the controller is propagated to its routes. If the controller has subcontrollers, their routes are resolved recursively.

Parameters:
  • prefix – The URL path prefix to prepend to the controller’s base path.

  • middlewares – A list of middleware functions to apply to all routes in the controller.

birchrest.routes.route module

class birchrest.routes.route.Route(func: Callable[[Request, Response], Awaitable[None]], method: str, path: str, middlewares: List[Callable[[Request, Response, Callable[[], Awaitable[None]]], Awaitable[None]]], protected: bool, validate_body: Any | None, validate_queries: Any | None, validate_params: Any | None, produces: Any | None = None, openapi_tags: List[str] = [])[source]

Bases: object

Represents an HTTP route in the application, mapping a specific HTTP method and path to a handler function. A Route can have middlewares, be protected with authentication, and validate request bodies, query parameters, and URL parameters.

Attributes:

func (RouteHandler): The handler function to execute when the route is matched. method (str): The HTTP method for this route (e.g., GET, POST). path (str): The URL path pattern for this route (e.g., ‘/users/:id’). middlewares (List[MiddlewareFunction]): A list of middleware functions to run before the handler. is_protected (bool): Indicates if this route requires authentication. validate_body (Optional[Any]): A dataclass or schema to validate the request body. validate_queries (Optional[Any]): A dataclass or schema to validate the query parameters. validate_params (Optional[Any]): A dataclass or schema to validate the URL parameters. auth_handler (Optional[AuthHandlerFunction]): A function to handle authentication for protected routes.

is_method_allowed(method: str) bool[source]

Checks if the given HTTP method is allowed for this route.

Parameters:

method – The HTTP method (e.g., GET, POST) to check.

Returns:

True if the method is allowed, otherwise False.

make_protected() None[source]

Marks the route as protected, requiring authentication to access.

match(request_path: str) Dict[str, str] | None[source]

Checks if the given request path matches the route’s path pattern.

Parameters:

request_path – The incoming request path.

Returns:

A dictionary of matched parameters if the path matches, otherwise None.

register_auth_handler(auth_handler: Callable[[Request, Response], Awaitable[Any]] | None) None[source]

Registers an authentication handler for this route.

Parameters:

auth_handler – A function that handles authentication for protected routes.

resolve(prefix: str, middlewares: List[Callable[[Request, Response, Callable[[], Awaitable[None]]], Awaitable[None]]]) None[source]

Resolves the final path and middlewares for the route, combining the given prefix with the route’s path and appending any global middlewares.

Parameters:
  • prefix – The path prefix to prepend to the route’s path.

  • middlewares – A list of global middleware functions to apply before the route-specific middlewares.

birchrest.routes.validator module

birchrest.routes.validator.parse_data_class(data_class: Type[Any], data: Any) Any[source]

Parses and validates data against a dataclass type, ensuring the data matches the field types, validation constraints (like min/max lengths, regex), and metadata such as default values. This function supports nested dataclasses and collections.

The function checks if the provided data conforms to the field types and optional constraints specified in the dataclass. If the data is invalid, a ValueError is raised with a descriptive message.

Parameters:
  • data_class – The dataclass type to validate against.

  • data – The input data to be validated, typically a dictionary.

Returns:

An instance of the dataclass with the validated data.

Raises:

ValueError – If the data is missing required fields or if any validation fails.

Module contents

This module provides routing and validation components for the BirchRest framework.

Components: - Controller: A base class for defining groups of routes, organizing request handling logic. - Route: Represents an individual route, mapping HTTP methods and paths to handler functions. - parse_data_class: A utility function for validating and parsing request data using dataclasses.

Exported components: - Controller - Route - parse_data_class

class birchrest.routes.Controller[source]

Bases: object

Base class for defining a collection of routes and subcontrollers for an HTTP API.

The Controller class allows organizing routes and middleware in a structured manner. It collects routes defined on its methods, handles subcontrollers, and resolves the base path for each route. Each method decorated with HTTP method decorators (like GET, POST, etc.) is treated as a route, and the controller can apply middleware or mark routes as protected.

Attributes:

_base_path (str): The base path that is prefixed to all routes in this controller. _middlewares (List[MiddlewareFunction]): The list of middleware applied to this controller. _is_protected (str): Indicates if routes in this controller require protection (e.g., authentication). routes (List[Route]): The list of routes collected from the controller’s methods. controllers (List[Controller]): The list of subcontrollers attached to this controller.

collect_routes() Generator[Route, None, None][source]

Collect and yield all routes defined in this controller and its subcontrollers.

This method generates all routes defined in the controller, including those in any attached subcontrollers, recursively.

Yield:

The routes defined in this controller and its subcontrollers.

resolve_paths(prefix: str = '', middlewares: List[Callable[[Request, Response, Callable[[], Awaitable[None]]], Awaitable[None]]] = []) None[source]

Resolve and apply the base paths and middleware to all routes in this controller.

This method resolves the complete path for each route in the controller by combining the provided prefix with the controller’s base path. It also ensures that any middleware applied to the controller is propagated to its routes. If the controller has subcontrollers, their routes are resolved recursively.

Parameters:
  • prefix – The URL path prefix to prepend to the controller’s base path.

  • middlewares – A list of middleware functions to apply to all routes in the controller.

class birchrest.routes.Route(func: Callable[[Request, Response], Awaitable[None]], method: str, path: str, middlewares: List[Callable[[Request, Response, Callable[[], Awaitable[None]]], Awaitable[None]]], protected: bool, validate_body: Any | None, validate_queries: Any | None, validate_params: Any | None, produces: Any | None = None, openapi_tags: List[str] = [])[source]

Bases: object

Represents an HTTP route in the application, mapping a specific HTTP method and path to a handler function. A Route can have middlewares, be protected with authentication, and validate request bodies, query parameters, and URL parameters.

Attributes:

func (RouteHandler): The handler function to execute when the route is matched. method (str): The HTTP method for this route (e.g., GET, POST). path (str): The URL path pattern for this route (e.g., ‘/users/:id’). middlewares (List[MiddlewareFunction]): A list of middleware functions to run before the handler. is_protected (bool): Indicates if this route requires authentication. validate_body (Optional[Any]): A dataclass or schema to validate the request body. validate_queries (Optional[Any]): A dataclass or schema to validate the query parameters. validate_params (Optional[Any]): A dataclass or schema to validate the URL parameters. auth_handler (Optional[AuthHandlerFunction]): A function to handle authentication for protected routes.

is_method_allowed(method: str) bool[source]

Checks if the given HTTP method is allowed for this route.

Parameters:

method – The HTTP method (e.g., GET, POST) to check.

Returns:

True if the method is allowed, otherwise False.

make_protected() None[source]

Marks the route as protected, requiring authentication to access.

match(request_path: str) Dict[str, str] | None[source]

Checks if the given request path matches the route’s path pattern.

Parameters:

request_path – The incoming request path.

Returns:

A dictionary of matched parameters if the path matches, otherwise None.

register_auth_handler(auth_handler: Callable[[Request, Response], Awaitable[Any]] | None) None[source]

Registers an authentication handler for this route.

Parameters:

auth_handler – A function that handles authentication for protected routes.

resolve(prefix: str, middlewares: List[Callable[[Request, Response, Callable[[], Awaitable[None]]], Awaitable[None]]]) None[source]

Resolves the final path and middlewares for the route, combining the given prefix with the route’s path and appending any global middlewares.

Parameters:
  • prefix – The path prefix to prepend to the route’s path.

  • middlewares – A list of global middleware functions to apply before the route-specific middlewares.

birchrest.routes.parse_data_class(data_class: Type[Any], data: Any) Any[source]

Parses and validates data against a dataclass type, ensuring the data matches the field types, validation constraints (like min/max lengths, regex), and metadata such as default values. This function supports nested dataclasses and collections.

The function checks if the provided data conforms to the field types and optional constraints specified in the dataclass. If the data is invalid, a ValueError is raised with a descriptive message.

Parameters:
  • data_class – The dataclass type to validate against.

  • data – The input data to be validated, typically a dictionary.

Returns:

An instance of the dataclass with the validated data.

Raises:

ValueError – If the data is missing required fields or if any validation fails.