3-building-a-restful-api-with-fastapi-and-postgresql.html

Building a RESTful API with FastAPI and PostgreSQL

In today's digital landscape, building responsive and efficient web applications is paramount. One of the most effective ways to manage data-driven applications is through RESTful APIs. FastAPI, a modern web framework for Python, combined with PostgreSQL, a powerful relational database, offers a robust solution for developing such APIs. This article will guide you through the process of building a RESTful API using FastAPI and PostgreSQL, complete with code examples and best practices.

What is FastAPI?

FastAPI is a Python web framework designed for building APIs quickly and efficiently. It emphasizes performance and ease of use, allowing developers to create RESTful services with minimal code. Some key features of FastAPI include:

  • Automatic data validation: Built-in support for Pydantic models.
  • Asynchronous support: Ideal for working with I/O-bound applications.
  • Interactive API documentation: Automatically generated using Swagger UI and ReDoc.

What is PostgreSQL?

PostgreSQL is an advanced open-source relational database management system. It is known for its robustness, extensibility, and compliance with SQL standards. PostgreSQL is widely used in various applications, from small projects to large-scale enterprise systems. Key characteristics include:

  • ACID compliance: Ensures reliable transactions.
  • Support for advanced data types: JSON, arrays, and more.
  • Extensible: Allows for custom functions and data types.

Use Cases for FastAPI and PostgreSQL

Building a RESTful API with FastAPI and PostgreSQL is suitable for various applications, including:

  • E-commerce platforms: Managing product inventories and user data.
  • Social media applications: Handling user profiles, posts, and interactions.
  • Data analytics services: Storing and retrieving large datasets efficiently.

Getting Started

Prerequisites

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

  1. Python 3.7 or higher
  2. PostgreSQL
  3. pip for package management

Step 1: Setting Up the Environment

First, create a virtual environment to manage your dependencies:

mkdir fastapi-postgresql
cd fastapi-postgresql
python -m venv venv
source venv/bin/activate  # On Windows use `venv\Scripts\activate`

Next, install FastAPI and an ASGI server (like Uvicorn), along with SQLAlchemy and psycopg2 for PostgreSQL interaction:

pip install fastapi[all] uvicorn sqlalchemy psycopg2

Step 2: Configuring PostgreSQL

  1. Create a PostgreSQL database:

Access your PostgreSQL shell and create a new database:

sql CREATE DATABASE fastapi_db;

  1. Create a table:

For this example, we'll create a simple items table:

sql CREATE TABLE items ( id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL, description TEXT, price NUMERIC(10, 2) NOT NULL );

Step 3: Building the FastAPI Application

Create a new file named main.py. This file will contain the logic for your FastAPI application.

Import Required Libraries

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

DATABASE_URL = "postgresql://user:password@localhost/fastapi_db"
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

app = FastAPI()

Define the SQLAlchemy Models

Create a model that reflects your items table:

class Item(Base):
    __tablename__ = "items"

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

Create Pydantic Models

Pydantic models help with data validation. Define an Item model:

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

class ItemResponse(ItemCreate):
    id: int

    class Config:
        orm_mode = True

Implementing CRUD Operations

Add endpoints for creating, reading, updating, and deleting items:

@app.post("/items/", response_model=ItemResponse)
def create_item(item: ItemCreate):
    db = SessionLocal()
    db_item = Item(name=item.name, description=item.description, price=item.price)
    db.add(db_item)
    db.commit()
    db.refresh(db_item)
    db.close()
    return db_item

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

@app.put("/items/{item_id}", response_model=ItemResponse)
def update_item(item_id: int, item: ItemCreate):
    db = 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 = 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"}

Step 4: Running the Application

Run the FastAPI application using Uvicorn:

uvicorn main:app --reload

Now, your API is running at http://127.0.0.1:8000. You can access the interactive documentation at http://127.0.0.1:8000/docs.

Conclusion

Building a RESTful API with FastAPI and PostgreSQL is an efficient way to manage data interactions in modern web applications. The combination of FastAPI's speed and PostgreSQL's reliability provides a powerful back-end solution. This guide has covered the essential steps to set up your API, including database configuration, CRUD operations, and best practices.

By following this approach, you can create scalable, maintainable, and performant APIs tailored to your application's needs. 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.