Setting Up a FastAPI Project with PostgreSQL and Docker
FastAPI is a modern web framework for building APIs with Python 3.6+ based on standard Python type hints. It is known for its speed and efficiency, making it an excellent choice for developers looking to create robust applications. When combined with PostgreSQL, a powerful and reliable relational database, and Docker, an essential tool for containerization, you can build scalable, easily deployable applications. In this article, we will guide you through setting up a FastAPI project with PostgreSQL and Docker, providing clear code examples and actionable insights along the way.
Why Choose FastAPI and PostgreSQL?
FastAPI Benefits
- Speed: FastAPI is one of the fastest Python frameworks available, thanks to its asynchronous capabilities.
- Ease of Use: It supports automatic generation of interactive API documentation.
- Type Safety: Utilizing Python's type hints allows for better validation and editor support.
PostgreSQL Benefits
- Reliability: Known for its stability and robustness in handling transactions.
- Advanced Features: Offers powerful features like JSONB support, full-text search, and more.
- Community Support: A large community and rich documentation make troubleshooting easier.
Prerequisites
Before we dive into the setup, ensure you have the following installed on your machine:
- Python 3.6 or higher
- Docker and Docker Compose
- PostgreSQL (if you want to run it locally without Docker)
Step 1: Create Your Project Directory
Let's start by creating a directory for your FastAPI project and navigating into it.
mkdir fastapi-postgres-docker
cd fastapi-postgres-docker
Step 2: Create a Dockerfile
Create a file named Dockerfile
in your project directory. This file will define the environment for your FastAPI application.
# Dockerfile
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]
Step 3: Set Up Requirements
Create a requirements.txt
file to manage your Python dependencies. For our FastAPI and PostgreSQL setup, the following packages are essential:
fastapi
uvicorn
asyncpg
sqlalchemy
Step 4: Create the Docker Compose File
Next, create a docker-compose.yml
file to set up both the FastAPI application and the PostgreSQL database.
version: '3.8'
services:
db:
image: postgres:13
environment:
POSTGRES_DB: fastapi_db
POSTGRES_USER: postgres
POSTGRES_PASSWORD: password
ports:
- "5432:5432"
web:
build: .
volumes:
- .:/app
ports:
- "8000:8000"
depends_on:
- db
Step 5: Create the FastAPI Application
Now, create a file named main.py
in your project directory. This file will contain your FastAPI application code.
# main.py
from fastapi import FastAPI
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
DATABASE_URL = "postgresql+asyncpg://postgres:password@db/fastapi_db"
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)
Base.metadata.create_all(bind=engine)
app = FastAPI()
@app.post("/items/")
async def create_item(name: str):
db: Session = sessionmaker(bind=engine)()
item = Item(name=name)
db.add(item)
db.commit()
db.refresh(item)
return item
@app.get("/items/{item_id}")
async def read_item(item_id: int):
db: Session = sessionmaker(bind=engine)()
return db.query(Item).filter(Item.id == item_id).first()
Step 6: Build and Run Your Application
With all the files in place, you can now build and run your Docker containers.
docker-compose up --build
You should see logs indicating that the FastAPI application is running on http://localhost:8000
. You can access the interactive API documentation at http://localhost:8000/docs
.
Step 7: Testing Your API
Create an Item
You can use tools like Postman or curl to test your API. To create an item, send a POST request:
curl -X POST "http://localhost:8000/items/" -H "Content-Type: application/json" -d '{"name": "Sample Item"}'
Retrieve an Item
To retrieve an item, simply make a GET request:
curl "http://localhost:8000/items/1"
Troubleshooting Common Issues
- Database Connection Errors: Ensure your PostgreSQL container is running and the connection string in
main.py
is correct. - Dependencies Issues: If you encounter issues related to missing packages, double-check your
requirements.txt
and rebuild your Docker image.
Conclusion
Setting up a FastAPI project with PostgreSQL and Docker is a streamlined process that allows developers to create efficient and scalable APIs. With the power of FastAPI, the reliability of PostgreSQL, and the convenience of Docker, you can focus on building robust applications without worrying about the underlying infrastructure. By following the steps above, you’ll be well on your way to developing your next great project. Happy coding!