2-how-to-create-a-rest-api-with-fastapi-and-postgresql.html

How to Create a REST API with FastAPI and PostgreSQL

Creating a REST API is a critical skill for developers, especially with the growing demand for web applications. FastAPI, a modern Python web framework, stands out for its speed and ease of use, while PostgreSQL is a powerful open-source relational database. In this article, we will walk through the steps to create a REST API using FastAPI and PostgreSQL, complete with code examples and actionable insights.

What is FastAPI?

FastAPI is an asynchronous web framework for building APIs with Python 3.7+ based on standard Python type hints. It's designed to be fast, both in terms of performance and ease of development. The framework is built on top of Starlette for the web parts and Pydantic for the data parts.

Key Features of FastAPI:

  • Fast: High performance, on par with NodeJS and Go.
  • Easy to Use: Designed for ease of use, with automatic data validation and serialization.
  • Type Hints: Utilizes Python type hints to provide better editor support and automatic documentation (using Swagger UI).
  • Asynchronous: Supports async and await, allowing high concurrency.

What is PostgreSQL?

PostgreSQL is an advanced, open-source relational database management system known for its robustness, scalability, and support for complex queries. It is widely used in web applications and enterprise-level solutions.

Why Use PostgreSQL?

  • ACID Compliance: Guarantees reliable transactions.
  • Extensibility: Allows users to define their own data types, operators, and functional languages.
  • Rich Data Types: Supports JSON, XML, and other data types, making it versatile for various applications.

Use Cases for FastAPI and PostgreSQL

FastAPI combined with PostgreSQL is ideal for:

  • Building microservices.
  • Creating data-driven applications.
  • Developing applications requiring real-time capabilities.
  • APIs that need to serve large amounts of data efficiently.

Getting Started

Prerequisites

Before we begin, you’ll need:

  • Python 3.7 or later installed.
  • PostgreSQL installed and running.
  • Basic knowledge of Python and RESTful APIs.

Step 1: Set Up Your Environment

  1. Install FastAPI and an ASGI server (e.g., uvicorn): bash pip install fastapi uvicorn

  2. Install the PostgreSQL driver: bash pip install asyncpg sqlalchemy databases

  3. Install Pydantic for data validation (this comes with FastAPI, but it’s good to know): bash pip install pydantic

Step 2: Create a PostgreSQL Database

  1. Open your PostgreSQL command line or use a GUI tool like pgAdmin.
  2. Create a new database: sql CREATE DATABASE fastapi_db;

  3. Create a new user (if needed): sql CREATE USER fastapi_user WITH PASSWORD 'your_password'; GRANT ALL PRIVILEGES ON DATABASE fastapi_db TO fastapi_user;

Step 3: Define the Database Models

Create a new file called models.py and define your database models using SQLAlchemy.

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)

Step 4: Set Up the Database Connection

Create a new file named database.py to manage the database connection.

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

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

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

Step 5: Create the FastAPI App

Create a new file called main.py for the FastAPI application.

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

Base.metadata.create_all(bind=engine)

app = FastAPI()

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

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

Step 6: Run the Application

In your terminal, run the FastAPI application with uvicorn:

uvicorn main:app --reload

This command starts your API, and you can access the automatically generated documentation at http://127.0.0.1:8000/docs.

Step 7: Test Your API

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": "Test Item", "description": "This is a test item."}'

Conclusion

In this article, we showcased how to create a REST API with FastAPI and PostgreSQL. FastAPI provides a simple yet powerful framework for building APIs, while PostgreSQL offers robust data management capabilities. With this foundational knowledge, you can expand your API with more functionality, such as authentication, data validation, and more complex queries.

Next Steps

  • Explore FastAPI’s dependency injection system.
  • Add error handling to your API.
  • Implement user authentication and authorization.
  • Experiment with async endpoints for improved performance.

By following these steps, you’ll be well on your way to mastering FastAPI and PostgreSQL, setting the stage for building efficient and scalable APIs!

SR
Syed
Rizwan

About the Author

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