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

Building a RESTful API with FastAPI and PostgreSQL

In today’s fast-paced software development landscape, building efficient and scalable RESTful APIs is a crucial skill. FastAPI, a modern web framework for Python, provides an intuitive way to create RESTful services, while PostgreSQL offers a powerful and reliable database solution. In this article, we will walk through the process of building a RESTful API using FastAPI and PostgreSQL, complete with code examples and actionable insights.

What is FastAPI?

FastAPI is a web framework designed for building APIs with Python 3.6+ based on standard Python type hints. It leverages the asynchronous capabilities of Python, making it one of the fastest frameworks available. Some of its key features include:

  • Automatic generation of OpenAPI documentation.
  • Validation of request and response data.
  • Support for asynchronous programming.

What is PostgreSQL?

PostgreSQL is an open-source relational database management system (RDBMS) known for its robustness, extensibility, and support for advanced data types. It's an excellent choice for applications that require complex queries and transactions.

Use Cases for FastAPI and PostgreSQL

Building a RESTful API with FastAPI and PostgreSQL is ideal for:

  • Web applications: Facilitating communication between the client and server.
  • Microservices: Creating modular services that can be scaled independently.
  • Data-driven applications: Handling data management with efficiency and reliability.

Setting Up the Environment

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

Prerequisites

  1. Python 3.6 or higher
  2. PostgreSQL installed
  3. Basic knowledge of Python

Step 1: Install Required Packages

Use pip to install FastAPI and an ASGI server, such as uvicorn, along with asyncpg for PostgreSQL interaction.

pip install fastapi uvicorn asyncpg sqlalchemy

Step 2: Set Up PostgreSQL Database

Create a new PostgreSQL database for your API. You can do this using the PostgreSQL command line or any database management tool.

CREATE DATABASE fastapi_db;

Next, create a table to store your data. For this example, let’s create a simple items table:

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

Building the RESTful API

Now that we have our environment set up, let’s start coding our FastAPI application.

Step 3: Create the Main Application File

Create a new Python file, main.py, and set up a basic 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://user:password@localhost/fastapi_db"

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

app = FastAPI()

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)

Step 4: Define API Routes

Next, let’s define some routes for our API.

Creating a New Item

from fastapi import HTTPException
from pydantic import BaseModel

class ItemCreate(BaseModel):
    name: str
    description: str
    price: float

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

Retrieving All Items

@app.get("/items/")
async def read_items():
    db = SessionLocal()
    items = db.query(Item).all()
    db.close()
    return items

Retrieving a Single Item

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    db = SessionLocal()
    item = db.query(Item).filter(Item.id == item_id).first()
    db.close()

    if item is None:
        raise HTTPException(status_code=404, detail="Item not found")
    return item

Step 5: Run the Application

To run your FastAPI application, execute the following command in your terminal:

uvicorn main:app --reload

Visit http://127.0.0.1:8000/docs in your browser to see the automatically generated API documentation.

Testing the API

You can test your API using tools like Postman or directly via the Swagger UI provided by FastAPI at /docs. Here, you can create, read, update, and delete items.

Troubleshooting Common Issues

  • Database Connection Errors: Ensure your PostgreSQL server is running and the connection string is correct.
  • Dependency Issues: Make sure all required packages are installed and up to date.
  • CORS Issues: If you're accessing your API from a different domain, consider adding CORS middleware.

Conclusion

Building a RESTful API with FastAPI and PostgreSQL is a seamless process that offers high performance and ease of use. With FastAPI’s asynchronous capabilities and PostgreSQL’s powerful database features, you can create robust and scalable applications quickly. Whether you're developing a web application, a microservice, or a data-driven solution, this combination is a solid choice for modern development. Start implementing these concepts today and take your API development skills to the next level!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.