how-to-create-restful-apis-with-fastapi-and-postgresql.html

How to Create RESTful APIs with FastAPI and PostgreSQL

In today's digital landscape, building efficient and scalable web applications is crucial for success. One of the most effective ways to achieve this is by creating RESTful APIs. FastAPI, a modern web framework for Python, paired with PostgreSQL, a powerful relational database, provides a robust solution for developing high-performance APIs. In this article, we will explore how to create RESTful APIs using FastAPI and PostgreSQL, complete with code examples and actionable insights.

What is FastAPI?

FastAPI is a Python web framework designed to build APIs quickly and efficiently. Leveraging asynchronous programming and type hints, FastAPI allows developers to create highly performant applications with minimal boilerplate code. Its automatic generation of OpenAPI documentation is a standout feature, making it easier for developers to understand and interact with the API.

Key Features of FastAPI

  • Fast Performance: FastAPI is built on top of Starlette and Pydantic, which contribute to its speed and efficiency.
  • Easy to Use: With intuitive syntax and automatic documentation generation, FastAPI reduces the learning curve for developers.
  • Asynchronous Support: FastAPI supports asynchronous request handling, enabling better performance under load.
  • Type Safety: The use of Python type hints improves code quality and allows for automatic data validation.

What is PostgreSQL?

PostgreSQL is an open-source relational database known for its robustness, scalability, and support for advanced data types. It is highly extensible and offers powerful features such as ACID compliance, complex queries, and full-text search capabilities.

Why Use PostgreSQL?

  • Reliability: PostgreSQL is known for its durability, ensuring data integrity even in the event of failures.
  • Rich Features: It supports advanced data types, indexing, and complex queries.
  • Community Support: Being open-source, PostgreSQL has a large and active community that contributes to its development.

Setting Up Your Environment

Before diving into coding, let's set up our environment.

Prerequisites

  • Python 3.7 or higher
  • PostgreSQL installed on your machine
  • Basic understanding of Python and SQL

Installation

  1. Create a virtual environment (optional but recommended): bash python -m venv fastapi-env source fastapi-env/bin/activate # On Windows use `fastapi-env\Scripts\activate`

  2. Install FastAPI and a server (e.g., Uvicorn): bash pip install fastapi uvicorn

  3. Install an ORM (Object Relational Mapping) library: bash pip install sqlalchemy[asyncio] asyncpg

Creating a Simple RESTful API

Step 1: Database Connection

Let's start by setting up the connection to our PostgreSQL database. Create a file named database.py:

from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker

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

engine = create_async_engine(DATABASE_URL, echo=True)
async_session = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)

Step 2: Defining Models

Now, let's define our data model. Create a file named models.py:

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_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: Creating the API

Now it's time to create the API. Create a file named main.py:

from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from database import async_session
from models import Item, Base

app = FastAPI()

# Dependency to get DB session
async def get_db() -> AsyncSession:
    async with async_session() as session:
        yield session

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

@app.get("/items/{item_id}", response_model=Item)
async def read_item(item_id: int, db: AsyncSession = Depends(get_db)):
    result = await db.execute(select(Item).where(Item.id == item_id))
    item = result.scalars().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:

uvicorn main:app --reload

This command starts the development server with hot reloading. You can access your API at http://127.0.0.1:8000/items/.

Testing Your API

You can test your API using tools like Postman or cURL. Here’s how to do it with cURL:

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

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

Troubleshooting Common Issues

  • Database Connection Errors: Ensure your PostgreSQL server is running and that you have the correct credentials in DATABASE_URL.
  • Dependency Issues: Make sure all required packages are installed within your virtual environment.

Conclusion

Creating RESTful APIs with FastAPI and PostgreSQL is a straightforward process that combines the power of modern web frameworks with reliable databases. FastAPI's speed and ease of use, paired with PostgreSQL's robust features, make this duo an excellent choice for developers looking to build efficient web applications.

By following the steps outlined in this article, you can quickly set up your own RESTful API. Experiment with adding more functionalities, such as PUT and DELETE methods, and continue to explore the vast capabilities of 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.