openenv/echo_env
6
1# SPDX-License-Identifier: BSD-3-Clause2 3"""4Route configuration utilities for declarative FastAPI route registration.5 6This module provides utilities to reduce boilerplate in route registration7by using configuration objects instead of repeated function calls.8"""9 10from dataclasses import dataclass11from typing import Callable, List, Type12 13from fastapi import FastAPI14from pydantic import BaseModel15 16 17@dataclass18class GetEndpointConfig:19 """Configuration for a simple GET endpoint."""20 21 path: str22 handler: Callable[[], BaseModel | dict]23 response_model: Type[BaseModel] | type[dict]24 tag: str25 summary: str26 description: str27 28 29def _make_get_endpoint(30 handler: Callable[[], BaseModel | dict],31) -> Callable[[], BaseModel | dict]:32 """Wrap a sync GET handler in the async endpoint FastAPI expects."""33 34 async def endpoint() -> BaseModel | dict:35 return handler()36 37 return endpoint38 39 40def register_get_endpoints(app: FastAPI, configs: List[GetEndpointConfig]) -> None:41 """42 Register multiple GET endpoints from configuration.43 44 Args:45 app ([`~fastapi.FastAPI`]):46 FastAPI application instance.47 configs (`List[GetEndpointConfig]`):48 List of GET endpoint configurations.49 """50 for config in configs:51 app.get(52 config.path,53 response_model=config.response_model,54 tags=[config.tag],55 summary=config.summary,56 description=config.description,57 )(_make_get_endpoint(config.handler))58 