2-building-restful-apis-with-fastapi-and-postgresql-database.html

Building RESTful APIs with FastAPI and PostgreSQL Database

In the modern world of web development, creating efficient and scalable APIs is a necessity. As the demand for rapid application development grows, frameworks like FastAPI have emerged as robust tools for building RESTful APIs. In this article, we will explore how to build a RESTful API using FastAPI and a PostgreSQL database, providing you with a comprehensive guide full of code snippets and actionable insights.

What is FastAPI?

FastAPI is a modern web framework for building APIs with Python 3.7+ based on standard Python type hints. It is designed to be fast, simple, and easy to use, allowing developers to build APIs quickly and with fewer lines of code than traditional frameworks like Flask or Django.

Key Features of FastAPI

  • Fast Performance: Built on top of Starlette for the web parts and Pydantic for the data parts, FastAPI is one of the fastest Python frameworks available.
  • Automatic Documentation: FastAPI automatically generates interactive API documentation using Swagger UI and ReDoc.
  • Data Validation: Using Python type hints, FastAPI automatically validates request data, ensuring your API handles errors gracefully.

What is PostgreSQL?

PostgreSQL is an advanced relational database management system that is open-source and widely recognized for its reliability, feature robustness, and performance. It supports various data types and is particularly well-suited for complex queries and large datasets.

Why Use PostgreSQL with FastAPI?

  • ACID Compliance: Ensures data safety and integrity.
  • Scalability: Can handle large volumes of data efficiently.
  • Rich Querying Capabilities: Supports complex queries, making it ideal for data-intensive applications.

Setting Up Your Environment

Before we dive into coding, let’s set up our development environment.

Prerequisites

  • Python 3.7 or later
  • PostgreSQL installed and running
  • Basic understanding of Python and SQL

Step 1: Install Required Packages

Create a new directory for your project and navigate into it. Then, create a virtual environment and install FastAPI along with uvicorn (the ASGI server) and asyncpg (the PostgreSQL driver).

mkdir fastapi-postgres-api
cd fastapi-postgres-api
python -m venv venv
source venv/bin/activate  # On Windows use `venv\Scripts\activate`
pip install fastapi uvicorn asyncpg sqlalchemy

Step 2: Set Up PostgreSQL Database

Create a new PostgreSQL database and user. You can do this via the PostgreSQL command line or a GUI tool like pgAdmin.

CREATE DATABASE fastapi_db;
CREATE USER fastapi_user WITH PASSWORD 'password';
ALTER ROLE fastapi_user SET client_encoding TO 'utf8';
ALTER ROLE fastapi_user SET default_transaction_isolation TO 'read committed';
ALTER ROLE fastapi_user SET timezone TO 'UTC';
GRANT ALL PRIVILEGES ON DATABASE fastapi_db TO fastapi_user;

Building the API

Step 3: Create the Database Model

Now, let's create a simple model. For this example, we’ll build a basic API for managing tasks.

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

DATABASE_URL = "postgresql+asyncpg://fastapi_user:password@localhost/fastapi_db"

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

class Task(Base):
    __tablename__ = "tasks"

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

Base.metadata.create_all(bind=engine)

Step 4: Create a FastAPI Application

Now we will create our FastAPI app and define the endpoints.

from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session

app = FastAPI()

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

@app.post("/tasks/", response_model=Task)
async def create_task(task: Task, db: Session = Depends(get_db)):
    db.add(task)
    db.commit()
    db.refresh(task)
    return task

@app.get("/tasks/{task_id}", response_model=Task)
async def read_task(task_id: int, db: Session = Depends(get_db)):
    task = db.query(Task).filter(Task.id == task_id).first()
    if task is None:
        raise HTTPException(status_code=404, detail="Task not found")
    return task

Step 5: Run the Application

To run your FastAPI application, use the following command:

uvicorn main:app --reload

Step 6: Interacting with the API

With the server running, you can access the interactive API documentation at http://127.0.0.1:8000/docs. You can create tasks using the /tasks/ endpoint and retrieve them by their ID.

Troubleshooting Common Issues

Connection Errors

If you encounter connection errors, ensure that: - PostgreSQL is running. - The database URL is correctly formatted. - The user credentials are valid.

Dependency Issues

If you face issues related to missing packages, ensure your virtual environment is activated and all packages are correctly installed.

Conclusion

Building RESTful APIs with FastAPI and PostgreSQL is a powerful combination for developers looking to create scalable and efficient applications. FastAPI’s speed and ease of use, combined with PostgreSQL’s robustness, make this stack an excellent choice for both beginners and experienced developers.

By following the steps outlined in this article, you can set up your own API quickly and effectively. Whether you're creating a simple task manager or a complex application, FastAPI and PostgreSQL provide the tools you need to succeed in your development journey. 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.