creating-a-restful-api-with-fastapi-and-postgresql.html

Creating a RESTful API with FastAPI and PostgreSQL

Building a RESTful API is an essential skill in today's software development landscape. With the rise of microservices and cloud-native applications, APIs are the backbone of modern applications. In this article, we will explore how to create a RESTful API using FastAPI, a modern web framework for Python, and PostgreSQL, a powerful relational database.

What is FastAPI?

FastAPI is a high-performance web framework for building APIs with Python 3.6+ based on standard Python type hints. It is designed to make API development fast and straightforward, focusing on:

  • Speed: FastAPI is one of the fastest Python frameworks available, thanks to its asynchronous capabilities.
  • Ease of Use: The framework is user-friendly and offers automatic generation of OpenAPI documentation.
  • Type Safety: With Python type hints, you can catch errors early in the development process.

Why Use PostgreSQL?

PostgreSQL is an advanced, open-source relational database that is known for its reliability, robustness, and performance. Some reasons to use PostgreSQL include:

  • ACID Compliance: Ensures data integrity even in the event of a failure.
  • Extensibility: Supports various data types and can be extended with custom functions.
  • Strong Community Support: A large community of users and developers contributes to its continuous improvement.

Setting Up the Environment

Before we dive into the code, let’s set up our development environment. You will need:

  • Python 3.6 or higher
  • FastAPI
  • PostgreSQL
  • SQLAlchemy (for ORM)
  • Uvicorn (ASGI server)

Step 1: Install Required Packages

First, create a new Python environment and install the necessary packages. You can do this using pip:

pip install fastapi uvicorn sqlalchemy psycopg2

Step 2: Set Up PostgreSQL

Next, you need to set up a PostgreSQL database:

  1. Install PostgreSQL on your machine or use a cloud-based service.
  2. Create a new database:
CREATE DATABASE fastapi_db;
  1. Create a user and grant permissions:
CREATE USER fastapi_user WITH PASSWORD 'your_password';
GRANT ALL PRIVILEGES ON DATABASE fastapi_db TO fastapi_user;

Building the FastAPI Application

Step 3: Project Structure

Create a new directory for your FastAPI project, and inside that directory, create the following structure:

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

Step 4: Database Connection

In database.py, we will set up a connection to the PostgreSQL database using SQLAlchemy.

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

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

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

Step 5: Create Models

In models.py, define your database models. For this example, let’s create a simple Item model.

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, index=True)

Step 6: Create Schemas

In schemas.py, define the Pydantic models that validate the data coming to and from the API.

from pydantic import BaseModel

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

class ItemCreate(ItemBase):
    pass

class Item(ItemBase):
    id: int

    class Config:
        orm_mode = True

Step 7: Create the API Endpoints

Now, let’s create the main API 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(**item.dict())
    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 8: Run the Application

You can now run your FastAPI application using Uvicorn:

uvicorn main:app --reload

Testing the API

Once your server is running, you can test the API endpoints using tools like Postman or directly in the browser by navigating to http://127.0.0.1:8000/items/.

Example Requests

  • Create Item: POST to /items/ with JSON body: json { "name": "Sample Item", "description": "This is a sample item." }

  • Get Item: GET from /items/{item_id}.

Conclusion

Creating a RESTful API using FastAPI and PostgreSQL is straightforward and efficient. With FastAPI’s speed and ease of use, combined with PostgreSQL’s robust features, you can build powerful APIs that are capable of handling real-world applications.

By following the steps outlined in this article, you now have a foundational API that you can expand upon, adding more features and functionality as needed. 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.