FastAPI is a modern, high-performance Python web framework that makes building APIs a breeze. In this tutorial, we’ll explore how to integrate PostgreSQL with FastAPI using both traditional local setup and Docker containers.
Project Structure
Before we begin, here’s the project structure we’ll be building:
# Create a new database CREATE DATABASE fastapi_db;
# Create a user (optional, you can use postgres) CREATE USER fastapi_user WITH PASSWORD 'your_password'; GRANT ALL PRIVILEGES ON DATABASE fastapi_db TO fastapi_user;
# Exit \q
Step 3: Set Up Python Environment
# Create project directory mkdir fastapi-postgres && cd fastapi-postgres
# View all tables docker compose exec db psql -U fastapi_user -d fastapi_db -c "\dt"
# Rebuild only the API service docker compose up -d --build api
Testing the API
Once running (either locally or with Docker), test the API:
# Create a user curl -X POST "http://localhost:8000/users/" \ -H "Content-Type: application/json" \ -d '{"email": "john@example.com", "name": "John Doe"}'
# Get all users curl "http://localhost:8000/users/"
# Get a specific user curl "http://localhost:8000/users/1"
# Update a user curl -X PATCH "http://localhost:8000/users/1" \ -H "Content-Type: application/json" \ -d '{"name": "John Smith"}'
# Create an item curl -X POST "http://localhost:8000/items/" \ -H "Content-Type: application/json" \ -d '{"title": "My Item", "description": "A test item", "owner_id": 1}'
# Delete a user curl -X DELETE "http://localhost:8000/users/1"
Comparison: Local vs Docker
Aspect
Local Setup
Docker Setup
Setup complexity
Higher (install PostgreSQL)
Lower (just Docker)
Portability
Machine-dependent
Runs anywhere
Development
Faster iteration
Slightly slower builds
Production parity
Varies
Consistent
Team onboarding
Manual setup
Single command
Database persistence
System PostgreSQL
Docker volume
When to Use Each
Use Local Setup when:
You need maximum development speed
You already have PostgreSQL installed
You’re debugging database issues directly
Use Docker when:
Working in a team (consistent environments)
Deploying to production (same setup)
You don’t want to install PostgreSQL locally
You need to test with specific PostgreSQL versions
Next Steps
Add Alembic for database migrations
Implement authentication with JWT
Add async SQLAlchemy for better performance
Set up pytest for testing
Add Redis for caching
Conclusion
We’ve built a complete FastAPI application with PostgreSQL integration, covering both local development and Docker-based setups. The Docker approach provides better portability and team collaboration, while local setup offers faster iteration during development.
Choose the approach that best fits your workflow, or use both: local for quick development and Docker for testing production-like environments.