Skip to main content

Supabase Flask integration

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

Here's a simple example of how to integrate Supabase with a Flask application. This guide will cover how to set up the environment, connect to your Supabase project, and perform basic CRUD (Create, Read, Update, Delete) operations.

Set Up Your Supabase Project

First, you need a Supabase project.

  1. Go to the Supabase Dashboard.
  2. Create a new project.
  3. Go to API Settings and find your Project URL and anon public key. You'll need these to connect from your Flask application.
  4. Create a simple table, for example, users, with a few columns like id (primary key), name, and email.

Set Up Your Flask Environment

Next, set up your Python environment and install the necessary libraries.

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

# Install Flask and the official Supabase Python client
pip install Flask supabase

Create the Flask Application

Create a file named app.py. This file will contain your Flask application, connecting to Supabase using the credentials you obtained earlier.

import os
from flask import Flask, jsonify, request
from supabase import create_client, Client

# Initialize Flask app
app = Flask(__name__)

# Supabase credentials (get these from your Supabase project settings)
# It's best practice to use environment variables for sensitive data
SUPABASE_URL = os.environ.get("SUPABASE_URL")
SUPABASE_KEY = os.environ.get("SUPABASE_KEY")

# Check if environment variables are set
if not SUPABASE_URL or not SUPABASE_KEY:
raise ValueError("Supabase URL and Key must be set as environment variables.")

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

# --- API Endpoints ---

@app.route("/users", methods=["POST"])
def create_user():
"""Create a new user."""
data = request.get_json()
response = supabase.table("users").insert(data).execute()
return jsonify(response.data), 201

@app.route("/users", methods=["GET"])
def get_all_users():
"""Get all users."""
response = supabase.table("users").select("*").execute()
return jsonify(response.data)

@app.route("/users/<int:user_id>", methods=["GET"])
def get_user(user_id):
"""Get a user by ID."""
response = supabase.table("users").select("*").eq("id", user_id).execute()
if response.data:
return jsonify(response.data[0])
return jsonify({"error": "User not found"}), 404

@app.route("/users/<int:user_id>", methods=["PUT"])
def update_user(user_id):
"""Update an existing user."""
data = request.get_json()
response = supabase.table("users").update(data).eq("id", user_id).execute()
if response.data:
return jsonify(response.data[0])
return jsonify({"error": "User not found"}), 404

@app.route("/users/<int:user_id>", methods=["DELETE"])
def delete_user(user_id):
"""Delete a user."""
response = supabase.table("users").delete().eq("id", user_id).execute()
if response.data:
return jsonify({"message": f"User with ID {user_id} deleted"}), 200
return jsonify({"error": "User not found"}), 404

# --- Run the App ---
if __name__ == "__main__":
app.run(debug=True)

Run the Application

Before running, set your environment variables.

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

# Run the Flask application
python3 app.py

Your Flask application is now running. You can use a tool like Postman or curl to test the endpoints.

Example curl commands:

  • Create a user:

    curl -X POST -H "Content-Type: application/json" -d '{"name": "Alice", "email": "alice@example.com"}' http://127.0.0.1:5000/users
  • Get all users:

    curl http://127.0.0.1:5000/users
  • Get a specific user:

    curl http://127.0.0.1:5000/users/1