2-creating-a-restful-api-using-fastapi-and-postgresql.html

Creating a RESTful API Using FastAPI and PostgreSQL

In the world of web development, creating robust APIs is essential for building scalable applications. FastAPI, a modern web framework for building APIs with Python 3.6+ based on standard Python type hints, has gained significant popularity due to its speed and ease of use. When paired with PostgreSQL, a powerful and open-source relational database, you can create a performance-oriented RESTful API that can handle complex queries and large datasets. In this article, we will walk through the steps to create a RESTful API using FastAPI and PostgreSQL, complete with code examples and actionable insights.

What is FastAPI?

FastAPI is a high-performance web framework for building APIs with Python. Here are some of its key features:

  • Fast: Very high performance, on par with Node.js and Go.
  • Easy: Designed to be easy to use and learn.
  • Automatic Documentation: Generates OpenAPI documentation automatically.
  • Type hints: Leverages Python type hints to validate request and response data.

Why Use PostgreSQL?

PostgreSQL is an advanced, enterprise-class open-source relational database. It is known for:

  • ACID Compliance: Ensures reliable transactions.
  • Extensibility: Custom data types, functions, and operators.
  • Rich Query Capabilities: Supports complex queries, making it ideal for large applications.

Setting Up Your Environment

Prerequisites

Before getting started, make sure you have the following:

  • Python 3.6 or higher installed.
  • PostgreSQL installed and running.
  • Basic knowledge of Python and SQL.

Installation

You can install FastAPI and the required libraries using pip:

pip install fastapi[all] psycopg2-binary
  • fastapi[all]: Installs FastAPI along with all optional dependencies, including uvicorn, which is an ASGI server for running your FastAPI application.
  • psycopg2-binary: A PostgreSQL adapter for Python.

Creating Your FastAPI Application

Step 1: Project Structure

Create a project directory with the following structure:

/fastapi_postgres
    ├── main.py
    ├── models.py
    ├── schemas.py
    ├── database.py

Step 2: Database Connection

In database.py, set up your PostgreSQL connection:

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

DATABASE_URL = "postgresql://user:password@localhost/db_name"

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

Replace user, password, and db_name with your PostgreSQL credentials.

Step 3: Defining Models

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

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)

Step 4: Creating Pydantic Schemas

In schemas.py, define your data validation schemas using Pydantic:

from pydantic import BaseModel

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

class Item(ItemCreate):
    id: int

    class Config:
        orm_mode = True

Step 5: CRUD Operations

Now, let’s implement the CRUD operations in main.py:

from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session
from . import models, schemas
from .database import SessionLocal, engine

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

app = FastAPI()

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

@app.post("/items/", response_model=schemas.Item)
def create_item(item: schemas.ItemCreate, db: Session = Depends(get_db)):
    db_item = models.Item(name=item.name, description=item.description)
    db.add(db_item)
    db.commit()
    db.refresh(db_item)
    return db_item

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

Step 6: Running the Application

To run your FastAPI application, execute the following command in your terminal:

uvicorn main:app --reload

This command starts the server with live reload enabled, so any changes you make will be immediately reflected.

Testing Your API

You can test your API using tools like Postman or Curl. Here’s how to create a new item:

curl -X POST "http://127.0.0.1:8000/items/" -H "Content-Type: application/json" -d '{"name": "Sample Item", "description": "This is a sample item."}'

To retrieve an item:

curl -X GET "http://127.0.0.1:8000/items/1"

Conclusion

Creating a RESTful API using FastAPI and PostgreSQL is a straightforward process that can be completed in just a few steps. FastAPI’s integration with SQLAlchemy simplifies database interactions, while PostgreSQL provides a robust back-end solution. The combination of these technologies offers a powerful platform for developing modern web applications.

With the foundational knowledge from this article, you can further expand your API by adding authentication, testing, or more complex query capabilities. 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.