FastAPI REST API project template and example. Uses Poetry for project and dependency management.
Requires:
- Python 3.11+
- Scripts use jq and Docker but not strictly needed
Install Python dependencies:
poetry install
Update dependencies:
poetry update
Use the provided shell scripts to easily run unit tests and the API locally with Docker with the scripts:
./test.sh
./run.sh
Tests use pytest.
poetry run pytest -v
Run tests with coverage report:
poetry run pytest -v --cov=app tests/
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
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
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 .
FastAPI automatically generates an OpenAPI schema for the API, which is used to render the documentation:
- Swagger UI documentation is available at http://127.0.0.1:8000/docs
- ReDoc documentation is available at http://127.0.0.1:8000/redoc
Note: The server needs to be running for these to work. With Docker, you can drop the port number 😉
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
- Setup coveralls
- Better API usage examples
- Improve test cases