Web Service Network - API

Web Service API

The WebServiceAPI class acts as a configurable wrapper to create and manage a FastAPI application.

On this page

    #Overview

    The WebServiceAPI class acts as a configurable wrapper to create and manage a FastAPI application. Its purpose is to simplify the web application initialization process, configure essential middlewares, register default routes and automatically integrate additional routers dynamically from Python packages.

    It solves the problem of repetition and scattering of common settings in FastAPI APIs, bringing together in one place all the initial configuration, CORS middleware, basic health and authentication routes, as well as making it easier to extend the API with external routers. In practice, it can be used to speed up the development of RESTful APIs, ensuring a consistent base and allowing modular integration and easier testing.

    The class is especially useful in projects that want to keep a clean and scalable architecture, with clear logs of the application lifecycle and centralized control of configuration via a dictionary and environment variables.

    #Execution Flow

    1. Class instantiation
      The developer creates an instance of WebServiceAPI, optionally passing a custom settings dictionary. If no dictionary is passed, a default one is used through the CONFIG import.
    2. Application initialization with initialize()
      When the initialize() method is called, the FastAPI application is created with name, description, version, lifecycle management and CORS middlewares configured, and the default routes (/health, /, /health-authorization) are registered.
    3. Including additional routers
      After initializing the application, the developer can include additional routers using the include_routers() or test_routers() methods, passing lists of FastAPI routers. Each inclusion is logged to make tracking easier.
    4. Dynamic router discovery
      If desired, the collect_routers(package_name) method can be used to dynamically load routers defined in the modules of a given package, allowing modular extensibility.
    5. Getting the FastAPI instance
      Finally, to run or manipulate the application outside the class, the get_app() method returns the already initialized FastAPI instance.
    6. Execution and lifecycle logging
      When the application starts up, a banner and important information are shown in the logs. The application shutdown events are also recorded.

    #Class Methods Table

    MethodDescription
    __init__Initializes the class with settings and prepares the logger
    initializeCreates and configures the FastAPI application
    include_routersAdds routers to the application after initialization
    test_routersAdds routers to the application for testing purposes
    collect_routersDiscovers and imports routers from a package dynamically
    get_appReturns the initialized FastAPI instance

    #Environment Variables

    • DOMAIN: Defines the base domain of the application, used to display URLs and documentation. If not set, it defaults to "http://localhost:8000".

    #Key Architecture Points and Insights

    • The class encapsulates the FastAPI configuration based on an external dictionary, making parameterization easier without changing code.
    • Use of asynccontextmanager to control the lifecycle of the FastAPI application, with clear logs at startup and shutdown.
    • Dynamic inclusion of routers with collect_routers uses introspection via pkgutil and importlib, allowing API modularization.
    • Clear separation between basic configuration (middleware, default routes) and expansion through additional routes.
    • The default logger is tied to the uvicorn server, ensuring integration with the ASGI runtime logs.
    • The default routes include an authorization route that depends on validation via API key, using the static method Authorization.validate_api_key.

    #Class and Methods Description

    #WebServiceAPI Class

    #Description

    This class represents a configurable wrapper for FastAPI applications, allowing a web API to be initialized from external settings, adding default middlewares and routes, managing the application lifecycle and extending the API through the dynamic inclusion of routers coming from Python packages.

    #Constructor Arguments

    ArgumentTypeDescriptionDefault Value
    configdictDictionary with settings for the web serviceCONFIG

    #1. __init__

    Description

    Initializes the class, setting the configuration, logger and base domain for the application.

    Arguments

    • config (dict): settings for the API.

    Returns

    • Returns no value.

    Raises

    • None.

    Examples

    ws_api = WebServiceAPI()  # Usa CONFIG padrão
    ws_api_custom = WebServiceAPI(config=my_config_dict)

    #2. initialize

    Description

    Creates and configures a FastAPI instance with title, description, version and the defined lifecycle. Adds CORS middleware and registers default routes for the health check and the root route.

    Arguments

    • None.

    Returns

    • FastAPI: initialized FastAPI application instance.

    Raises

    • None.

    Examples

    app = ws_api.initialize()
    # app agora está pronta para uso em um servidor ASGI

    #3. include_routers

    Description

    Includes a list of FastAPI routers in the application, making sure the application has already been initialized. Logs the inclusion of each router.

    Arguments

    • routers (list): list of FastAPI router objects.

    Returns

    • Returns no value.

    Raises

    • RuntimeError: if the application is not initialized.

    Examples

    ws_api.include_routers([user_router, product_router])

    #4. test_routers

    Description

    Similar to include_routers, it includes a list of routers for possible testing or ad-hoc use, with logging of the inclusion.

    Arguments

    • routers (list): list of routers to include.

    Returns

    • Returns no value.

    Raises

    • RuntimeError: if the application is not initialized.

    Examples

    ws_api.test_routers([test_router])

    #5. collect_routers

    Description

    Dynamically discovers and imports all routers named router inside the modules of the given package, returning them in a list.

    Arguments

    • package_name (str): name of the package (dotted path) in which to look for modules with routers.

    Returns

    • list: list of FastAPI router instances found.

    Raises

    • None.

    Examples

    routers = ws_api.collect_routers("src.api.v1")
    # Retorna todos os routers em src/api/v1/*

    #6. get_app

    Description

    Returns the initialized FastAPI instance to be used externally.

    Arguments

    • None.

    Returns

    • FastAPI: FastAPI instance.

    Raises

    • RuntimeError: if called before the application is initialized.

    Examples

    app = ws_api.get_app()

    Complete practical examples:

    ws_api = WebServiceAPI()
    app = ws_api.initialize()
    
    routers = ws_api.collect_routers("src.api.v1")
    ws_api.include_routers(routers)
    
    # Agora app está pronto para ser executado

    Another simplified example:

    ws_api = WebServiceAPI()
    ws_api.initialize()
    
    ws_api.include_routers([user_router])
    
    app = ws_api.get_app()

    The documentation above provides essential details for understanding, extending and practically using the WebServiceAPI class in real projects, making it easier to develop modular, well-configured APIs with FastAPI.

    Source: src/web_services_network/api.py

    Esc
    ↑↓navigate Enteropen