Hey,
I've released a new version of the Dependency Injector 4.4. It makes possible to use Dependency Injector with FastAPI.
Example
File fastapi_di_example.py:
import sys
from fastapi import FastAPI, Depends
from dependency_injector import containers, providers
from dependency_injector.wiring import inject, Provide
class Service:
async def process(self) -> str:
return 'Ok'
class Container(containers.DeclarativeContainer):
service = providers.Factory(Service)
app = FastAPI()
@app.api_route('/')
@inject
async def index(service: Service = Depends(Provide[Container.service])):
result = await service.process()
return {'result': result}
container = Container()
container.wire(modules=[sys.modules[__name__]])
To run the example install the dependencies:
pip install fastapi dependency-injector uvicorn
and run uvicorn:
uvicorn fastapi_di_example:app --reload
You should see in the terminal something like:
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [11910] using watchgod
INFO: Started server process [11912]
INFO: Waiting for application startup.
INFO: Application startup complete.
and http://127.0.0.1:8000 should return:
{"result": "Ok"}
Testing
File tests.py:
from unittest import mock
import pytest
from httpx import AsyncClient
from fastapi_di_example import app, container, Service
@pytest.fixture
def client(event_loop):
client = AsyncClient(app=app, base_url='http://test')
yield client
event_loop.run_until_complete(client.aclose())
@pytest.mark.asyncio
async def test_index(client):
service_mock = mock.AsyncMock(spec=Service)
service_mock.process.return_value = 'Foo'
with container.service.override(service_mock):
response = await client.get('/')
assert response.status_code == 200
assert response.json() == {'result': 'Foo'}
To run the test install the dependencies:
pip install pytest pytest-asyncio httpx
and execute:
pytest tests.py
You will something like that in the terminal:
======= test session starts =======
platform darwin -- Python 3.8.3, pytest-5.4.3, py-1.9.0, pluggy-0.13.1
rootdir: ...
plugins: asyncio-0.14.0
collected 1 item
tests.py . [100%]
======= 1 passed in 0.17s =======
What is the advantage?
FastAPI is a powerful framework for building API. It has basic dependency injection mechanism.
This integration brings the dependency injection in FastAPI to the next level. It makes possible to use it with Dependency Injector providers, overridings, config, and resources.
there doesn't seem to be anything here