1-building-a-restful-api-with-fastapi-and-postgresql-integration.html

Building a RESTful API with FastAPI and PostgreSQL Integration

In the world of web development, creating efficient and scalable APIs is essential for modern applications. FastAPI, a modern web framework for building APIs with Python, paired with PostgreSQL, a powerful relational database, offers an excellent combination for developers. This article will take you through the process of building a RESTful API using FastAPI with PostgreSQL integration, complete with coding examples, actionable insights, and troubleshooting tips.

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 be easy to use while providing high performance. FastAPI is built on top of Starlette for the web parts and Pydantic for the data parts. It allows developers to create robust applications quickly and efficiently, thanks to automatic data validation, serialization, and interactive API documentation.

Key Features of FastAPI:

  • Fast: It is one of the fastest Python frameworks available.
  • Easy: Simple to set up and use, with intuitive syntax.
  • Automatic Documentation: Generates interactive API documentation via Swagger UI and ReDoc.
  • Data Validation: Leverages Python type hints for automatic data validation.

What is PostgreSQL?

PostgreSQL is an advanced open-source relational database management system (RDBMS) that supports SQL compliance, transactions, and complex queries. It is known for its reliability, robustness, and performance, making it a popular choice for applications requiring data integrity and complex queries.

Why Use PostgreSQL?

  • ACID Compliance: Ensures data reliability.
  • Extensibility: Supports custom data types and functions.
  • Rich Querying Capabilities: Advanced features like JSONB support for semi-structured data.

Setting Up the Environment

Before diving into the code, let's set up our development environment.

Prerequisites

  • Python 3.6 or later
  • PostgreSQL installed on your machine
  • Basic knowledge of Python and SQL

Installation

  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 Required Packages: bash pip install fastapi uvicorn psycopg2-binary sqlalchemy

  3. fastapi: The framework for building the API.

  4. uvicorn: An ASGI server for running FastAPI applications.
  5. psycopg2-binary: PostgreSQL adapter for Python.
  6. sqlalchemy: A SQL toolkit and Object-Relational Mapping (ORM) system.

Building the API

Now that our environment is set up, let’s start coding our API.

Step 1: Defining the Database Model

Create a new file named models.py to define our data model. For this example, we will create a simple Todo application.

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

class Todo(Base):
    __tablename__ = "todos"

    id = Column(Integer, primary_key=True, index=True)
    title = Column(String, index=True)
    description = Column(String)
    completed = Column(Integer, default=0)

Step 2: Setting Up the Database Connection

Create another file called database.py to handle the database connection.

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

SQLALCHEMY_DATABASE_URL = "postgresql://user:password@localhost/todo_db"

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

Step 3: Creating a CRUD Operations File

Now, let's create a file named crud.py to handle our create, read, update, and delete operations.

from sqlalchemy.orm import Session
from models import Todo

def get_todo(db: Session, todo_id: int):
    return db.query(Todo).filter(Todo.id == todo_id).first()

def get_todos(db: Session, skip: int = 0, limit: int = 10):
    return db.query(Todo).offset(skip).limit(limit).all()

def create_todo(db: Session, title: str, description: str):
    db_todo = Todo(title=title, description=description)
    db.add(db_todo)
    db.commit()
    db.refresh(db_todo)
    return db_todo

Step 4: Creating the FastAPI Application

Finally, let's put everything together in the main application file, main.py.

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

# Create the database tables
Base.metadata.create_all(bind=engine)

app = FastAPI()

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

@app.post("/todos/", response_model=Todo)
def create_todo(title: str, description: str, db: Session = Depends(get_db)):
    return crud.create_todo(db=db, title=title, description=description)

@app.get("/todos/{todo_id}", response_model=Todo)
def read_todo(todo_id: int, db: Session = Depends(get_db)):
    db_todo = crud.get_todo(db=db, todo_id=todo_id)
    if db_todo is None:
        raise HTTPException(status_code=404, detail="Todo not found")
    return db_todo

@app.get("/todos/", response_model=list[Todo])
def read_todos(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)):
    todos = crud.get_todos(db=db, skip=skip, limit=limit)
    return todos

Step 5: Running the Application

You can run your FastAPI application using Uvicorn. In your terminal, execute:

uvicorn main:app --reload

Troubleshooting Common Issues

  • Database Connection Issues: Ensure that your PostgreSQL server is running and that the credentials in database.py are correct.
  • Dependencies Not Found: Make sure you’ve activated your virtual environment and installed all required packages.
  • CORS Issues: If you are accessing the API from a web application, you may need to configure CORS in FastAPI.

Conclusion

Building a RESTful API with FastAPI and PostgreSQL is a straightforward process that combines the power of FastAPI's performance and PostgreSQL's data management capabilities. By following this guide, you have created a basic Todo API with CRUD functionality.

You can extend this API by adding user authentication, more complex data relationships, and advanced features like pagination and filtering. FastAPI, combined with PostgreSQL, offers a powerful toolkit for developers looking to create scalable and efficient web 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.