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

Creating a RESTful API with FastAPI and PostgreSQL

In today’s digital landscape, RESTful APIs (Representational State Transfer APIs) are essential for web applications, enabling smooth communication between the client and server. FastAPI, a modern and fast web framework for building APIs with Python, has gained immense popularity due to its ease of use and performance. When combined with PostgreSQL, a powerful relational database, you can create robust applications that are both efficient and scalable. In this article, we will dive deep into creating a RESTful API using FastAPI and PostgreSQL, covering everything from setup to implementation.

What is FastAPI?

FastAPI is a Python web framework designed for building APIs quickly, with minimal effort. It is based on standard Python type hints, which helps with data validation and serialization while providing automatic OpenAPI documentation. FastAPI is renowned for its performance, making it one of the fastest frameworks available for building web applications.

Key Features of FastAPI

  • Asynchronous Support: FastAPI allows you to write asynchronous code using async and await, making it ideal for I/O-bound applications.
  • Automatic Documentation: It generates interactive API documentation using Swagger UI and ReDoc.
  • Data Validation: Utilizes Python type hints for automatic request and response validation.
  • Modularity: FastAPI promotes a modular approach, facilitating easier testing and maintenance.

What is PostgreSQL?

PostgreSQL is an open-source relational database management system known for its robustness, flexibility, and performance. It supports advanced data types and offers powerful features like ACID compliance, making it a preferred choice for many developers.

Benefits of Using PostgreSQL

  • ACID Compliance: Ensures reliable transactions.
  • Rich Data Types: Supports JSON, XML, and arrays among others.
  • Extensibility: Allows custom functions and data types to be created.
  • Strong Community Support: Active development and a wealth of resources available.

Setting Up the Environment

Before diving into coding, you need to set up your development environment. Here’s how:

Prerequisites

  1. Python 3.6 or higher: Ensure you have Python installed.
  2. PostgreSQL: Install PostgreSQL on your machine or use a cloud service.
  3. Virtual Environment: It's best practice to create a virtual environment for your project.

Installation Steps

  1. Create a Virtual Environment: bash python3 -m venv fastapi-env source fastapi-env/bin/activate # On Windows use fastapi-env\Scripts\activate

  2. Install FastAPI and Uvicorn: bash pip install fastapi uvicorn

  3. Install Asyncpg: This is the PostgreSQL driver for Python. bash pip install asyncpg

  4. Install SQLAlchemy: For ORM (Object Relational Mapping). bash pip install sqlalchemy

Creating the FastAPI Application

Now that your environment is set up, let’s create a simple RESTful API. We'll build a basic application to manage a list of books.

Project Structure

fastapi_postgresql/
│
├── main.py
├── models.py
├── database.py
└── schemas.py

Step 1: Setting Up Database Connection

database.py:

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

DATABASE_URL = "postgresql+asyncpg://username:password@localhost/dbname"  # Update with your credentials

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

Step 2: Defining Models

models.py:

from sqlalchemy import Column, Integer, String
from database import Base

class Book(Base):
    __tablename__ = "books"

    id = Column(Integer, primary_key=True, index=True)
    title = Column(String, index=True)
    author = Column(String, index=True)

Step 3: Creating Pydantic Schemas

schemas.py:

from pydantic import BaseModel

class BookBase(BaseModel):
    title: str
    author: str

class BookCreate(BookBase):
    pass

class Book(BookBase):
    id: int

    class Config:
        orm_mode = True

Step 4: Building the API Endpoints

main.py:

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

Base.metadata.create_all(bind=engine)

app = FastAPI()

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

@app.post("/books/", response_model=schemas.Book)
async def create_book(book: schemas.BookCreate, db: Session = Depends(get_db)):
    db_book = Book(title=book.title, author=book.author)
    db.add(db_book)
    db.commit()
    db.refresh(db_book)
    return db_book

@app.get("/books/{book_id}", response_model=schemas.Book)
async def read_book(book_id: int, db: Session = Depends(get_db)):
    db_book = db.query(Book).filter(Book.id == book_id).first()
    if db_book is None:
        raise HTTPException(status_code=404, detail="Book not found")
    return db_book

Step 5: Running the Application

Run your FastAPI application using Uvicorn:

uvicorn main:app --reload

Navigate to http://127.0.0.1:8000/docs to explore your API with interactive Swagger documentation.

Conclusion

Creating a RESTful API with FastAPI and PostgreSQL is a straightforward process that combines the power of a modern web framework with a robust database. This article walked you through the essential steps from setup to implementation, emphasizing code organization and modularity. As you continue to develop your API, consider exploring more advanced features such as authentication, middleware, and asynchronous operations to enhance your application's performance and security.

By mastering FastAPI and PostgreSQL, you can create high-performance applications that meet the demands of today’s users while ensuring maintainability and scalability for the future. 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.