Metadata-Version: 2.4
Name: core-apis
Version: 2.0.1
Summary: This project/library contains useful elements related to APIs...
Author-email: Alejandro Cora González <alek.cora.glez@gmail.com>
Maintainer: Alejandro Cora González
License-Expression: MIT
Project-URL: Homepage, https://gitlab.com/bytecode-solutions/core/core-apis
Project-URL: Repository, https://gitlab.com/bytecode-solutions/core/core-apis
Project-URL: Documentation, https://core-apis.readthedocs.io/en/latest/
Project-URL: Issues, https://gitlab.com/bytecode-solutions/core/core-apis/-/issues
Project-URL: Changelog, https://gitlab.com/bytecode-solutions/core/core-apis/-/blob/master/CHANGELOG.md
Classifier: Intended Audience :: Developers
Classifier: Development Status :: 5 - Production/Stable
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Utilities
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: Implementation :: PyPy
Requires-Python: >=3.9
Description-Content-Type: text/x-rst
License-File: LICENSE
Requires-Dist: core-https>=3.0.1
Requires-Dist: fastapi>=0.115.6
Requires-Dist: uvicorn>=0.34.0
Provides-Extra: dev
Requires-Dist: core-dev-tools>=1.2.1; extra == "dev"
Requires-Dist: core-tests>=2.0.5; extra == "dev"
Requires-Dist: httpx>=0.28.1; extra == "dev"
Dynamic: license-file

core-apis
===============================================================================

This project/library contains useful elements related to APIs and provides
basic structures to speed up the implementation of an API service using
the FastApi framework as base...

===============================================================================

.. image:: https://img.shields.io/pypi/pyversions/core-apis.svg
    :target: https://pypi.org/project/core-apis/
    :alt: Python Versions

.. image:: https://img.shields.io/badge/license-MIT-blue.svg
    :target: https://gitlab.com/bytecode-solutions/core/core-apis/-/blob/main/LICENSE
    :alt: License

.. image:: https://gitlab.com/bytecode-solutions/core/core-apis/badges/release/pipeline.svg
    :target: https://gitlab.com/bytecode-solutions/core/core-apis/-/pipelines
    :alt: Pipeline Status

.. image:: https://readthedocs.org/projects/core-apis/badge/?version=latest
    :target: https://readthedocs.org/projects/core-apis/
    :alt: Docs Status

.. image:: https://img.shields.io/badge/security-bandit-yellow.svg
    :target: https://github.com/PyCQA/bandit
    :alt: Security

|


Installation
===============================================================================

Install from PyPI using pip:

.. code-block:: bash

    pip install core-apis
    uv pip install core-apis  # Or using UV...


Features
===============================================================================

**FastAPI Server Management**

* Quick server setup with uvicorn ASGI server
* Environment-based configuration (HOST, PORT, DEBUG, LOG_LEVEL)
* Secure defaults (localhost-only binding)

**Application Factory**

* ``AppConfig`` dataclass consolidating all application parameters (name, version, description, base_path, cors_config, debug)
* ``CorsConfig`` dataclass for CORS middleware (origins, methods, headers)
* ``create_application(app_config: AppConfig)`` factory with safe defaults

**Router Management**

* Plugin architecture: register routers at import time via ``add_router()``
* Runtime addition: attach routers to an existing app via ``app.include_router()``
* ``reset_routers()`` for clearing the registry between tests
* Built-in health check endpoint (``/api/ping``)

**Response Standardization**

* ``@wrap_response`` decorator for consistent API responses
* ``ApiResponse`` TypedDict contract: ``code``, ``status``, ``result``, ``error``
* HTTP status code mapping (2XX success, 4XX error, 5XX failure)
* Automatic exception handling for ``ServiceException`` and ``InternalServerError``

**Testing Utilities**

* ``BaseApiTestCases`` class for FastAPI testing with pre-configured ``TestClient``
* ``setUp()`` calls ``reset_routers()`` automatically to prevent cross-test pollution
* ``init_client(with_cors=True)`` for flexible test application initialization


How to use it
===============================================================================

The simple way to spin up the FastAPI server locally using `uvicorn`:

