1-creating-restful-apis-with-fastapi-and-postgresql.html

Creating RESTful APIs with FastAPI and PostgreSQL

In today’s digital landscape, the demand for efficient and scalable web applications is higher than ever. As developers, we often need to create APIs that allow different parts of applications to communicate seamlessly. FastAPI, a modern web framework for building APIs with Python, has gained immense popularity due to its speed, ease of use, and automatic generation of OpenAPI documentation. When combined with PostgreSQL, a powerful and robust relational database, you can create a solid backend for your applications. This article will guide you through the process of creating RESTful APIs using FastAPI and PostgreSQL, complete with code examples and actionable insights.

What is FastAPI?

FastAPI is a high-performance web framework for building APIs with Python 3.7+ based on standard Python type hints. It is designed for fast development and has several notable features:

  • High performance: FastAPI is one of the fastest frameworks available, outperforming Flask and Django.
  • Automatic documentation: It automatically generates interactive API documentation using Swagger UI and ReDoc.
  • Data validation: FastAPI leverages Pydantic for data validation and serialization.

Why Use PostgreSQL?

PostgreSQL is an open-source relational database known for its robustness, flexibility, and advanced features. Here are some reasons to choose PostgreSQL for your project:

  • ACID compliance: Ensures reliable transactions and data integrity.
  • Complex queries: Supports complex queries, indexing, and full-text search.
  • Extensibility: Allows for custom data types and functions.

Setting Up Your Environment

To get started, ensure you have Python, FastAPI, and PostgreSQL installed on your system. You can install FastAPI using pip:

pip install fastapi[all] psycopg2-binary
  • FastAPI: The framework for building your API.
  • psycopg2-binary: A PostgreSQL adapter for Python.

You will also need a PostgreSQL database. You can set up a local instance or use a cloud service like Heroku or AWS RDS.

Step-by-Step Guide to Creating a RESTful API

Step 1: Create a PostgreSQL Database

First, create a database in PostgreSQL. You can do this using the command line:

CREATE DATABASE fastapi_example;

Next, create a table to store data. For example, let’s create a users table:

CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    full_name VARCHAR(100),
    disabled BOOLEAN DEFAULT FALSE
);

Step 2: Initialize FastAPI

Create a new Python file (e.g., main.py) and initialize FastAPI:

from fastapi import FastAPI
from pydantic import BaseModel
import psycopg2

app = FastAPI()

Step 3: Define the Data Model

Using Pydantic, define a data model that represents the structure of your users:

class User(BaseModel):
    username: str
    email: str
    full_name: str = None
    disabled: bool = False

Step 4: Connect to PostgreSQL

Establish a connection to your PostgreSQL database:

def get_db_connection():
    conn = psycopg2.connect(
        dbname="fastapi_example",
        user="your_username",
        password="your_password",
        host="localhost"
    )
    return conn

Step 5: Create CRUD Operations

Now, let’s implement the basic CRUD operations: Create, Read, Update, and Delete.

Create a User

@app.post("/users/", response_model=User)
def create_user(user: User):
    conn = get_db_connection()
    cursor = conn.cursor()

    cursor.execute(
        "INSERT INTO users (username, email, full_name, disabled) VALUES (%s, %s, %s, %s) RETURNING id",
        (user.username, user.email, user.full_name, user.disabled)
    )
    user_id = cursor.fetchone()[0]
    conn.commit()
    cursor.close()
    conn.close()

    user.id = user_id
    return user

Read Users

@app.get("/users/", response_model=list[User])
def read_users():
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM users")
    users = cursor.fetchall()
    cursor.close()
    conn.close()

    return [{"id": user[0], "username": user[1], "email": user[2], "full_name": user[3], "disabled": user[4]} for user in users]

Update a User

@app.put("/users/{user_id}", response_model=User)
def update_user(user_id: int, user: User):
    conn = get_db_connection()
    cursor = conn.cursor()

    cursor.execute(
        "UPDATE users SET username = %s, email = %s, full_name = %s, disabled = %s WHERE id = %s",
        (user.username, user.email, user.full_name, user.disabled, user_id)
    )
    conn.commit()
    cursor.close()
    conn.close()

    user.id = user_id
    return user

Delete a User

@app.delete("/users/{user_id}")
def delete_user(user_id: int):
    conn = get_db_connection()
    cursor = conn.cursor()

    cursor.execute("DELETE FROM users WHERE id = %s", (user_id,))
    conn.commit()
    cursor.close()
    conn.close()

    return {"message": "User deleted successfully"}

Step 6: Running Your FastAPI Application

To run your FastAPI application, use the command:

uvicorn main:app --reload

You can now access your API at http://127.0.0.1:8000/docs to see the automatically generated documentation and test your endpoints.

Conclusion

Creating RESTful APIs with FastAPI and PostgreSQL is an efficient way to build robust backend services. With FastAPI's speed and automatic documentation features, combined with PostgreSQL's reliability and scalability, you can develop powerful applications that meet modern demands. By following this guide, you now have a solid foundation to expand and enhance your API with more advanced functionalities like authentication, pagination, and error handling.

Key Takeaways

  • FastAPI provides a quick and efficient way to build APIs.
  • PostgreSQL offers a reliable and powerful data storage solution.
  • The combination of FastAPI and PostgreSQL allows you to create dynamic, scalable applications.

Start building your API today, and take advantage of the strengths of both FastAPI and PostgreSQL!

SR
Syed
Rizwan

About the Author

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