This is a FastAPI demo application implementing the Hexagonal Architecture.
The services module holds our domain implementations. We expose various interfaces (implemented using abstract classes) as ports that can be used by the adapters from the driving and driven modules.
In this example, the path operation endpoint function save_data acts as the driving adapter, and the concrete subclass MemoryDataPort of port abstract class MyDataPort acts as the driven adapter.
Path operation method save_data invokes the save method from the concrete implementation class MyServiceImpl. A dependency on the driven class MemoryDataport is injected from the path operation function to the domain business logic implementation using FastAPI's Depends mechanism.
The difference between a N-tier and hexagonal architecture is that the adapter MemoryDataPort implements interfaces from the domain's port instead of the domain logic implementing an interface from a lower level.
Create a Python 3.11 virtual environment and install dependencies from the requirements file.
python3.11 -m venv venv
source venv/bin/activate
pip install -r requirements.txtRun Uvicorn server
uvicorn app.main:app --reloadTest using Postman or cURL by tweaking the data query parameter:
curl --location --request PUT 'http://localhost:8000?data=true'To run the tests, simply run pytest.
pytest -s- Read more about hexagonal architecture.
- A short video on Hexagonal, onion, and clean architecture
- Domain driven design (DDD) with Hexagonal architecture
- More examples using python