1-creating-a-restful-api-with-fastapi-and-postgresql-for-efficient-data-handling.html

Creating a RESTful API with FastAPI and PostgreSQL for Efficient Data Handling

In today's digital landscape, the demand for efficient data handling is greater than ever. Developers are continually seeking ways to build robust applications that can manage data effectively. One of the most effective ways to achieve this is by creating a RESTful API. In this article, we will explore how to create a RESTful API using FastAPI and PostgreSQL, two powerful tools that streamline the development process.

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 be easy to use and to provide automatic generation of API documentation.

Key Features of FastAPI:

  • High Performance: Built on Starlette for the web parts and Pydantic for the data parts, allowing for async capabilities.
  • Easy to Use: User-friendly with intuitive syntax, making it accessible for beginners and experienced developers alike.
  • Automatic Documentation: Generates interactive API documentation using OpenAPI and JSON Schema.
  • Built-in Validation: Automatically validates request and response data against defined data models.

What is PostgreSQL?

PostgreSQL is an open-source relational database management system with a strong reputation for reliability, feature robustness, and performance. It supports advanced data types and offers powerful indexing options.

Benefits of Using PostgreSQL:

  • Transactional Integrity: Guarantees ACID compliance, ensuring reliable transactions.
  • Extensibility: Easily extendable with custom functions, data types, and operators.
  • Community Support: Active community that contributes to its continuous improvement.

Use Cases

Creating a RESTful API with FastAPI and PostgreSQL is ideal for various applications, including:

  • Web Applications: Backend services for dynamic web apps.
  • Mobile Apps: Providing data and services for mobile applications.
  • Microservices: Building lightweight, independent services within a larger architecture.

Setting Up Your Environment

Prerequisites

Before we start coding, ensure you have the following installed:

  • Python 3.6 or higher
  • PostgreSQL
  • pip (Python package installer)

Step 1: Install FastAPI and Other Dependencies

Create a new directory for your project and navigate into it. Then run the following command to set up your environment:

pip install fastapi[all] psycopg2-binary
  • fastapi[all] installs FastAPI along with its dependencies for asynchronous capabilities and automatic documentation.
  • psycopg2-binary is the PostgreSQL adapter for Python.

Step 2: Create a PostgreSQL Database

Log into your PostgreSQL database and create a new database:

CREATE DATABASE fastapi_db;

Step 3: Define Your Data Model

Create a new file named models.py in your project directory. This file will contain the data models for our application.

from pydantic import BaseModel
from typing import Optional

class Item(BaseModel):
    id: Optional[int] = None
    name: str
    description: Optional[str] = None
    price: float

Step 4: Create the API

Now, create a file named main.py to set up the FastAPI application.

from fastapi import FastAPI, HTTPException
from typing import List
import asyncpg

app = FastAPI()

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

async def connect_db():
    return await asyncpg.connect(DATABASE_URL)

@app.on_event("startup")
async def startup():
    app.state.db = await connect_db()

@app.on_event("shutdown")
async def shutdown():
    await app.state.db.close()

@app.post("/items/", response_model=Item)
async def create_item(item: Item):
    query = "INSERT INTO items(name, description, price) VALUES($1, $2, $3) RETURNING id;"
    values = (item.name, item.description, item.price)
    last_record_id = await app.state.db.fetchval(query, *values)
    item.id = last_record_id
    return item

@app.get("/items/", response_model=List[Item])
async def read_items():
    query = "SELECT * FROM items;"
    return await app.state.db.fetch(query)

Step 5: Create the Database Table

Before running the API, create the required table in PostgreSQL.

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

Step 6: Run Your API

You can run your FastAPI application using the command below:

uvicorn main:app --reload

This command starts the server, and you can access the interactive API documentation at http://127.0.0.1:8000/docs.

Troubleshooting Common Issues

  • Database Connection Errors: Ensure your connection string is correct and PostgreSQL is running.
  • Missing Dependencies: If you encounter module not found errors, confirm that all packages are installed and that you are in the correct virtual environment.
  • Validation Errors: Check your data model against the data being sent in requests.

Conclusion

Creating a RESTful API with FastAPI and PostgreSQL is a straightforward process that allows developers to build efficient and scalable applications. By leveraging FastAPI's intuitive syntax and PostgreSQL's powerful data handling capabilities, you can create a robust backend for your applications. With this guide, you have the foundational knowledge to expand and optimize your API further, making it a valuable asset for your projects. 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.