Fast API Routers are the equivalent of Flask Blueprints
Route responses can have customized Request and Response classes. These classes are enforced by pydantic and automatically populates the Swagger UI to explicitly define allowable JSON request and responses.
Fast API Setting is the equivalent of Flask Config.
Set up your virtual environment with virtualenv venv and source venv/bin/activate.
Similar to Flask, pip install the requirements file and run the start_local.sh.
pip install -r requirements.txt
./start_local.sh
Visit http://localhost:8080 to verify the healthcheck.
Visit http://localhost:8080/docs or http://localhost:8080/redocs for the documentation page.
- Create new models to define the endpoint's request and response payloads in
service/api/models. - Create the model's router in
service/api/routers. - Handle any logic by creating a new controller in
service/api/controllers. - Add a new feature flag in
settings.pywith any needed environment variablesfeature_flags.py. - Include the new router from step 2 to the bottom of
app.pybehind your feature flag.
Run pytests by running the command:
pytest
To include test code coverage from [pytest-cov], run the following from the root directory:
pytest --cov=src
Example output may look like
poetry run pytest
============================================ test session starts ============================================
platform darwin -- Python 3.10.0, pytest-7.4.3, pluggy-1.3.0 -- /Users/JustinRWong/Desktop/Projects/neon/fastapi-starter-template/venv/bin/python
cachedir: .pytest_cache
rootdir: /Users/JustinRWong/Desktop/Projects/neon/fastapi-starter-template
configfile: pytest.ini
testpaths: tests
plugins: cov-4.1.0, mock-3.12.0, anyio-3.7.1, dotenv-0.5.2
collected 9 items
tests/test_app.py::test_get_healthcheck PASSED [ 11%]
tests/test_app.py::test_get_docs PASSED [ 22%]
tests/test_info.py::test_get_info_incorrect_header_401 PASSED [ 33%]
tests/test_info.py::test_get_info_missing_parameter_422 PASSED [ 44%]
tests/test_info.py::test_get_info_info_correct_header_200 PASSED [ 55%]
tests/test_whoami.py::test_get_whoami_incorrect_header_401 PASSED [ 66%]
tests/test_whoami.py::test_get_whoami_missing_parameter_422 PASSED [ 77%]
tests/test_whoami.py::test_whoami_200_with_logging PASSED [ 88%]
tests/test_whoami.py::test_whoami_200_with_logging_bad_curlmyip PASSED [100%]
---------- coverage: platform darwin, python 3.10.0-final-0 ----------
Coverage HTML written to dir htmlcov
Required test coverage of 90% reached. Total coverage: 90.73%
============================================= 9 passed in 0.10s =============================================
The purpose of models in a web application, including FastAPI, is to represent the data structures used within the application. Models define the structure, attributes, and behavior of the data entities that are manipulated and exchanged between different components of the application.
Here are some key purposes of models:
-
Data Representation: Models define the structure and attributes of the data entities in your application. They represent the real-world objects or concepts that your application deals with, such as users, products, orders, or any other relevant entities. Models typically consist of fields that represent the attributes or properties of the entities.
-
Data Validation: Models can be used for data validation. By leveraging libraries like Pydantic in FastAPI, models can define validation rules and constraints for the data. This ensures that the incoming data is valid and meets the specified criteria before further processing.
-
Serialization and Deserialization: Models facilitate the serialization and deserialization of data. Serialization is the process of converting the model instances into a format suitable for storage or transmission, such as JSON or XML. Deserialization is the reverse process of converting the serialized data back into model instances. This allows for easy exchange of data between different components of the application.
-
Database Interaction: Models often map to database tables or collections. They provide an abstraction layer that allows the application to interact with the database without directly dealing with low-level database operations. Models can define relationships, query methods, and other database-specific functionality.
-
Business Logic Integration: Models are used to integrate with the business logic layer of the application. They serve as the input and output structures for the business logic operations. Models encapsulate the data required for the business logic to perform operations like data processing, calculations, or any other business-specific tasks.
By using models, you can ensure consistency, maintainability, and reusability of data structures throughout your application. They provide a clear representation of the data entities and enable seamless communication between different components of the application.
The purpose of routers in a web application, including FastAPI, is to define the API endpoints and handle incoming requests. Routers play a crucial role in routing the incoming requests to the appropriate handlers or controllers based on the requested URL and HTTP method.
Here are some key purposes of routers:
-
Endpoint Definition: Routers define the API endpoints and their corresponding URLs. Each endpoint represents a specific functionality or resource that the application exposes to clients. By defining endpoints, routers provide a clear and organized structure to the API.
-
Request Handling: Routers handle the incoming requests and delegate the request processing to the appropriate handlers or controllers. They extract relevant information from the request, such as query parameters, request body, or path parameters, and pass it to the corresponding handler for further processing.
-
URL Routing: Routers perform URL routing, which involves matching the requested URL to the defined endpoints. They determine which handler or controller should be responsible for processing the request based on the URL path and HTTP method.
-
Middleware Application: Routers can also be used to apply middleware to the incoming requests. Middleware functions can intercept and modify the request or response before it reaches the handler or controller. Routers provide a convenient way to apply middleware to specific endpoints or groups of endpoints.
-
Response Generation: Routers generate the appropriate response based on the result of the request processing. They construct the response object, set the appropriate status codes, headers, and body content, and send it back to the client.
By using routers, you can organize and structure your API endpoints, handle incoming requests, and ensure proper routing and response generation. Routers play a vital role in defining the API's behavior and facilitating communication between clients and the application.
The purpose of controllers in a web application, including FastAPI, is to handle the incoming requests, interact with the necessary models and business logic, and generate appropriate responses. Controllers act as an intermediary between the routers and the business logic.
Here are some key purposes of controllers:
-
Request Handling: Controllers receive the incoming requests from the routers and extract relevant data from the request, such as query parameters, request body, or path parameters. They validate and sanitize the input data as necessary.
-
Business Logic Interaction: Controllers interact with the business logic layer of the application. They call the appropriate methods or functions in the business logic layer to perform the required operations, such as retrieving data from a database, processing data, or updating records.
-
Data Transformation: Controllers transform the data received from the business logic layer into the appropriate format for the response. They may map the data to response models, apply formatting or serialization, and handle any necessary data transformations.
-
Response Generation: Controllers generate the response to be sent back to the client. They construct the response object, set the appropriate status codes, headers, and body content. They may also handle error cases and generate error responses when needed.
-
Error Handling: Controllers handle any errors that occur during request processing. They catch exceptions thrown by the business logic layer or other components and generate appropriate error responses. This includes handling validation errors, database errors, or any other exceptional conditions.
By separating the responsibilities of request handling, business logic interaction, and response generation, controllers help to keep the codebase organized, modular, and maintainable. They promote separation of concerns and make it easier to test and debug different parts of the application independently.