2-building-restful-apis-with-fastapi-and-integrating-with-postgresql.html

Building RESTful APIs with FastAPI and Integrating with PostgreSQL

In today's rapidly evolving digital landscape, building efficient and scalable web applications is crucial. RESTful APIs serve as the backbone for web services, enabling seamless communication between different systems. FastAPI, a modern web framework for Python, has gained immense popularity for its speed and ease of use. When combined with PostgreSQL, a powerful relational database, developers can create robust and efficient APIs. In this article, we will explore how to build RESTful APIs using FastAPI and integrate them with PostgreSQL, providing clear examples and actionable insights along the way.

What is FastAPI?

FastAPI is a high-performance web framework for building APIs with Python 3.7+ based on standard Python type hints. It allows for easy creation of RESTful APIs and is known for its speed, thanks to asynchronous programming capabilities. FastAPI is built on top of Starlette for the web parts and Pydantic for the data parts, giving developers the best of both worlds.

Key Features of FastAPI

  • Fast: It is one of the fastest frameworks available.
  • Easy to use: Minimal boilerplate code is required, making it friendly for beginners.
  • Automatic documentation: FastAPI automatically generates interactive API documentation through Swagger UI and ReDoc.
  • Data validation: With Pydantic, you get data validation and serialization out of the box.

What is PostgreSQL?

PostgreSQL is an advanced, open-source relational database system known for its robustness, extensibility, and standards compliance. It supports a wide range of data types and advanced features like transactions, subselects, and multi-version concurrency control (MVCC).

Why Use PostgreSQL?

  • Reliability: Proven performance in high-demand environments.
  • Extensibility: Support for custom procedures and data types.
  • SQL compliance: Adheres to the SQL standards, making it familiar for developers.

Setting Up Your Environment

Before we dive into the code, ensure you have Python, FastAPI, and PostgreSQL installed on your machine. You can use virtual environments to manage dependencies effectively.

Step 1: Install Required Packages

Use pip to install FastAPI and an ASGI server like uvicorn, along with the database adapter asyncpg for PostgreSQL.

pip install fastapi uvicorn asyncpg sqlalchemy databases

Step 2: Set Up PostgreSQL

  1. Install PostgreSQL on your machine if you haven't already.
  2. Create a database for your application. You can use the following command in the PostgreSQL shell:

sql CREATE DATABASE fastapi_db;

  1. Create a user with permissions to access this database:

sql CREATE USER fastapi_user WITH PASSWORD 'your_password'; GRANT ALL PRIVILEGES ON DATABASE fastapi_db TO fastapi_user;

Building a Simple RESTful API

Now that we have our environment set up, let’s create a simple RESTful API that allows users to manage a list of items (e.g., products).

Step 3: Creating Your FastAPI Application

Create a file called main.py:

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from databases import Database

DATABASE_URL = "postgresql+asyncpg://fastapi_user:your_password@localhost/fastapi_db"
database = Database(DATABASE_URL)

app = FastAPI()

class Item(BaseModel):
    id: int
    name: str
    description: str

# Connect to the database
@app.on_event("startup")
async def startup():
    await database.connect()

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

# Create an item
@app.post("/items/", response_model=Item)
async def create_item(item: Item):
    query = "INSERT INTO items(name, description) VALUES (:name, :description) RETURNING id"
    values = {"name": item.name, "description": item.description}
    item_id = await database.execute(query=query, values=values)
    return {**item.dict(), "id": item_id}

# Read items
@app.get("/items/{item_id}", response_model=Item)
async def read_item(item_id: int):
    query = "SELECT * FROM items WHERE id = :id"
    item = await database.fetch_one(query=query, values={"id": item_id})
    if item is None:
        raise HTTPException(status_code=404, detail="Item not found")
    return item

Step 4: Creating the Database Table

Before running the API, ensure you have a table to store the items. You can create it using the following SQL command:

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

Step 5: Running the FastAPI Application

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

uvicorn main:app --reload

You can now access your API at http://127.0.0.1:8000/items/. You can also check the interactive documentation at http://127.0.0.1:8000/docs.

Troubleshooting Common Issues

  • Database Connection Errors: Ensure that your PostgreSQL server is running and the connection string is correct.
  • CORS Issues: If you’re accessing your API from a different domain, you may need to enable Cross-Origin Resource Sharing (CORS) using FastAPI's middleware.
  • Data Validation Errors: FastAPI uses Pydantic for data validation. Ensure your input data matches the expected types.

Conclusion

Building RESTful APIs with FastAPI and PostgreSQL is a powerful combination for creating efficient and scalable applications. FastAPI's speed and ease of use, coupled with PostgreSQL's reliability, make them an excellent choice for developers. By following the steps outlined in this article, you can create a simple API and gain insights into building more complex applications. As you explore further, consider implementing additional features like authentication, pagination, and advanced querying capabilities to enhance your API’s functionality. 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.