Published May 4, 2024 ⦁ 8 min read
Supabase REST API Basics

Supabase REST API Basics

The Supabase REST API is a powerful tool that allows you to interact with your PostgreSQL database directly, without writing any code. It provides a secure and scalable way to access your data, with the API automatically generated as you update your database.

Key Features:

  • Instant Access: The API is instantly available as you update your database.
  • Secure: Leverages PostgreSQL's Row Level Security for secure data access.
  • Scalable: Designed to handle large amounts of data and traffic.

The API exposes CRUD operations (Create, Read, Update, Delete) at the URL https://<project_ref>.supabase.co/rest/v1/, enabling you to build applications quickly without backend development.

Setting Up:

  1. Create a New Project: Sign up on Supabase.io, create a new project, and authenticate your account.
  2. Configure Database and Security: Create a new table, enable row-level security, and create a policy for public access.
  3. Add Sample Data: Insert sample data into your table using SQL commands or the Table interface.

API Authentication:

API Key Type Purpose Usage
anon Anonymous access Public-facing applications
service_role Server-side authentication Backend use only, never expose to client

CRUD Operations:

Operation HTTP Method Example
Create POST POST /rest/v1/todos { "title": "New Todo" }
Read GET GET /rest/v1/todos
Update PATCH PATCH /rest/v1/todos/1 { "title": "Updated Todo" }
Delete DELETE DELETE /rest/v1/todos/1

Securing Your API:

  • Row-Level Security: Control access to specific rows based on user roles.
  • Safeupdate Policy: Specify filtering criteria to prevent accidental updates or deletions.
  • Request Data: Use current_setting() to access request methods, paths, headers, and JWTs for custom logic and security.

By following the Supabase REST API Basics guide, you'll learn how to set up a new project, authenticate with API keys, perform CRUD operations, and secure your API for building fast, scalable, and secure applications.

Setting Up Your Supabase Project

Supabase

Creating a New Project

To start using the Supabase REST API, you need to set up a new project in Supabase. Here's how:

  1. Go to Supabase.io and create a new account or log in to an existing one.
  2. Authenticate your account with your preferred service.
  3. Click "New Project" and create a new project under your chosen organization.

Configuring Database and Security

After setting up your project, you need to create a database and configure security settings. Here's how:

Create a Database

  1. Navigate to the Database section on the left-hand menu.
  2. Create a new table. This will create a corresponding API route /rest/v1/todos that can accept GET, POST, PATCH, and DELETE requests.

Enable Row-Level Security

  1. Alter the table to enable row-level security using the following SQL command:
alter table "todos" enable row level security;

Create a Policy for Public Access

  1. Create a policy to allow public access to your table using the following SQL command:
create policy "Allow public access" on todos for select to anon using (true);

This will allow anonymous access to your table, which is necessary for the REST API to work.

Adding Sample Data

Before you can start using the REST API, you need to add some sample data to your table. You can do this using the SQL Editor or the Table interface. For example, you can use the following SQL command to insert some sample data into your table:

insert into todos (task) values ('Buy milk'), ('Walk the dog'), ('Do laundry');

This will add three sample tasks to your table, which you can use to test the REST API.

By following these steps, you can set up a new Supabase project, create a database, and configure the necessary security settings to get started with the REST API. In the next section, we'll explore API authentication and how to use API keys to interact with your database.

API Authentication Explained

API authentication is a crucial aspect of interacting with the Supabase REST API. In this section, we'll explore API keys, their types, and how to use them securely to access your database.

Understanding API Keys

Supabase provides two types of API keys: anon and service_role. Each key serves a specific purpose and is used in different scenarios.

API Key Type Purpose Usage
anon Anonymous access to your database Public-facing applications where users don't need to authenticate
service_role Server-side authentication with elevated access Backend use only, never expose to the client-side

When using API keys, follow these best practices to ensure secure access to your database:

  • Store API keys securely, such as in environment variables or a secrets manager.
  • Never expose the service_role key to the client-side.
  • Rotate API keys regularly to minimize security risks.
  • Use the official Supabase client libraries to simplify API interactions and enhance security.

By understanding the differences between anon and service_role keys and using them correctly, you can ensure secure and efficient access to your Supabase database.

In the next section, we'll explore CRUD operations with the API, including creating, reading, updating, and deleting data.

CRUD Operations with the API

CRUD (Create, Read, Update, Delete) operations are essential for interacting with your Supabase database through the REST API. In this section, we'll explore each operation, providing examples and use cases to help you master CRUD operations.

Creating Data

To create new records in your database, use the HTTP POST method. You'll need to specify the table name and provide the necessary data in the request body. For example, to create a new todo item:

POST https://<project_ref>.supabase.co/rest/v1/todos
{
  "title": "New Todo Item",
  "description": "This is a new todo item",
  "completed": false
}

Reading Data

