1-building-restful-apis-with-fastapi-and-postgresql.html

Building RESTful APIs with FastAPI and PostgreSQL

In today’s tech landscape, RESTful APIs have become the backbone of web applications, facilitating seamless communication between client and server. FastAPI, a modern web framework for building APIs with Python, coupled with PostgreSQL, a powerful relational database, makes for a robust combination to create high-performance applications. In this article, we will explore how to build a RESTful API using FastAPI and PostgreSQL, covering definitions, use cases, and practical coding examples.

What is FastAPI?

FastAPI is a Python web framework that allows developers to create APIs quickly and efficiently. It is designed to optimize performance and ease of use. Some of its standout features include:

  • Asynchronous Support: FastAPI is built on ASGI and supports asynchronous programming, making it ideal for handling multiple requests simultaneously.
  • Automatic Documentation: FastAPI automatically generates interactive API documentation using Swagger UI and ReDoc, making it easy for developers to test endpoints.
  • Data Validation: The framework uses Pydantic for data validation, which ensures that the data being processed meets the expected schema.

Why Use PostgreSQL?

PostgreSQL is a powerful, open-source object-relational database system known for its robustness and scalability. It supports advanced data types and offers excellent performance for complex queries. Here are some reasons to choose PostgreSQL:

  • ACID Compliance: Ensures reliable transactions.
  • Extensibility: Users can define their own data types and functions.
  • Rich Ecosystem: A wide array of extensions and tools to enhance functionality.

Setting Up Your Environment

Before we start coding, let’s set up our environment. Ensure you have Python 3.7 or later installed, along with pip. You will also need PostgreSQL installed and running on your machine.

Install Required Packages

Use the following command to install FastAPI and the database driver for PostgreSQL, asyncpg, along with an ASGI server like uvicorn:

pip install fastapi[all] asyncpg uvicorn

Creating Your First FastAPI Application

Let’s start by creating a simple FastAPI application. Create a new directory for your project and create a file named main.py.

Step 1: Setting Up FastAPI

Here’s a basic FastAPI application:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Welcome to FastAPI with PostgreSQL!"}

Step 2: Running the Application

To run your FastAPI application, use the following command:

uvicorn main:app --reload

Visit http://127.0.0.1:8000 in your browser, and you should see the welcome message.

Connecting to PostgreSQL

To connect FastAPI to PostgreSQL, you will need to use an ORM (Object-Relational Mapping). SQLAlchemy is a popular choice for this purpose. First, install SQLAlchemy and the asyncpg driver:

pip install sqlalchemy databases

Step 3: Database Configuration

Let’s create a database connection in main.py. Replace the contents of your main.py file with the following code:

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

DATABASE_URL = "postgresql+asyncpg://user:password@localhost/dbname"

database = Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()

Base = declarative_base()

class Item(Base):
    __tablename__ = "items"
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, index=True)

app = FastAPI()

@app.on_event("startup")
async def startup():
    await database.connect()

@app.on_event("shutdown")
async def shutdown():
    await database.disconnect()

Ensure you replace user, password, and dbname with your PostgreSQL credentials.

Creating RESTful Endpoints

Now that we have our database connection set up, let’s create RESTful endpoints to manage items in our database.

Step 4: CRUD Operations

We will implement the following CRUD operations:

  • Create: Add a new item.
  • Read: Retrieve an item or all items.
  • Update: Modify an existing item.
  • Delete: Remove an item.

Here’s how you can implement these operations:

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List

class ItemIn(BaseModel):
    name: str

class ItemOut(ItemIn):
    id: int

@app.post("/items/", response_model=ItemOut)
async def create_item(item: ItemIn):
    query = Item.__table__.insert().values(name=item.name)
    last_record_id = await database.execute(query)
    return {**item.dict(), "id": last_record_id}

@app.get("/items/", response_model=List[ItemOut])
async def read_items():
    query = Item.__table__.select()
    return await database.fetch_all(query)

@app.get("/items/{item_id}", response_model=ItemOut)
async def read_item(item_id: int):
    query = Item.__table__.select().where(Item.id == item_id)
    item = await database.fetch_one(query)
    if item is None:
        raise HTTPException(status_code=404, detail="Item not found")
    return item

@app.put("/items/{item_id}", response_model=ItemOut)
async def update_item(item_id: int, item: ItemIn):
    query = Item.__table__.update().where(Item.id == item_id).values(name=item.name)
    await database.execute(query)
    return {**item.dict(), "id": item_id}

@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
    query = Item.__table__.delete().where(Item.id == item_id)
    await database.execute(query)
    return {"message": "Item deleted successfully!"}

Step 5: Testing Your API

With the endpoints created, you can use tools like Postman or curl to test your API. Here’s how to test the create_item endpoint using curl:

curl -X POST "http://127.0.0.1:8000/items/" -H "Content-Type: application/json" -d '{"name": "Sample Item"}'

Conclusion

Building RESTful APIs with FastAPI and PostgreSQL is a powerful way to create fast and efficient web applications. Throughout this article, we covered the essential components to get you started, including setting up your environment, connecting to PostgreSQL, and implementing CRUD operations.

FastAPI's ease of use, combined with PostgreSQL's reliability, offers developers a great toolkit for creating scalable applications. As you continue to build on this foundation, consider diving deeper into FastAPI's advanced features, such as authentication, background tasks, and dependency injection, to further enhance your API.

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.