/python_fastapi

FastAPI project with unit tests, GIT hooks (pre-commit, black, isort, and flake8), and Docker

Primary LanguagePythonMIT LicenseMIT

Create App logo

Test Creation Workflow Status Code style: black

FastAPI Project Template

This is a template used by create_app to create a new FastAPI project.

To create your new project from this template, simply run:

pip install create_app
python -m create_app python_fastapi

What's in this template

  • Project structure
  • A FastAPI API:
    • Configurable through environment variables and environment file
    • With CORS
    • And Base models for endpoints with pagination
  • Virtualenv
  • Unit tests
  • Docker containerization
  • Pre-commit GIT hooks
  • Makefile with useful commands

Git hooks

This template uses pre-commit to run GIT hooks in your repo:

This helps developers to keep the same code styling in the project.

To install the hooks in your repo, first install pre-commit in your system. Then run:

make install_git_hooks

Docker

You can build and run this project with Docker.

To build the Docker image, run:

make docker_build

To start the Docker image, run:

make docker_run

To build and start the Docker image with a single command, run:

make docker_build_and_run

Take a look at your running API

After starting the container, you can hit the API root with any browser or HTTP client. For example, with CURL:

curl localhost:{api_port}

Check the API docs! http://localhost:{api_port}/docs

And the alternative API docs! http://localhost:{api_port}/redoc

Virtualenv

It is recommended to keep your system's Python interpreter clean, and install your project's dependencies in a virtual environment (venv). Doing this has advantages like preventing dependencies conflicts between different projects you may have in your system.

Create the virtualenv

After you've installed venv in your system, do the following to create the venv:

make create_virtualenv

Requirements

Use the requirements.frozen file to declare the project's dependencies, and requirements.test.frozen to declare dependencies that are only required to run tests. As indicated in the filenames, it is advised to declare the dependencies with explicit versions (example: requests==2.28.1). This will allow you to control when to upgrade dependencies versions, and will save you headaches when a new dependency version is released right when you were running a deployment pipeline.

To install the requirements in the venv, run:

make install_requirements

To install the test requirements in the venv, run:

make install_test_requirements

To install requirements and test requirements with a single, command, run:

make install_all_requirements

Unit tests

Add your unit tests to the tests package.

To run all unit tests:

make run_unit_tests

Build your API

It's as simple as adding routers to the routers package, and registering them in routers/__init__py.