src.api ======= APIFromAnything module for generating APIs from Python functions. .. py:currentmodule:: src.api Overview -------- **Classes** * :py:class:`APIFromAnything` Classes ------- .. py:class:: APIFromAnything(config = None) Core class for transforming Python functions into REST API endpoints. The APIFromAnything class provides functionality to automatically generate REST API endpoints from existing Python functions using type hints for validation and documentation. .. attribute:: config Configuration dictionary for customizing API behavior. :type: Dict[str, Any] .. attribute:: routes Dictionary mapping routes to handler configurations. :type: Dict[str, Dict] .. attribute:: middleware List of middleware functions to apply to requests. :type: List[Callable] .. admonition:: Examples Basic usage: >>> from apifrom import APIFromAnything >>> api = APIFromAnything() >>> >>> @api.route("/hello/{name}") >>> def hello(name: str, greeting: str = "Hello") -> Dict[str, str]: >>> return {"message": f"{greeting}, {name}!"} >>> >>> # Start the API server >>> api.serve(host="localhost", port=8000) Initialize the API generator. :param config: Configuration options for the API. Includes settings for authentication, rate limiting, CORS, etc. Defaults to None. :type config: Dict[str, Any], optional .. note:: If config is None, default configuration values will be used. .. :: config :no-index: .. :: middleware :no-index: .. :: routes :no-index: .. method:: _analyze_function(func) Analyze a function and create an API endpoint configuration. :param func: The function to analyze. :returns: Endpoint configuration dictionary. :rtype: Dict[str, Any] .. method:: _initialize_defaults() Set up default configuration values. This internal method initializes default values for various configuration settings if they aren't explicitly provided in the config dictionary. .. method:: add_middleware(middleware_func) Add middleware to the API request processing pipeline. :param middleware_func: Middleware function to add. The function should accept (request, next_handler) parameters. :type middleware_func: Callable .. admonition:: Examples >>> api = APIFromAnything() >>> >>> @api.add_middleware >>> async def logging_middleware(request, next_handler): >>> print(f"Request to {request.path}") >>> response = await next_handler(request) >>> print(f"Response status: {response.status}") >>> return response .. method:: export_api(format = 'openapi') Export the generated API in the specified format. :param format: The format to export the API in. Supported formats include: - 'openapi': OpenAPI/Swagger specification - 'raml': RAML specification - 'postman': Postman collection Defaults to 'openapi'. :type format: str, optional :returns: The API specification in the requested format. :rtype: Dict[str, Any] :raises ValueError: If the requested format is not supported. .. admonition:: Examples Export as OpenAPI specification: >>> api = APIFromAnything() >>> # ... add routes >>> openapi_spec = api.export_api(format='openapi') >>> with open('openapi.json', 'w') as f: >>> json.dump(openapi_spec, f) .. method:: generate_api(source) Generate API from the provided source. Analyzes the provided source (function, class, or module) and generates API route configurations based on the source's structure and type hints. :param source: The source to generate API endpoints from. Can be: - A function: Creates a single endpoint - A class: Creates endpoints for each public method - A module: Creates endpoints for all functions and classes - A string: Path to a Python file to analyze :returns: A dictionary containing the generated API configuration. :rtype: Dict[str, Any] :raises TypeError: If the source type is not supported. :raises ValueError: If the source cannot be parsed or contains invalid types. .. admonition:: Examples Generate API from a function: >>> def user_info(user_id: int) -> Dict[str, Any]: >>> return {"id": user_id, "name": f"User {user_id}"} >>> >>> api = APIFromAnything() >>> api_config = api.generate_api(user_info) .. method:: route(path, methods = None, **options) Decorator for registering routes with the API. :param path: URL path pattern for the route. :type path: str :param methods: HTTP methods supported by this route. Defaults to ["GET"]. :type methods: List[str], optional :param \*\*options: Additional route options like rate limiting, auth requirements. :returns: Decorator function that registers the decorated function. :rtype: Callable .. admonition:: Examples >>> api = APIFromAnything() >>> >>> @api.route("/users/{user_id}", methods=["GET"]) >>> def get_user(user_id: int) -> Dict[str, Any]: >>> return {"id": user_id, "name": f"User {user_id}"} .. method:: serve(host = '127.0.0.1', port = 8000) Start the API server. :param host: Host address to bind the server to. Defaults to "127.0.0.1". :type host: str, optional :param port: Port number to listen on. Defaults to 8000. :type port: int, optional .. admonition:: Examples >>> api = APIFromAnything() >>> # ... configure routes >>> api.serve(host="0.0.0.0", port=5000)