creating-a-restful-api-with-fastapi-and-postgresql-for-data-driven-applications.html

Creating a RESTful API with FastAPI and PostgreSQL for Data-Driven Applications

In today’s fast-paced digital world, building robust and scalable applications is crucial. One of the most effective ways to achieve this is by creating a RESTful API that can interact seamlessly with a relational database. FastAPI, a modern web framework for Python, combined with PostgreSQL, a powerful open-source relational database, offers the perfect foundation for developing data-driven applications. In this article, we’ll explore how to create a RESTful API with FastAPI and PostgreSQL, providing you with actionable insights, clear code examples, and troubleshooting tips along the way.

What is FastAPI?

FastAPI is a high-performance web framework built on top of Starlette and Pydantic. Its key features include:

  • Fast: As the name suggests, FastAPI is designed for speed. It utilizes asynchronous programming to handle requests efficiently.
  • Easy to Use: The framework simplifies API development with auto-generated documentation and validation.
  • Type Checking: FastAPI leverages Python type hints, allowing for robust error handling and improved developer experience.

What is PostgreSQL?

PostgreSQL is an advanced, open-source relational database management system (RDBMS) known for its reliability, feature robustness, and performance. Key features include:

  • ACID Compliance: Ensures reliable transactions.
  • Complex Queries: Supports advanced SQL queries with ease.
  • Extensibility: Allows for custom data types and functions.

Use Cases for FastAPI and PostgreSQL

Creating a RESTful API with FastAPI and PostgreSQL is ideal for various applications, including:

  • Web Applications: Building interactive front-end applications that require a back-end API.
  • Mobile Applications: Providing mobile apps with data through a secure API.
  • Microservices: Developing small, modular services that communicate over HTTP.

Setting Up Your Development Environment

Prerequisites

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

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

Installation

To get started, create a project directory and install FastAPI and the required libraries:

mkdir fastapi-postgresql-api
cd fastapi-postgresql-api
python -m venv venv
source venv/bin/activate  # On Windows use `venv\Scripts\activate`
pip install fastapi[all] psycopg2-binary sqlalchemy

Creating a RESTful API

Database Configuration

First, we need a PostgreSQL database. Create a database named fastapi_db:

CREATE DATABASE fastapi_db;

Next, create a table for storing data. For this example, let's create a simple items table:

CREATE TABLE items (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100),
    description TEXT,
    price NUMERIC
);

FastAPI Application Structure

Now, let’s structure our FastAPI application. Create a new file named main.py:

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from sqlalchemy import create_engine, Column, Integer, String, Numeric
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session

DATABASE_URL = "postgresql://username:password@localhost/fastapi_db"  # Replace with your own credentials

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

app = FastAPI()

class Item(Base):
    __tablename__ = "items"
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, index=True)
    description = Column(String)
    price = Column(Numeric)

Base.metadata.create_all(bind=engine)

class ItemCreate(BaseModel):
    name: str
    description: str
    price: float

@app.post("/items/", response_model=ItemCreate)
def create_item(item: ItemCreate):
    db: Session = SessionLocal()
    db_item = Item(**item.dict())
    db.add(db_item)
    db.commit()
    db.refresh(db_item)
    db.close()
    return db_item

Adding CRUD Functionality

To complete our RESTful API, we need to implement additional CRUD operations. Let's expand our main.py to include retrieving, updating, and deleting items:

@app.get("/items/{item_id}", response_model=ItemCreate)
def read_item(item_id: int):
    db: Session = SessionLocal()
    item = db.query(Item).filter(Item.id == item_id).first()
    db.close()
    if item is None:
        raise HTTPException(status_code=404, detail="Item not found")
    return item

@app.put("/items/{item_id}", response_model=ItemCreate)
def update_item(item_id: int, item: ItemCreate):
    db: Session = SessionLocal()
    db_item = db.query(Item).filter(Item.id == item_id).first()
    if db_item is None:
        db.close()
        raise HTTPException(status_code=404, detail="Item not found")

    for key, value in item.dict().items():
        setattr(db_item, key, value)

    db.commit()
    db.refresh(db_item)
    db.close()
    return db_item

@app.delete("/items/{item_id}")
def delete_item(item_id: int):
    db: Session = SessionLocal()
    db_item = db.query(Item).filter(Item.id == item_id).first()
    if db_item is None:
        db.close()
        raise HTTPException(status_code=404, detail="Item not found")

    db.delete(db_item)
    db.commit()
    db.close()
    return {"detail": "Item deleted"}

Running the Application

To run your FastAPI application, execute the following command:

uvicorn main:app --reload

Visit http://127.0.0.1:8000/docs to see the auto-generated API documentation where you can test your endpoints.

Conclusion

Creating a RESTful API with FastAPI and PostgreSQL is a powerful way to support data-driven applications. This guide has provided a comprehensive overview of setting up your environment, creating a database, and implementing CRUD functionality. As you explore further, consider optimizing your API with authentication, pagination, and advanced query capabilities.

With FastAPI’s speed and PostgreSQL’s reliability, you’re well on your way to building efficient and scalable applications. 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.