2-how-to-use-fastapi-with-postgresql-for-building-restful-apis.html

How to Use FastAPI with PostgreSQL for Building RESTful APIs

Building RESTful APIs has become an essential skill for developers, especially in today's cloud-driven architecture. FastAPI, a modern web framework for Python, pairs perfectly with PostgreSQL, a powerful open-source relational database. This combination allows developers to create high-performance APIs quickly and efficiently. In this article, we’ll walk through how to use FastAPI with PostgreSQL to build robust RESTful APIs, complete with code examples and actionable insights.

What is FastAPI?

FastAPI is a Python web framework designed to build APIs quickly. It leverages Python type hints, which means you can build applications that are not only fast but also easy to maintain. Known for its asynchronous capabilities, FastAPI allows you to handle multiple requests simultaneously, making it an excellent choice for high-performance applications.

What is PostgreSQL?

PostgreSQL is an advanced, open-source relational database management system (RDBMS) that supports both SQL (relational) and JSON (non-relational) querying. Its robustness, extensibility, and support for complex queries make it a preferred choice for many developers when building applications that require data integrity and complex transactions.

Use Cases for FastAPI and PostgreSQL

  • Microservices Architecture: FastAPI is lightweight and designed for development speed, making it ideal for microservices.
  • Real-Time Applications: With its asynchronous nature, FastAPI can handle real-time data updates efficiently.
  • Data-Driven Applications: PostgreSQL’s powerful querying capabilities work well for applications that require complex data manipulations.

Setting Up Your Environment

Prerequisites

Before diving into the code, ensure you have the following installed on your machine:

  • Python 3.7 or higher
  • PostgreSQL
  • pip (Python package installer)

Installing Required Libraries

To get started, you need to install FastAPI, an ASGI server like uvicorn, and an ORM (Object-Relational Mapping) tool such as SQLAlchemy to interact with PostgreSQL.

Open your terminal and run the following command:

pip install fastapi[all] psycopg2 sqlalchemy uvicorn

Creating a Basic FastAPI Application with PostgreSQL

Step 1: Setting Up the Database

First, create a PostgreSQL database. You can do this using the psql command line:

CREATE DATABASE fastapi_db;

Step 2: Create a Database Model

Next, create a Python file called models.py. This file will define the database model using SQLAlchemy. Here's a simple example of a User model:

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'

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

Step 3: Setting Up the Database Session

Create a file named database.py to manage the database session:

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

DATABASE_URL = "postgresql://username:password@localhost/fastapi_db"

engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

Step 4: Creating the FastAPI Application

Now, create a new file called main.py and start building your FastAPI application:

from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session
from models import User, Base
from database import engine, get_db

# Create the database tables
Base.metadata.create_all(bind=engine)

app = FastAPI()

@app.post("/users/", response_model=User)
def create_user(user: User, db: Session = Depends(get_db)):
    db.add(user)
    db.commit()
    db.refresh(user)
    return user

@app.get("/users/{user_id}", response_model=User)
def read_user(user_id: int, db: Session = Depends(get_db)):
    user = db.query(User).filter(User.id == user_id).first()
    if user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return user

Step 5: Running the Application

Run your FastAPI application using uvicorn:

uvicorn main:app --reload

Visit http://127.0.0.1:8000/docs to access the automatically generated Swagger UI, where you can test your API endpoints.

Troubleshooting Common Issues

  • Connection Issues: Ensure your PostgreSQL server is running and that the credentials in DATABASE_URL are correct.
  • Import Errors: Double-check that all libraries are installed and imported correctly.
  • Data Not Persisting: Verify that you are committing your database sessions after making changes.

Conclusion

Combining FastAPI with PostgreSQL enables you to build high-performance RESTful APIs with minimal effort. The asynchronous capabilities of FastAPI make it an ideal choice for modern applications, while PostgreSQL provides a reliable and powerful backend. By following the steps outlined in this article, you can create a robust API that can be expanded and optimized as needed.

As you dive deeper into FastAPI and PostgreSQL, consider exploring more complex relationships, validation using Pydantic, and advanced querying techniques. 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.