Supabase Python: Quickstart Guide & API Reference
Supabase Python: Quickstart Guide & API Reference
Hey guys! Today, we’re diving deep into the world of Supabase and how you can wield its power using Python. Think of Supabase as an open-source Firebase alternative – it gives you all the backend tools you need without the vendor lock-in. And with Python? Well, that’s just the cherry on top. So, let’s get started and explore the Supabase Python API, making your development journey smoother and more efficient.
Table of Contents
- What is Supabase?
- Getting Started with Supabase and Python
- CRUD Operations with Supabase Python
- Creating Data
- Reading Data
- Updating Data
- Deleting Data
- Authentication with Supabase Python
- Signing Up Users
- Signing In Users
- Signing Out Users
- Realtime Subscriptions with Supabase Python
- Setting Up Realtime
- Subscribing to Changes
- File Storage with Supabase Python
- Uploading Files
- Downloading Files
- Deleting Files
- Conclusion
What is Supabase?
Before we jump into the code, let’s clarify what Supabase actually is . Supabase is an open-source backend-as-a-service (BaaS) platform. It provides you with a suite of tools, including a Postgres database, authentication, real-time subscriptions, and storage, all wrapped up in an easy-to-use interface. This means you can focus on building the front-end of your applications without getting bogged down in the complexities of backend infrastructure. Key features include:
- Postgres Database: A fully managed and scalable Postgres database, giving you the power and flexibility of a relational database.
- Authentication: Built-in authentication and authorization, making it easy to manage user accounts and access control.
- Realtime Subscriptions: Real-time updates using WebSockets, allowing you to build dynamic and responsive applications.
- Storage: Simple and scalable storage for files and media, integrated directly with your database and authentication system.
- Edge Functions: Serverless functions to extend your backend and handle complex logic.
For Python developers, this is awesome news. Supabase provides a Python library that allows you to interact with all of these services directly from your Python code. This means you can use your existing Python skills to build powerful and scalable applications with ease. Whether you’re building a web application, a mobile app, or a background service, Supabase and Python make a great combination. Now, let’s dive into how to get started.
Getting Started with Supabase and Python
Alright, let’s get our hands dirty with some code! To start using Supabase with Python, you’ll first need to install the Supabase Python client. It’s super easy – just use pip, Python’s package installer. Fire up your terminal and type:
pip install supabase
Once the installation is complete, you’ll need to initialize the Supabase client in your Python code. For this, you’ll need your Supabase URL and your Supabase anon key. You can find these in your Supabase project dashboard. Here’s how you can initialize the client:
from supabase import create_client, Client
import os
SUPABASE_URL = os.environ.get("SUPABASE_URL")
SUPABASE_KEY = os.environ.get("SUPABASE_KEY")
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
Make sure to replace
YOUR_SUPABASE_URL
and
YOUR_SUPABASE_ANON_KEY
with your actual Supabase URL and anon key.
Important note:
For security reasons, it’s best practice to store these keys as environment variables rather than hardcoding them directly into your script. This way, you can keep your credentials safe and separate from your code. With the client initialized, you’re now ready to start interacting with your Supabase project using Python. Let’s move on to some common operations like reading, writing, and updating data.
CRUD Operations with Supabase Python
CRUD (Create, Read, Update, Delete) operations are the bread and butter of any application that interacts with a database. Supabase makes these operations straightforward with its Python client. Here’s how you can perform each of these operations:
Creating Data
To insert data into a table, you can use the
insert
method. Let’s say you have a table named
todos
with columns
id
(integer, primary key),
task
(text), and
is_complete
(boolean). Here’s how you can insert a new todo:
data = {
"task": "Buy groceries",
"is_complete": False
}
response = supabase.table("todos").insert(data).execute()
print(response)
This code snippet inserts a new row into the
todos
table with the specified values for
task
and
is_complete
. The
execute()
method sends the request to the Supabase API and returns the response. The response will contain information about the operation, including any errors that occurred.
Reading Data
To read data from a table, you can use the
select
method. You can specify which columns to retrieve and add filters to narrow down the results. Here’s how you can retrieve all todos:
response = supabase.table("todos").select("*").execute()
print(response)
This code retrieves all columns (
*
) from the
todos
table. You can also specify specific columns to retrieve, like this:
response = supabase.table("todos").select("id, task").execute()
print(response)
To add filters, you can use the
eq
,
gt
,
lt
, and other methods. For example, to retrieve only the todos that are complete, you can use:
response = supabase.table("todos").select("*").eq("is_complete", True).execute()
print(response)
Updating Data
To update data in a table, you can use the
update
method. You’ll need to specify which rows to update using filters and provide the new values for the columns you want to change. Here’s how you can update a todo to mark it as complete:
data = {
"is_complete": True
}
response = supabase.table("todos").update(data).eq("id", 1).execute()
print(response)
This code updates the row in the
todos
table where the
id
is 1, setting the
is_complete
column to
True
.
Deleting Data
To delete data from a table, you can use the
delete
method. You’ll need to specify which rows to delete using filters. Here’s how you can delete a todo:
response = supabase.table("todos").delete().eq("id", 1).execute()
print(response)
This code deletes the row in the
todos
table where the
id
is 1. These CRUD operations are the foundation of most applications. With Supabase and Python, they are simple to implement and easy to understand.
Authentication with Supabase Python
User authentication is a critical part of many applications. Supabase provides built-in authentication services that you can easily integrate into your Python application. Here’s how you can handle user authentication with Supabase Python:
Signing Up Users
To sign up a new user, you can use the
auth.sign_up
method. You’ll need to provide the user’s email and password.
email = "test@example.com"
password = "secure_password"
response = supabase.auth.sign_up({
"email": email,
"password": password,
})
print(response)
This code creates a new user with the specified email and password. Supabase will handle the verification process, including sending a confirmation email to the user.
Signing In Users
To sign in an existing user, you can use the
auth.sign_in_with_password
method. You’ll need to provide the user’s email and password.
email = "test@example.com"
password = "secure_password"
response = supabase.auth.sign_in_with_password({
"email": email,
"password": password
})
print(response)
This code signs in the user with the specified email and password. If the credentials are correct, Supabase will return a session object containing the user’s access token and refresh token. You’ll want to store these tokens securely .
Signing Out Users
To sign out a user, you can use the
auth.sign_out
method.
response = supabase.auth.sign_out()
print(response)
This code signs out the current user, invalidating their access token. Remember to handle the user’s session appropriately in your application. Authentication is a complex topic, but Supabase makes it much easier with its built-in services and Python client.
Realtime Subscriptions with Supabase Python
Realtime functionality can take your applications to the next level, providing users with instant updates and a more engaging experience. Supabase supports realtime subscriptions using WebSockets, and the Python client makes it easy to integrate this functionality into your application.
Setting Up Realtime
First, you need to enable realtime functionality for your table in the Supabase dashboard. Go to your Supabase project, navigate to the “Database” section, and then select the table you want to enable realtime for. Click on the “Realtime” tab and enable realtime subscriptions for the table.
Subscribing to Changes
Once realtime is enabled, you can subscribe to changes using the
supabase.table(...).on(...).subscribe()
methods. Here’s how you can subscribe to all changes in the
todos
table:
def handle_event(event):
print(event)
realtime_client = supabase.realtime.connect()
channel = realtime_client.channel("any")
channel.on("postgres_changes", {"event": "*", "schema": "public", "table": "todos"}, handle_event).subscribe()
In this code:
-
handle_eventis a callback function that will be called whenever a change occurs in thetodostable. -
supabase.realtime.connect()establishes a connection to the Supabase realtime server. -
channel.onsets up a subscription to thepostgres_changesevent for thetodostable. -
channel.subscribestarts the subscription, and thehandle_eventfunction will be called whenever a change occurs.
Realtime subscriptions can be used to build collaborative applications, real-time dashboards, and more. With Supabase and Python, it’s easier than ever to add realtime functionality to your applications.
File Storage with Supabase Python
Supabase provides a simple and scalable storage solution for files and media. You can use the Supabase Python client to upload, download, and manage files in your Supabase storage buckets. This is great for handling user uploads, images, videos, and other media files directly within your application.
Uploading Files
To upload a file, you can use the
storage.from(...).upload(...).execute()
methods. Here’s how you can upload a file to a bucket named
avatars
:
file_path = "/path/to/your/file.jpg"
with open(file_path, "rb") as f:
file_content = f.read()
response = supabase.storage.from_("avatars").upload("public/avatar1.jpg", file_content, {
"cacheControl": "3600",
"upsert": False
}).execute()
print(response)
In this code:
-
file_pathis the path to the file you want to upload. -
supabase.storage.from_("avatars")specifies the storage bucket you want to use. -
upload("public/avatar1.jpg", file_content)uploads the file to the specified path in the bucket.
Downloading Files
To download a file, you can use the
storage.from(...).download(...).execute()
methods. Here’s how you can download a file from the
avatars
bucket:
response = supabase.storage.from_("avatars").download("public/avatar1.jpg").execute()
file_content = response.data
with open("downloaded_file.jpg", "wb") as f:
f.write(file_content)
Deleting Files
To delete a file, you can use the
storage.from(...).remove(...).execute()
methods. Here’s how you can delete a file from the
avatars
bucket:
response = supabase.storage.from_("avatars").remove(["public/avatar1.jpg"]).execute()
print(response)
With Supabase storage, you can easily manage files and media in your application. The Python client makes it simple to integrate storage functionality into your code.
Conclusion
So there you have it – a comprehensive look at using Supabase with Python! We’ve covered everything from setting up your environment to performing CRUD operations, handling authentication, implementing real-time subscriptions, and managing file storage. With these tools in your arsenal, you’re well-equipped to build powerful and scalable applications with Supabase and Python.
Remember, the key to mastering any new technology is practice. So, start experimenting with the code snippets we’ve covered, explore the Supabase documentation, and build some cool projects. You’ll be amazed at what you can achieve! Happy coding, guys!