src.api๏
APIFromAnything module for generating APIs from Python functions.
Overview๏
Classes
Classes๏
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.
- src.api.middleware๏
List of middleware functions to apply to requests.
- Type:
List[Callable]
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.
- src.api._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]
- src.api._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.
- src.api.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
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
- src.api.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.
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)
- src.api.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.
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)
- src.api.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
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}"}
- src.api.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
Examples
>>> api = APIFromAnything() >>> # ... configure routes >>> api.serve(host="0.0.0.0", port=5000)