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

How to Create a RESTful API with FastAPI and PostgreSQL

In today’s digital landscape, building a robust and scalable API is crucial for any application that interacts with data. FastAPI, a modern Python web framework, makes it easy to build APIs quickly and efficiently. When combined with PostgreSQL, a powerful relational database, you can create a RESTful API that is not only fast but also reliable. In this article, we’ll explore how to set up a RESTful API using FastAPI and PostgreSQL, complete with detailed code examples and best practices.

What is FastAPI?

FastAPI is a web framework for building APIs with Python 3.6+ based on standard Python type hints. It is designed to be easy to use and to help developers create APIs quickly while ensuring high performance. FastAPI leverages asynchronous programming features seamlessly, making it perfect for modern applications that require real-time data processing.

Key Features of FastAPI:

  • Automatic generation of OpenAPI documentation: FastAPI automatically generates detailed API documentation, making it easier for developers to understand and use your API.
  • High performance: FastAPI is built on top of Starlette for the web parts and Pydantic for the data parts, ensuring high performance and ease of use.
  • Type validation: Using Python type hints, FastAPI validates request and response data, reducing the chances of runtime errors.

What is PostgreSQL?

PostgreSQL is an open-source, object-relational database system known for its robustness, scalability, and support for advanced data types. It’s an excellent choice for applications that require complex queries, high concurrency, and data integrity.

Why Use PostgreSQL?

  • ACID compliance: Ensures reliable transactions and data integrity.
  • Support for JSON data types: Allows for flexible data modeling.
  • Extensibility: You can define your own data types, operators, and index types.

Setting Up the Environment

To get started, you need to have Python, FastAPI, and PostgreSQL installed. You can set up your environment by following these steps:

  1. Install Python: Ensure you have Python 3.6 or higher installed.
  2. Create a virtual environment: bash python -m venv fastapi-env source fastapi-env/bin/activate # On Windows: fastapi-env\Scripts\activate
  3. Install FastAPI and an ASGI server: bash pip install fastapi uvicorn
  4. Install PostgreSQL: Follow instructions on the PostgreSQL official site to install PostgreSQL.

  5. Install a PostgreSQL adapter for Python: bash pip install asyncpg sqlalchemy

Creating the FastAPI Application

Now that your environment is set up, let’s create a simple FastAPI application that interacts with a PostgreSQL database.

Step 1: Setting Up the Database

First, create a PostgreSQL database. You can do this by accessing the PostgreSQL shell:

CREATE DATABASE fastapi_db;

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

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

Step 2: Building the FastAPI Application

Now, let’s create a file named main.py and start building our FastAPI application.

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session

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

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

# Pydantic model
class Item(BaseModel):
    id: int
    name: str
    description: str

# SQLAlchemy model
class ItemModel(Base):
    __tablename__ = "items"
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, index=True)
    description = Column(String)

# Create FastAPI instance
app = FastAPI()

# CRUD Operations
@app.post("/items/", response_model=Item)
def create_item(item: Item):
    db: Session = SessionLocal()
    db_item = ItemModel(name=item.name, description=item.description)
    db.add(db_item)
    db.commit()
    db.refresh(db_item)
    db.close()
    return db_item

@app.get("/items/{item_id}", response_model=Item)
def read_item(item_id: int):
    db: Session = SessionLocal()
    item = db.query(ItemModel).filter(ItemModel.id == item_id).first()
    db.close()
    if item is None:
        raise HTTPException(status_code=404, detail="Item not found")
    return item

Step 3: Running the Application

To run your FastAPI application, use Uvicorn:

uvicorn main:app --reload

This command starts the server, and you can access your API at http://127.0.0.1:8000/items/.

Step 4: Testing the API

You can use tools like Postman or cURL to test your API. Here are some example requests:

  • Create an Item: bash curl -X POST "http://127.0.0.1:8000/items/" -H "Content-Type: application/json" -d '{"name":"Sample Item", "description":"This is a sample item."}'

  • Get an Item: bash curl -X GET "http://127.0.0.1:8000/items/1"

Troubleshooting Common Issues

  • Database Connection Errors: Ensure that your PostgreSQL service is running and that your connection string is correct.
  • Dependency Conflicts: Use a virtual environment to avoid conflicts between package versions.

Conclusion

Creating a RESTful API with FastAPI and PostgreSQL is a straightforward process that can significantly enhance your application’s functionality. By using FastAPI’s features like automatic documentation and type validation, you can focus on building a robust backend while ensuring high performance. With the foundational knowledge provided in this article, you can expand your API further by adding more complex functionalities, implementing authentication, and more.

Start building your FastAPI application today and take your 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.