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

How to Set Up FastAPI for Building RESTful APIs with PostgreSQL

In today’s fast-paced software development landscape, building efficient and scalable APIs is crucial. FastAPI has emerged as one of the most popular frameworks for developing RESTful APIs in Python, offering high performance and ease of use. When combined with PostgreSQL, a powerful relational database, you can create robust applications that handle complex data operations seamlessly. This article will guide you through setting up FastAPI with PostgreSQL, complete with code examples and actionable insights.

What is FastAPI?

FastAPI is a modern web framework for building APIs with Python 3.6+ based on standard Python type hints. It is designed to be fast (high performance), easy to use, and easy to deploy. FastAPI leverages asynchronous programming to handle multiple requests simultaneously, making it ideal for high-load applications.

Key Features of FastAPI

  • High Performance: Comparable to Node.js and Go.
  • Easy to Use: Designed for developers with automatic interactive API documentation.
  • Type Checking: Utilizes Python type hints for better code quality and editor support.
  • Asynchronous Programming: Built on Starlette for handling asynchronous requests.

Why Use PostgreSQL?

PostgreSQL is an advanced, open-source relational database known for its scalability and robustness. It supports various data types and offers powerful features like transactions, sub-selects, and user-defined functions. When paired with FastAPI, PostgreSQL provides a solid foundation for data storage and retrieval.

Key Benefits of PostgreSQL

  • Reliability: ACID-compliant for safe transactions.
  • Extensibility: Supports custom data types and functions.
  • Performance: Optimized for complex queries and large datasets.

Setting Up Your Environment

To get started, you will need to set up your development environment. Ensure you have Python and PostgreSQL installed on your machine.

Step 1: Install Required Packages

You can install FastAPI and an ASGI server like Uvicorn using pip:

pip install fastapi uvicorn psycopg2-binary sqlalchemy
  • psycopg2-binary: PostgreSQL adapter for Python.
  • sqlalchemy: SQL toolkit and Object-Relational Mapping (ORM) system for Python.

Step 2: Configure PostgreSQL

  1. Create a PostgreSQL Database: Log in to your PostgreSQL shell and create a new database:

sql CREATE DATABASE fastapi_db;

  1. Create a User: Create a user with a password:

sql CREATE USER fastapi_user WITH PASSWORD 'password';

  1. Grant Privileges: Grant the user privileges to the database:

sql GRANT ALL PRIVILEGES ON DATABASE fastapi_db TO fastapi_user;

Building Your FastAPI Application

Now that your environment is set up, let’s build a simple FastAPI application with PostgreSQL.

Step 3: Create the Project Structure

Create a new directory for your project and set up the following structure:

fastapi_postgresql/
│
├── app/
│   ├── main.py
│   ├── models.py
│   ├── database.py
│   └── crud.py
└── requirements.txt

Step 4: Setting Up Database Connection

In database.py, set up the database connection using SQLAlchemy:

# app/database.py
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

SQLALCHEMY_DATABASE_URL = "postgresql://fastapi_user:password@localhost/fastapi_db"

engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

Step 5: Define Your Models

In models.py, define your data models using SQLAlchemy:

# app/models.py
from sqlalchemy import Column, Integer, String
from .database import Base

class Item(Base):
    __tablename__ = "items"

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

Step 6: Create CRUD Operations

In crud.py, implement your CRUD operations:

# app/crud.py
from sqlalchemy.orm import Session
from . import models

def create_item(db: Session, name: str, description: str, price: int):
    db_item = models.Item(name=name, description=description, price=price)
    db.add(db_item)
    db.commit()
    db.refresh(db_item)
    return db_item

Step 7: Implement the FastAPI Application

In main.py, set up your FastAPI application:

# app/main.py
from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session
from . import models, crud
from .database import SessionLocal, engine

models.Base.metadata.create_all(bind=engine)

app = FastAPI()

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

@app.post("/items/")
def create_item(name: str, description: str, price: int, db: Session = Depends(get_db)):
    return crud.create_item(db=db, name=name, description=description, price=price)

Step 8: Run the Application

You can run your FastAPI application using Uvicorn:

uvicorn app.main:app --reload

Visit http://127.0.0.1:8000/docs to see the interactive API documentation.

Conclusion

Setting up FastAPI with PostgreSQL allows you to build scalable RESTful APIs efficiently. By leveraging the strengths of both FastAPI and PostgreSQL, you can create a robust application that handles complex data interactions. With this guide, you now have a solid foundation to build upon and explore more advanced features, such as authentication, testing, and more sophisticated data models. 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.