.. code-block:: python

    # -*- coding: utf-8 -*-
    from core_apis.api import server
    server.run()
..

Creating an application with custom configuration (``AppConfig`` / ``CorsConfig``):

.. code-block:: python

    # -*- coding: utf-8 -*-
    from core_apis.api import create_application, AppConfig, CorsConfig

    app = create_application(
        app_config=AppConfig(
            name="My Service",
            version="1.0.0",
            cors_config=CorsConfig(
                enabled=True,
                origins=["https://example.com"],
            ),
        ),
    )
..

Adding custom routers — plugin architecture (recommended):

Use ``add_router()`` to register routers at import time. They are collected by
``create_application()`` when the app is built. This is the recommended pattern
for plugins and reusable components that don't need a reference to the app instance.

.. code-block:: python

    # -*- coding: utf-8 -*-

    from fastapi import APIRouter

    from core_apis.api import server
    from core_apis.api.routers import add_router

    router = APIRouter()
    add_router(router)

    @router.get(path="/server_status")
    def get_server_status():
        return {"status": "OK"}

    server.run()
..

Adding routers at runtime (post-creation):

Use ``app.include_router()`` directly on the FastAPI instance after the application
has already been created. Useful for dynamic or conditional route registration.

.. code-block:: python

    # -*- coding: utf-8 -*-

    from fastapi import APIRouter

    from core_apis.api import create_application

    app = create_application()

    late_router = APIRouter()

    @late_router.get(path="/status")
    def get_status():
        return {"status": "OK"}

    app.include_router(late_router, prefix="/api")
..

Using ``@wrap_response`` — standardized response contract (``ApiResponse``):

.. code-block:: python

    # -*- coding: utf-8 -*-

    from core_https import HTTPStatus
    from core_apis.decorators import wrap_response

    @wrap_response
    def get_item(item_id: int):
        return HTTPStatus.OK, {"id": item_id, "name": "Widget"}

    # Returns an ApiResponse dict:
    # {"code": 200, "status": "success", "result": {"id": 1, "name": "Widget"}, "error": None}
..

For an example of the structure of a production-ready project
check: https://gitlab.com/bytecode-solutions/examples/fastapi-project


Quick Start
===============================================================================

Installation
-------------------------------------------------------------------------------

Install the package:

.. code-block:: bash

    pip install core-apis
    uv pip install core-apis  # Or using UV...
    pip install -e ".[dev]"    # For development...


Setting Up Environment
-------------------------------------------------------------------------------

1. Install required libraries:

.. code-block:: bash

    pip install --upgrade pip
    pip install virtualenv

2. Create Python virtual environment:

.. code-block:: bash

    virtualenv --python=python3.12 .venv

3. Activate the virtual environment:

.. code-block:: bash

    source .venv/bin/activate

Install packages
-------------------------------------------------------------------------------

.. code-block:: bash

    pip install .
    pip install -e ".[dev]"

Check tests and coverage
-------------------------------------------------------------------------------

.. code-block:: bash

    python manager.py run-tests
    python manager.py run-coverage


Contributing
===============================================================================

Contributions are welcome! Please:

1. Fork the repository
2. Create a feature branch
3. Write tests for new functionality
4. Ensure all tests pass: ``pytest -n auto``
5. Run linting: ``pylint core_apis``
6. Run security checks: ``bandit -r core_apis``
7. Submit a pull request


License
===============================================================================

This project is licensed under the MIT License. See the LICENSE file for details.


Links
===============================================================================

* **Documentation:** https://core-apis.readthedocs.io/en/latest/
* **Repository:** https://gitlab.com/bytecode-solutions/core/core-apis
* **Issues:** https://gitlab.com/bytecode-solutions/core/core-apis/-/issues
* **Changelog:** https://gitlab.com/bytecode-solutions/core/core-apis/-/blob/master/CHANGELOG.md
* **PyPI:** https://pypi.org/project/core-apis/


Support
===============================================================================

For questions or support, please open an issue on GitLab or contact the maintainers.


Authors
===============================================================================

* **Alejandro Cora González** - *Initial work* - alek.cora.glez@gmail.com
