3-how-to-build-restful-apis-using-fastapi-with-postgresql.html

How to Build RESTful APIs Using FastAPI with PostgreSQL

In today's fast-paced digital landscape, creating efficient and scalable web applications is a fundamental skill for developers. FastAPI, a modern web framework for building APIs with Python, offers a robust solution for developing RESTful services quickly and effectively. Coupled with PostgreSQL, a powerful open-source relational database, you can build applications that not only perform well but also scale seamlessly. In this article, we’ll explore how to build RESTful APIs using FastAPI and PostgreSQL, complete with code examples and step-by-step instructions.

What is FastAPI?

FastAPI is a Python web framework designed for building APIs quickly and efficiently. It is powered by Starlette for the web parts and Pydantic for the data parts. FastAPI is known for its speed, ease of use, and automatic generation of documentation, making it an ideal choice for developers looking to create RESTful APIs.

Key Features of FastAPI

  • Fast Performance: FastAPI is one of the fastest web frameworks available, thanks to its asynchronous capabilities.
  • Automatic Documentation: FastAPI automatically generates interactive API documentation using OpenAPI and Swagger UI.
  • Data Validation: Built-in data validation using Pydantic ensures that incoming data is accurate and adheres to specified types.

Why Choose PostgreSQL?

PostgreSQL is a powerful, open-source object-relational database system. Its robust feature set, including support for complex queries, transactions, and extensibility, makes it a popular choice for developers building data-driven applications.

Benefits of Using PostgreSQL

  • ACID Compliance: Guarantees reliable transactions and data integrity.
  • Rich Data Types: Supports a variety of data types, including JSON, arrays, and more.
  • Scalability: Handles large volumes of data and concurrent users efficiently.

Setting Up Your Environment

Before diving into the code, ensure you have the following installed:

  • Python 3.7 or higher
  • PostgreSQL
  • pip (Python package installer)

You can install FastAPI and the PostgreSQL driver (asyncpg) using pip:

pip install fastapi uvicorn[standard] asyncpg sqlalchemy

Step-by-Step Guide to Building a RESTful API

1. Create the Database and Table

Start by creating a PostgreSQL database. You can do this through the PostgreSQL command line or a graphical interface like pgAdmin.

CREATE DATABASE fastapi_db;

\c fastapi_db

CREATE TABLE items (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100),
    description TEXT,
    price NUMERIC
);

2. Setting Up FastAPI

Create a new Python file (e.g., main.py) and set up the FastAPI application.

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

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

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

app = FastAPI()

3. Define Your Data Model

Using SQLAlchemy, define your data model for the items table.

class Item(Base):
    __tablename__ = "items"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, index=True)
    description = Column(String)
    price = Column(Numeric)

Base.metadata.create_all(bind=engine)

4. Create CRUD Operations

Next, implement the CRUD (Create, Read, Update, Delete) operations for your API.

Create an Item

from fastapi import HTTPException

@app.post("/items/", response_model=Item)
async def create_item(item: Item):
    db = SessionLocal()
    db.add(item)
    db.commit()
    db.refresh(item)
    return item

Read All Items

@app.get("/items/", response_model=list[Item])
async def read_items():
    db = SessionLocal()
    items = db.query(Item).all()
    return items

Update an Item

@app.put("/items/{item_id}", response_model=Item)
async def update_item(item_id: int, item: Item):
    db = SessionLocal()
    db_item = db.query(Item).filter(Item.id == item_id).first()
    if not db_item:
        raise HTTPException(status_code=404, detail="Item not found")

    db_item.name = item.name
    db_item.description = item.description
    db_item.price = item.price
    db.commit()
    db.refresh(db_item)
    return db_item

Delete an Item

@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
    db = SessionLocal()
    db_item = db.query(Item).filter(Item.id == item_id).first()
    if not db_item:
        raise HTTPException(status_code=404, detail="Item not found")

    db.delete(db_item)
    db.commit()
    return {"detail": "Item deleted"}

5. Running Your API

Finally, you can run your FastAPI application with the following command:

uvicorn main:app --reload

You can now access your API at http://127.0.0.1:8000/items/ and test the various endpoints with tools like Postman or curl.

Conclusion

Building RESTful APIs with FastAPI and PostgreSQL is a straightforward process that combines the power of Python with a robust database system. By following the steps outlined in this article, you can create a fully functional API that meets your application's needs. FastAPI’s speed and ease of use, combined with PostgreSQL’s scalability and reliability, make this combination an excellent choice for modern web development.

Key Takeaways

  • FastAPI simplifies the process of building APIs with automatic documentation and validation.
  • PostgreSQL is ideal for applications requiring complex data handling and transactions.
  • Following modular coding practices ensures your API is maintainable and scalable.

With this foundational knowledge, you are well on your way to creating high-performance APIs that can grow with your 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.