2-setting-up-a-scalable-fastapi-application-with-postgresql-and-docker.html

Setting Up a Scalable FastAPI Application with PostgreSQL and Docker

In today's fast-paced development landscape, creating scalable web applications efficiently is crucial. FastAPI, a modern web framework for Python, allows developers to build APIs quickly while ensuring high performance. Pairing FastAPI with PostgreSQL, a powerful relational database, and Docker, a containerization platform, creates a robust application environment. In this article, we’ll guide you through setting up a scalable FastAPI application using PostgreSQL and Docker, complete with code examples, step-by-step instructions, and actionable insights.

Why Choose FastAPI?

FastAPI is designed to help developers create APIs quickly. Here are some reasons to choose FastAPI for your next project:

  • High Performance: Built on Starlette for web parts and Pydantic for data handling, FastAPI is one of the fastest Python frameworks available.
  • Automatic Interactive Documentation: FastAPI automatically generates interactive API documentation using OpenAPI and Swagger.
  • Ease of Use: With simple syntax and type hints, FastAPI is developer-friendly.

Why Use PostgreSQL?

PostgreSQL is an advanced, open-source relational database. Its advantages include:

  • Scalability: PostgreSQL can handle large volumes of data seamlessly.
  • ACID Compliance: Ensures data integrity and reliability.
  • Rich Features: Supports complex queries, JSONB data types, and more.

Why Docker?

Docker allows you to package applications and their dependencies into containers, ensuring consistency across environments. Benefits include:

  • Isolation: Each application runs in its own container, avoiding conflicts.
  • Portability: Easily move your applications across different environments.
  • Scalability: Quickly scale applications up or down as needed.

Setting Up Your Environment

Prerequisites

Before you start, ensure you have the following installed:

  • Python 3.7+
  • Docker and Docker Compose
  • PostgreSQL

Step 1: Create a Project Directory

First, create a directory for your FastAPI application:

mkdir fastapi_postgres_docker
cd fastapi_postgres_docker

Step 2: Create Dockerfile

Create a file named Dockerfile in your project directory and add the following content:

# Use the official FastAPI image from Docker Hub
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9

# Set the working directory
WORKDIR /app

# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy the application code
COPY ./app /app

# Expose the API port
EXPOSE 80

Step 3: Create requirements.txt

Next, create a requirements.txt file for dependencies:

fastapi
uvicorn
asyncpg
sqlalchemy
pydantic

Step 4: Create the Application Structure

Create a directory named app, and within it, create a file called main.py:

mkdir app
touch app/main.py

Step 5: Write FastAPI Code

Open app/main.py and write the following code to set up a simple FastAPI application:

from fastapi import FastAPI
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

DATABASE_URL = "postgresql+asyncpg://user:password@db/postgres"

engine = create_engine(DATABASE_URL)
Base = declarative_base()

class Item(Base):
    __tablename__ = 'items'

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, index=True)
    description = Column(String)

Base.metadata.create_all(bind=engine)

app = FastAPI()

@app.get("/")
async def read_root():
    return {"Hello": "World"}

@app.post("/items/")
async def create_item(item: Item):
    return item

Step 6: Create docker-compose.yml

Create a docker-compose.yml file in your project root to define the services:

version: '3.8'

services:
  web:
    build: .
    ports:
      - "80:80"
    depends_on:
      - db

  db:
    image: postgres:13
    environment:
      POSTGRES_DB: postgres
      POSTGRES_USER: user
      POSTGRES_PASSWORD: password
    volumes:
      - postgres_data:/var/lib/postgresql/data

volumes:
  postgres_data:

Step 7: Build and Run the Application

Now, you can build and run your application using Docker Compose:

docker-compose up --build

Step 8: Access the Application

Once the application is running, you can access it at http://localhost. You should see a JSON response:

{"Hello": "World"}

Troubleshooting Tips

  • Database Connection Issues: Ensure the database service is running and the connection string in main.py is correct.
  • Dependency Errors: Check your requirements.txt for any missing packages.
  • Port Conflicts: If the application doesn’t start, ensure the port 80 is not being used by another application.

Conclusion

By following this guide, you have successfully set up a scalable FastAPI application with PostgreSQL and Docker. This setup not only enhances your application’s performance but also ensures reliability and ease of deployment. As you continue to develop your application, explore FastAPI's advanced features, such as dependency injection and background tasks, to further optimize your code. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.