To read data from your database, use the HTTP GET method. You can fetch data from a specific table by specifying the table name in the URL. For instance, to retrieve all todo items:

GET https://<project_ref>.supabase.co/rest/v1/todos

You can also use query parameters to filter or sort the data. For example, to retrieve only completed todo items:

GET https://<project_ref>.supabase.co/rest/v1/todos?completed=true

Updating Data

To update existing records, use the HTTP PATCH method. You'll need to specify the table name and the ID of the record you want to update, as well as the updated data in the request body. For example, to update a todo item:

PATCH https://<project_ref>.supabase.co/rest/v1/todos/1
{
  "title": "Updated Todo Item",
  "description": "This is an updated todo item"
}

Deleting Data

To delete records, use the HTTP DELETE method. You'll need to specify the table name and the ID of the record you want to delete. For example, to delete a todo item:

DELETE https://<project_ref>.supabase.co/rest/v1/todos/1

Remember to exercise caution when deleting data, as it will be permanently removed from your database.

By mastering CRUD operations, you'll be able to effectively interact with your Supabase database and build powerful applications. In the next section, we'll explore ways to secure your API and prevent unauthorized access.

sbb-itb-b2281d3

Securing Your API

Securing your API is crucial to prevent unauthorized access and ensure the integrity of your data. Supabase provides several security measures to help you protect your API.

Row-Level Security

Row-Level Security (RLS) is a feature in Supabase that allows you to control access to specific rows in your tables based on user roles. By implementing RLS policies, you can restrict data access to authorized users, ensuring that sensitive information is protected.

To enable RLS, you need to create policies that define which users can access specific rows in your tables. For example, you can create a policy that allows only users with the "admin" role to access certain rows in a table.

Preventing Accidental Operations

Another important aspect of securing your API is preventing accidental operations, such as unintended updates or deletions. Supabase provides a safeupdate policy that allows you to specify filtering criteria for updates and deletions, ensuring that only intended changes are made to your data.

Safeupdate Policy

Policy Description
safeupdate Specifies filtering criteria for updates and deletions to prevent accidental operations

By implementing safeupdate policies, you can avoid accidental operations and ensure that your data remains consistent and accurate.

By following these security measures, you can ensure that your API is secure and protected from unauthorized access. In the next section, we'll explore how to use request data to further enhance the security of your API.

Using Request Data

Accessing Request Methods and Paths

When building a RESTful API with Supabase, you need to control the request data to implement custom logic, security rules, or rate limiting. You can use the current_setting() PostgreSQL function to access various request-specific data.

To retrieve the HTTP method and request path, use the following syntax:

SELECT current_setting('request.method') AS method,
       current_setting('request.path') AS path;

This returns the HTTP method (e.g., GET, POST, PUT, DELETE) and the request path (e.g., /users, /products, /orders) as separate columns. You can then use this information to implement custom logic or security rules in your API.

Using Request Headers and JWTs

In addition to retrieving the request method and path, you can access request headers and JSON Web Tokens (JWTs) using the current_setting() function. This allows you to implement fine-grained access control and logging purposes.

To access request headers, use the following syntax:

SELECT current_setting('request.headers') AS headers;

This returns a JSON object containing all the request headers, which you can then parse and use in your API logic.

To access JWTs, use the following syntax:

SELECT current_setting('request.jwt_claim') AS jwt_claim;

This returns a JSON object containing the JWT claims, which you can then use to authenticate and authorize requests.

By leveraging the current_setting() function, you can gain greater control over your API and implement advanced security measures to protect your data.

Here's a summary of the current_setting() function:

Function Description
current_setting('request.method') Retrieves the HTTP method (e.g., GET, POST, PUT, DELETE)
current_setting('request.path') Retrieves the request path (e.g., /users, /products, /orders)
current_setting('request.headers') Retrieves the request headers as a JSON object
current_setting('request.jwt_claim') Retrieves the JWT claims as a JSON object

By using these functions, you can create a more secure and customizable API with Supabase.

Conclusion

You've made it to the end of the Supabase REST API Basics guide! By now, you should have a solid understanding of the fundamentals of the Supabase REST API.

What You've Learned

In this guide, we've covered the essential concepts and features of the Supabase REST API, including:

  • Setting up a new project
  • Authentication and API keys
  • Simple CRUD operations
  • Securing your API with row-level security and JWTs
  • Accessing request data

Next Steps

As you continue to work with Supabase, remember to take advantage of its advanced features, such as real-time updates, file storage, and user presence. With Supabase, you can build fast, scalable, and secure applications that meet the demands of modern users.

If you have any further questions or need additional guidance, don't hesitate to explore the official Supabase documentation and community resources. Happy building!

FAQs

Does Supabase have a REST API?

Yes, Supabase provides a RESTful API using PostgREST. This API is a thin layer on top of Postgres, exposing everything you need from a CRUD API at the URL https://<project_ref>.supabase.co/rest/v1/.