Controller¶
A controller receives a request, then calls a use case, before finally returning a response.
The controller (adapter layer) is responsible for validating and transforming requests into an understandable format for the use cases (application layer). The format is defined inside the use cases by the request and response models. The controller takes the user input (the request), converts it into the request model defined by the use case and passes the request model to the use case, and at the end return the response model.
--8<-- "api/src/app/features/todo/todo_feature.py"
Required- The controller needs to be decorated with the
create_responsedecorator, which handles exceptions and returns a unified response type. - The controller needs to have set the
response_modelandrequest_model, that is used to generate API documentation and used for validation. Optional- Add repository interface to handle communication to external services such as databases and inject the repository implementations to the controller endpoint and pass the injected repository implementations to the use case.
Note
FastAPI is built around the OpenAPI Specification (formerly known as swagger) standards. In FastAPI, by coding your endpoints, you are automatically writing your API documentation. FastAPI maps your endpoint details to a JSON Schema document. Under the hood, FastAPI uses Pydantic for data validation. With Pydantic along with type hints, you get a nice editor experience with autocompletion.
Testing controllers¶
Use the test_client fixture to populate the database with test data and test_app fixture to perform REST API calls.
--8<-- "api/tests/integration/features/todo/test_todo_feature.py"
Note
Mark it as integration test.