3-how-to-create-a-restful-api-using-fastapi-and-postgresql.html

How to Create a RESTful API Using FastAPI and PostgreSQL

In the modern web development landscape, creating a robust and scalable application often hinges on the ability to build efficient APIs. RESTful APIs have become the standard for communication between clients and servers, and with tools like FastAPI and PostgreSQL, you can develop high-performance applications quickly and effectively. In this article, we will explore how to create a RESTful API using FastAPI and PostgreSQL, complete with code examples and actionable insights.

What is FastAPI?

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. It is designed to help developers create APIs quickly and with minimal effort while ensuring performance and automatic generation of OpenAPI documentation. FastAPI is particularly well-suited for creating RESTful APIs because it is asynchronous and supports both synchronous and asynchronous endpoint handling.

Key Features of FastAPI:

  • Performance: FastAPI is one of the fastest Python frameworks available, thanks to its asynchronous capabilities.
  • Easy to Use: With automatic data validation and serialization, developers can focus on writing business logic rather than boilerplate code.
  • Automatic Documentation: FastAPI automatically generates interactive API documentation using Swagger UI and ReDoc.

What is PostgreSQL?

PostgreSQL is an advanced, open-source relational database management system (RDBMS) that supports both SQL (relational) and JSON (non-relational) querying. It is renowned for its robustness, extensibility, and support for complex queries. PostgreSQL is an excellent choice for applications needing a reliable and scalable database.

Why Use PostgreSQL?

  • ACID Compliance: Ensures data integrity and reliability.
  • Extensibility: Allows for custom data types, operators, and functions.
  • Strong Community Support: A vast community means plenty of resources and plugins.

Setting Up Your Environment

Before we dive into coding, let's set up our development environment. You will need: - Python (version 3.6 or higher) - FastAPI - PostgreSQL - An ASGI server (e.g., Uvicorn)

Installation

You can install FastAPI and Uvicorn using pip:

pip install fastapi uvicorn psycopg2-binary

The psycopg2-binary package allows FastAPI to interact with PostgreSQL.

Setting Up PostgreSQL

  1. Install PostgreSQL: Follow the installation instructions for your operating system.
  2. Create a Database: Access the PostgreSQL interactive terminal and create a new database.
CREATE DATABASE myapi;
  1. Create a User: Create a user for the database.
CREATE USER myuser WITH PASSWORD 'mypassword';
GRANT ALL PRIVILEGES ON DATABASE myapi TO myuser;

Building the RESTful API

Project Structure

Create the following project structure:

myapi/
│
├── main.py
├── models.py
└── database.py

Step 1: Database Connection

In database.py, set up the connection to your PostgreSQL database.

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

DATABASE_URL = "postgresql://myuser:mypassword@localhost/myapi"

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

Step 2: Define Your Data Models

Next, define your data models in models.py. For example, let's create a simple Item model.

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

class Item(Base):
    __tablename__ = 'items'

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

Step 3: Create the API Endpoints

In main.py, create the FastAPI app and define your API endpoints.

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

models.Base.metadata.create_all(bind=engine)

app = FastAPI()

# Dependency to get the database session
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# Create an item
@app.post("/items/")
def create_item(item: models.Item, db: Session = Depends(get_db)):
    db.add(item)
    db.commit()
    db.refresh(item)
    return item

# Read all items
@app.get("/items/")
def read_items(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)):
    items = db.query(models.Item).offset(skip).limit(limit).all()
    return items

# Read a single item
@app.get("/items/{item_id}")
def read_item(item_id: int, db: Session = Depends(get_db)):
    item = db.query(models.Item).filter(models.Item.id == item_id).first()
    if item is None:
        raise HTTPException(status_code=404, detail="Item not found")
    return item

Step 4: Running the API

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

uvicorn main:app --reload

Visit http://127.0.0.1:8000/docs to see the automatically generated API documentation and test your endpoints.

Conclusion

Creating a RESTful API with FastAPI and PostgreSQL is straightforward and efficient. FastAPI’s asynchronous capabilities and automatic documentation generation, combined with PostgreSQL’s powerful database features, provide a solid foundation for building modern web applications. Whether you are developing a small service or a large application, this combination can help streamline your development process.

Key Takeaways:

  • FastAPI and PostgreSQL are powerful tools for building RESTful APIs.
  • Setting up a basic API structure involves defining models, creating endpoints, and managing database connections.
  • FastAPI provides automatic documentation, making it easier to test and maintain your API.

With the knowledge gained from this article, you're now equipped to start building your own RESTful APIs using FastAPI and PostgreSQL. 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.