Skip to content

Esgrove/fastapi-template

Repository files navigation

FastAPI template

Ruff

FastAPI REST API project template and example. Uses Poetry for project and dependency management.

Dependencies

Requires:

  • Python 3.11+
  • Scripts use jq and Docker but not strictly needed

Install Python dependencies:

poetry install

Update dependencies:

poetry update

Quick start

Use the provided shell scripts to easily run unit tests and the API locally with Docker with the scripts:

./test.sh
./run.sh

Tests

Tests use pytest.

poetry run pytest -v

Run tests with coverage report:

poetry run pytest -v --cov=app tests/

Running server locally

Start a development server locally with a shortcut:

poetry run start
# with optional args
poetry run start --port 3000 --log debug

Or full command with all available uvicorn args:

poetry run uvicorn app.main:app --reload --host localhost --port 8000

Using Docker

Build Docker image and run container with the script:

./run.sh

Or manually:

docker build -t runtime .
docker run -d --name fastapi -p 80:80 runtime

Test API locally

With script with nice formatting:

./test-routes.sh

Manually:

curl -s http://127.0.0.1:8000/ | jq .
curl -s http://127.0.0.1:8000/items/1234 | jq .
curl -s http://127.0.0.1:8000/items/ | jq .
curl -s http://127.0.0.1:8000/items/?limit=8 | jq .

Interactive API docs

FastAPI automatically generates an OpenAPI schema for the API, which is used to render the documentation:

Note: The server needs to be running for these to work. With Docker, you can drop the port number 😉

Code formatting and linting

Code formatting and linting with ruff. Import sorting with isort.

These are configured with a custom line length limit of 120. The configs can be found in pyproject.toml.

Usage:

isort .
ruff format .
ruff --fix .

Using with pre-commit:

# setup to be run automatically on git commit
pre-commit install

# run manually
pre-commit run --all-files

TODO

  • Setup coveralls
  • Better API usage examples
  • Improve test cases