โšกSupabase Integration

Adding User Data to a Supabase Table

Supabase is an open-source Firebase alternative that provides all the backend services you need to build a scalable app in Databutton. This guide outlines the key steps to integrate Supabase with your application, including creating a Supabase project, setting up a table, and creating a backend in Databutton.

Key Steps

  1. Create a Supabase Project

  2. Set Up a Table in Supabase

  3. Create a Backend in Databutton

Getting Started with Supabase Projects

Creating a Supabase Account

To get started with Supabase, you need to have a Supabase account. You can sign up using your email or use a third-party provider like GitHub to create your Supabase account.

Create a New Project

  • Once logged in, click on "New Project."

  • Choose a name for your project and select a region closest to your location.

  • Click "Create new project" to continue.

Setting up Your Table in Supabase

To work with tables, you need to first create a table in Supabase.

  • Navigate to the "Database" tab on the left sidebar.

  • And then create a "New table"

  • You need to name your table. In this demo example the table is named as ; user_feedback

Defining Columns and Their Types

In this demo example, we define five columns:

  • id: Primary key of type uuid with default value uuid_generate_v4().

  • user_id: Type text, this will store the user ID

  • feedback_text: Type text, to store feedback content.

  • rating: Type int, to store a numerical rating.

  • movie_url: Type text, to store the URL related to the feedback

Refer to the screenshot below to see how this looks in practice. You can add multiple columns and enable Row Level Security (RLS) as well, which we will discuss shortly.

Click "Save" to create your table!

Enable Row Level Security (RLS)

Row Level Security (RLS) allows you to control access to rows in a table based on specific conditions.

  • Enable the RLS checkbox to activate this feature.

Creating RLS Policies:

  • Go to the "Policies" tab for the selected table.

  • Click on "New Policy" to create a new policy

Creating an Unrestricted API Access Policy

During development or when dealing with public data, you might want to allow unrestricted access to your table. This can be done by creating a policy that grants all users permission to perform any operation on the table.

  • Policy Name: Allow API Access

  • Table: public.user_feedback

  • Policy Behavior: Permissive (as clause)

  • Policy Command: ALL (SELECT, INSERT, UPDATE, DELETE)

  • Target Roles: Defaults to all (public) roles if none selected

  • Condition: Set the condition to true to allow unrestricted access

Security Implications: The true condition means the policy will allow any operation by any user on the table. This is ideal for testing or open-access applications, but for production, you should replace this policy with more secure, user-specific access controls.

Building the Backend (API) with Databutton

Now we come to the main part where Databutton works like magic! Databutton simplifies building a backend that connects to your Supabase database, allowing you to easily perform CRUD operations on your data.

Databutton can guide you through this process.

Define Your Requirements

You can start by outlining your requirements to Databutton. Here's an example prompt you might use. Example prompt :

Hey! I would like to create a backend which has access to my supabase table <name of the table> and use Python SDK of supabase to fetch data, add data , delete data and update data. How shall I proceed?

Obtain API Credentials

To interact with your Supabase database, you need the API Secret Key and Web URL for authentication.

Navigate to the "Home" Tab:

  • Go to the "Home" tab in the Supabase dashboard.

  • Scroll down to find Project API details.

RLS API Key (service_role secret):

  • Ensure you provide Databutton with the RLS API key (service_role secret), as RLS is enabled for your table.

Note: Ensure to provide Databutton with the RLS API key (service_role secret) since RLS is enabled.

Store Credentials Securely

Once, you have both of them, ask Databutton to store your credentials securely for easy access in your backend code.

Example Prompt :

Hey help me to store the URL and API key

Develop the Backend API

The backend covers all necessary functionalities for a CRUD app, with each function treated as an individual endpoint. The core functionalities include:

  • Retrieve all feedback records from the Supabase table.

  • Adding data : Insert a new feedback record into the Supabase table

  • Update data : Update an existing feedback record based on the user ID

  • Deleting data : Delete a feedback record based on the user ID.

Pro Tip: Implement one function at a time rather than adding all functionalities at once. For example, start by implementing the "Retrieve" table feature first.

API Code Implementation

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
import databutton as db
from supabase import create_client, Client

# Initialize Supabase client
SUPABASE_URL = db.secrets.get("SUPABASE_URL")
SUPABASE_API_KEY = db.secrets.get("SUPABASE_API_KEY")
supabase: Client = create_client(SUPABASE_URL, SUPABASE_API_KEY)

# Router for endpoints
router = APIRouter()

class FeedbackRequest(BaseModel):
    user_id: str
    feedback_text: str
    rating: int
    movie_url: str  # New required field

class UpdateFeedbackRequest(BaseModel):
    user_id: str  # Use user_id to identify the feedback
    feedback_text: str | None = None  # Optional fields for updating
    rating: int | None = None
    movie_url: str | None = None

class DeleteFeedbackRequest(BaseModel):
    user_id: str  # Use user_id instead of feedback_id

@router.delete("/feedbacks")
def delete_feedback(request: DeleteFeedbackRequest):
    try:
        response = supabase.table("user_feedback").delete().eq("user_id", request.user_id).execute()
        print("Delete response: ", response)
        return {"message": "Feedback deleted successfully"}
    except Exception as e:
        print("Exception: ", str(e))
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/feedbacks")
def add_feedback(feedback: FeedbackRequest):
    try:
        response = supabase.table("user_feedback").insert({
            "user_id": feedback.user_id,
            "feedback_text": feedback.feedback_text,
            "rating": feedback.rating,
            "movie_url": feedback.movie_url  # Include the new field
        }).execute()
        print("Insert response: ", response)
        return {"message": "Feedback added successfully"}
    except Exception as e:
        print("Exception: ", str(e))
        raise HTTPException(status_code=500, detail=str(e))

@router.put("/feedbacks")
def update_feedback(request: UpdateFeedbackRequest):
    try:
        update_data = {k: v for k, v in request.dict().items() if v is not None}
        response = supabase.table("user_feedback").update(update_data).eq("user_id", request.user_id).execute()
        print("Update response: ", response)
        return {"message": "Feedback updated successfully"}
    except Exception as e:
        print("Exception: ", str(e))
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/feedbacks")
def get_feedbacks():
    try:
        print("Supabase URL: ", SUPABASE_URL)
        print("Supabase API Key: ", SUPABASE_API_KEY)
        response = supabase.table("user_feedback").select("*").execute()
        feedbacks = response.data
        print("Feedbacks data: ", feedbacks)
        return feedbacks
    except Exception as e:
        print("Exception: ", str(e))
        raise HTTPException(status_code=500, detail=str(e))

Databutton handles the installation of the supabase Python package.

Test Your API Endpoints

Once each endpoint is implemented, ask Databutton to test it !

Next following steps would be to integrate the this backend to the UI component!

Last updated