Skip to main content
  1. Experiences/

fastapi-postgresql-boilerplate

·371 words·2 mins
Detail codes on Github

Overview #

๐Ÿš€ FastAPI is a modern, fast (high-performance) web framework for building APIs with Python 3.6+ based on standard Python-type hints.
I made and used this boilerplate for projects that I’m working on. ๐Ÿง‘โ€๐Ÿ’ป
it was powerful for building data-driven applications using schema for data validation, serialization, and documentation. ๐Ÿ“

Description #

A boilerplate that can serve as a base for FastAPI with PostgreSQL
Made with FastAPI, PostgreSQL, Docker, Coverage, SQLAlchemy, Pytest, Black, Flake8, Isort, and Poetry.

Features #

Developer experience #

  • ๐Ÿ Python 3.10 for programming language
  • ๐Ÿš€ FastAPI for handling HTTP requests and responses
  • ๐Ÿณ Docker for containerization
  • ๐Ÿ˜ PostgreSQL for database
  • ๐Ÿ“ฆ Poetry for dependency management
  • ๐Ÿ“ˆ Coverage for code coverage
  • ๐Ÿงช Pytest for unit and integration testing
  • ๐Ÿ’พ SQLAlchemy ORM for interacting with a database
  • ๐Ÿšง Flake8 for linting
  • ๐ŸŽจ Black for code formatting
  • ๐Ÿ“š Isort for sorting imports

Back-end app features #

  • ๐Ÿšซ JWT authentication for secure access to the API
  • ๐ŸŽข Layered architecture. (Controller, Service, Repository, Model)
  • ๐Ÿ“ฆ Dependency injection for better code organization
  • ๐Ÿ“ Swagger and Redoc for API documentation and testing
  • โ™ป๏ธ Schema validation for input and output data

Requirements #

  • Python 3.10
  • Poetry
  • PostgreSQL
  • Docker

Getting Started #

Every command below except build and run is executed in a docker container.

Set Environment Variables #

# Copy service env file
$ cp .env.example .env
# Copy db env file
$ cp .db.env.example .db.env

Build and run the app with Docker Compose #

# Build docker image
$ docker-compose build

# Run the app in the background
$ docker-compose up -d

# Watch logs
$ docker-compose logs -f

# Execute a command in a running container
$ docker-compose exec app <command>

Migrate database #

before test or use the app, you need to migrate the database.

# init User table
$ docker-compose exec app poetry run alembic upgrade head

Test #

# Run unit tests using pytest
$ docker-compose exec app poetry run pytest

Lint and format #

# Run flake8
$ docker-compose exec app poetry run flake8

# Run black
$ docker-compose exec app poetry run black .

# Run isort
$ docker-compose exec app poetry run isort .

What’s next? #

  • Handle scheduled tasks with Celery