apifrom.core ============ Core functionality for the APIFromAnything library. This module contains the core components for the API framework, including the application container, routing mechanism, request handling, and response handling. .. py:currentmodule:: apifrom.core Overview -------- **Classes** * :py:class:`API` * :py:class:`Request` * :py:class:`Response` * :py:class:`Router` Classes ------- .. py:class:: API(debug = False, title = 'APIFromAnything API', description = 'API created with APIFromAnything', version = '1.0.0', docs_url = '/docs', openapi_config = None, swagger_ui_config = None, enable_docs = True) Main application container for APIFromAnything. This class serves as the central registry for all API endpoints, middleware, and configuration. It provides methods for registering endpoints, middleware, and starting the server. .. attribute:: router The router instance for managing routes. :type: Router .. attribute:: middleware List of middleware instances. :type: list .. attribute:: debug Whether to run in debug mode. :type: bool .. attribute:: title The title of the API. :type: str .. attribute:: description The description of the API. :type: str .. attribute:: version The version of the API. :type: str .. attribute:: docs_url The URL for the API documentation. :type: str Initialize a new API instance. :param debug: Whether to run in debug mode. :param title: The title of the API. :param description: The description of the API. :param version: The version of the API. :param docs_url: The URL for the API documentation. :param openapi_config: Configuration for OpenAPI documentation. :param swagger_ui_config: Configuration for Swagger UI. :param enable_docs: Whether to enable API documentation. .. :: _app .. :: _current_instance .. :: debug .. :: description .. :: docs_url .. :: enable_docs .. :: middleware :no-index: .. :: openapi_config .. :: router .. :: swagger_ui_config .. :: title .. :: version .. method:: __call__(scope, receive, send) ASGI callable. This method allows the API instance to be used as an ASGI application. :param scope: The ASGI scope. :param receive: The ASGI receive function. :param send: The ASGI send function. .. method:: _build_app() Build the Starlette application. :returns: The Starlette application instance. .. method:: _get_current_instance() :classmethod: Get the current API instance. :returns: The current API instance, or None if no instance has been created. .. method:: add_middleware(middleware) Add middleware to the API. :param middleware: The middleware instance to add. .. method:: add_route(path, endpoint = None, methods = None, name = None, include_in_schema = True, **kwargs) Add a route to the API. This method can be used as a decorator or called directly. :param path: The path for the route. :param endpoint: The endpoint function. :param methods: The HTTP methods for the route. :param name: The name for the route. :param include_in_schema: Whether to include the route in the OpenAPI schema. :param \*\*kwargs: Additional arguments to pass to the router. :returns: The endpoint function if used as a decorator, or None if called directly. .. method:: add_routes(routes) Add multiple routes to the API. This method adds multiple routes to the API at once. The routes should be functions decorated with the @api decorator. :param routes: A list of functions decorated with the @api decorator. .. method:: process_request(request) :async: Process a request and return a response. This method is used by adapters to process requests without going through the ASGI interface. :param request: The request to process. :returns: The response to the request. .. method:: register_endpoint(handler, route, method = 'GET', name = None, **kwargs) Register an endpoint with the API. :param handler: The handler function for the endpoint. :param route: The route for the endpoint. :param method: The HTTP method for the endpoint. :param name: The name of the endpoint. :param \*\*kwargs: Additional arguments to pass to the router. .. method:: run(host = '127.0.0.1', port = 8000, **kwargs) Run the API server. :param host: The host to bind to. :param port: The port to bind to. :param \*\*kwargs: Additional arguments to pass to uvicorn.run. .. py:class:: Request(request = None, path_params = None, method = None, path = None, query_params = None, headers = None, body = None, client_ip = None) Request class for APIFromAnything. This class wraps a Starlette request and provides methods for accessing request data in a convenient way. .. attribute:: _request The underlying Starlette request. .. attribute:: path_params Path parameters extracted from the URL. .. attribute:: query_params Query parameters extracted from the URL. .. attribute:: headers HTTP headers. .. attribute:: method HTTP method. .. attribute:: path Request path. .. attribute:: _body Cached request body. Initialize a new Request instance. :param request: The underlying Starlette request. :param path_params: Path parameters extracted from the URL. :param method: The HTTP method. :param path: The request path. :param query_params: Query parameters. :param headers: HTTP headers. :param body: Request body. :param client_ip: Client IP address. .. :: state .. method:: __getattr__(name) Get an attribute from the underlying request. :param name: The name of the attribute. :returns: The attribute value. :raises AttributeError: If the attribute is not found. .. method:: body() :async: Get the request body. :returns: The request body as bytes. .. method:: form() :async: Get the request body as form data. :returns: The request body parsed as form data. .. method:: get_param(name, default = None) Get a parameter from the request. This method looks for the parameter in path parameters, query parameters, and then the request body (in that order). :param name: The name of the parameter. :param default: The default value to return if the parameter is not found. :returns: The parameter value, or the default value if not found. .. method:: json() :async: Get the request body as JSON. :returns: The request body parsed as JSON. :raises ValueError: If the request body is not valid JSON. .. py:class:: Response(content = None, status_code = 200, headers = None, content_type = 'application/json') Response class for APIFromAnything. This class represents an HTTP response and provides methods for setting response data, status code, and headers. .. attribute:: content The response content. .. attribute:: status_code The HTTP status code. .. attribute:: headers HTTP headers. .. attribute:: content_type The content type of the response. Initialize a new Response instance. :param content: The response content. :param status_code: The HTTP status code. :param headers: HTTP headers. :param content_type: The content type of the response. .. :: content .. :: content_type .. :: headers .. :: status_code .. method:: from_dict(data) :classmethod: Create a Response instance from a dictionary. :param data: The dictionary containing response data. :returns: A new Response instance. .. method:: set_cookie(key, value = '', max_age = None, expires = None, path = '/', domain = None, secure = False, httponly = False, samesite = 'lax') Set a cookie in the response. :param key: The cookie name. :param value: The cookie value. :param max_age: The maximum age of the cookie in seconds. :param expires: The expiration time of the cookie as a UNIX timestamp. :param path: The path for which the cookie is valid. :param domain: The domain for which the cookie is valid. :param secure: Whether the cookie should only be sent over HTTPS. :param httponly: Whether the cookie should be accessible only via HTTP. :param samesite: The SameSite attribute of the cookie. .. method:: to_dict() Convert the response to a dictionary. :returns: A dictionary representation of the response. .. method:: to_starlette_response() Convert to a Starlette response. :returns: A Starlette response. .. py:class:: Router Router for managing API endpoints. This class is responsible for registering and looking up API endpoints. It maintains a registry of routes and their associated handlers. .. attribute:: routes List of registered routes. :type: list Initialize a new Router instance. .. :: routes :no-index: .. method:: add_route(handler, path = None, method = 'GET', name = None, **kwargs) Add a route to the router. :param handler: The function to handle the route. :param path: The URL path for the route. If None, derived from handler name. :param method: The HTTP method for the route. :param name: The name for the route. If None, derived from handler name. :param \*\*kwargs: Additional arguments to associate with the route. .. method:: get_route_by_path(path, method = 'GET') Get a route by path and method. :param path: The path to match. :param method: The HTTP method to match. :returns: The route info if found, None otherwise. .. method:: get_route_handler(path, method = 'GET') Get a route handler by path and method. :param path: The path to match. :param method: The HTTP method to match. :returns: The handler function if found, None otherwise.