Production Ready FastAPI Application From 0 to 1 [Part-3]

Mohit
2 min readNov 4, 2022

--

In Part 2 of this series, we have created a simple application based on FastAPI. Now, we will cover the below features in this post.

  • Code setup to read from environment variables.
  • Database configuration using SQLAlchemy.
  • Models & repositories creation.
  • Running Postgres using docker.

The part3 specific implementation is available in the GitHub repository.

Let’s set up the code to read environment variables.

We use python-dotenv to achieve this functionality.

pipenv install python-dotenv 
pipenv install starlette #supporting library
pipenv install pydantic #supporting library for Postgres

config.py inside the core module helps in reading environment variables.

Set up a database configuration using SQLAlchemy

pipenv install sqlalchemy 
pipenv install psycopg2-binary

db_session.py is used to provide database sessions.

deps.py provides database sessions to the functions.

All configurations & setup are completed. 😄

Let's create a model & repository for an example User Table.

model.py defines the common table attributes and a user model.

base.py provides generic implementation for all the model crud operations.

Now, the user.py extends the base repository class and provides its own custom method which isn’t present in the base class.

Let's add table creation logic in main.py for now

model.metadata.create_all(bind=engine)

Spin up Postgres instance using docker.

We have to run Postgres in our system and we will achieve this using docker. You can use any other Postgres instance too.

Install docker on your machine using the instructions from the official docker website.

Create a docker-compose.yaml in the root directory.

Bingo!!! We have completed the setup.

We need to create a dev.env file in the root folder where we provide the database credentials. We provide the path of this file as input to the uvicorn server.

POSTGRES_SERVER=localhost
POSTGRES_PORT=5432
POSTGRES_USER=test
POSTGRES_PASSWORD=test123
POSTGRES_DB=test_db
POOL_SIZE=5
MAX_OVERFLOW=-1
POOL_PRE_PING=True
ECHO=False
POOL_RECYCLE_IN_SECONDS=3600
ECHO_POOL=False
POOL_RESET_ON_RETURN=rollback
POOL_TIMEOUT_IN_SECONDS=30
POOL=~class:`~sqlalchemy.pool.QueuePool`

Run the application now

uvicorn app.main:app --env-file dev.env

Summary

We have covered the complete production-ready code related to databases, settings, models & repositories. In Part 4, we have covered CRUD API operation for the user table.

A quick link to articles from this series:

We would be glad to hear suggestions from you. Thank you for reading.

The whole project is available in the GitHub repository.

If this article is helpful, follow me to see my next articles.

--

--

Mohit

Founder @SignalsIQ.AI | Prev @Co-Founder @getphyllo.com