Skip to main content

Supabase FastAPI integration

· 4 min read
Serhii Hrekov
software engineer, creator, artist, programmer, projects founder

Supabase Integration with FastAPI

Here's a guide to integrating Supabase with a FastAPI application. We'll cover environment setup, connecting to Supabase, and performing basic CRUD operations.

Set Up Your Supabase Project

First, you need a Supabase project.

  1. Go to the Supabase Dashboard.
  2. Create a new project.
  3. Navigate to API Settings to find your Project URL and anon public key. You will need these for your FastAPI application.
  4. Create a test table, for example, products, with a few columns like id (primary key), name, and price.

Set Up Your FastAPI Environment

Next, set up a new Python virtual environment and install the necessary libraries.

# Create a virtual environment
python3 -m venv venv
source venv/bin/activate

# Install FastAPI, Uvicorn (an ASGI server), and the Supabase client
pip install fastapi "uvicorn[standard]" supabase

Create the FastAPI Application

Create a file named main.py. This file will contain your FastAPI application and connect to Supabase using the credentials you obtained earlier.

import os
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from supabase import create_client, Client

# Initialize FastAPI app
app = FastAPI()

# Supabase credentials (get these from your Supabase project settings)
# Using environment variables is a best practice for security
SUPABASE_URL = os.environ.get("SUPABASE_URL")
SUPABASE_KEY = os.environ.get("SUPABASE_KEY")

# Create the Supabase client
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)

# Pydantic model for data validation
class Product(BaseModel):
name: str
price: float

class ProductInDB(Product):
id: int

# --- API Endpoints ---

@app.post("/products", response_model=ProductInDB)
def create_product(product: Product):
"""Create a new product."""
data = product.dict()
response = supabase.table("products").insert(data).execute()
if not response.data:
raise HTTPException(status_code=500, detail="Failed to create product")
return response.data[0]

@app.get("/products", response_model=list[ProductInDB])
def get_all_products():
"""Get all products."""
response = supabase.table("products").select("*").execute()
return response.data

@app.get("/products/{product_id}", response_model=ProductInDB)
def get_product(product_id: int):
"""Get a product by ID."""
response = supabase.table("products").select("*").eq("id", product_id).execute()
if not response.data:
raise HTTPException(status_code=404, detail="Product not found")
return response.data[0]

@app.put("/products/{product_id}", response_model=ProductInDB)
def update_product(product_id: int, product: Product):
"""Update an existing product."""
data = product.dict()
response = supabase.table("products").update(data).eq("id", product_id).execute()
if not response.data:
raise HTTPException(status_code=404, detail="Product not found")
return response.data[0]

@app.delete("/products/{product_id]")
def delete_product(product_id: int):
"""Delete a product."""
response = supabase.table("products").delete().eq("id", product_id).execute()
if not response.data:
raise HTTPException(status_code=404, detail="Product not found")
return {"message": f"Product with ID {product_id} deleted"}

Run the Application

Before running, set your environment variables for security.

# Replace with your actual Supabase credentials
export SUPABASE_URL="https://your-project-ref.supabase.co"
export SUPABASE_KEY="eyJhbGciOiJIUzI1NiIsIn..."

# Run the FastAPI application
uvicorn main:app --reload

Your FastAPI application is now running on http://127.0.0.1:8000. You can test the endpoints using a tool like Postman, curl, or by visiting the interactive docs at http://127.0.0.1:8000/docs.