Build an API route in less than 2 minutes.
Create your first API route by creating a table called `todos` to store tasks.
Let's create our first REST route which we can query using cURL
or the browser.
We'll create a database table called todos
for storing tasks. This creates a corresponding API route /rest/v1/todos
which can accept GET
, POST
, PATCH
, & DELETE
requests.
Set up a Supabase project with a 'todos' table
Create a new project in the Supabase Dashboard.
After your project is ready, create a table in your Supabase database. You can do this with either the Table interface or the SQL Editor.
-- Create a table called "todos" -- with a column to store tasks. create table todos ( id serial primary key, task text );
Allow anonymous access
Let's turn on Row Level Security for this table and allow anonymous access.
-- Turn on security alter table "todos" enable row level security; -- Allow anonymous access create policy "Allow anonymous access" on todos to anon for select using (true);
Insert some dummy data
Now we can add some data to our table which we can access through our API.
insert into todos (task) values ('Create tables'), ('Enable security'), ('Add data'), ('Fetch data from the API');
Fetch the data
Find your API URL and Keys in your Dashboard API Settings. You can now query your "todos" table by appending /rest/v1/todos
to the API URL.
Copy this block of code, substitute <PROJECT_REF>
and <ANON_KEY>
, then run it from a terminal.
1curl 'https://<PROJECT_REF>.supabase.co/rest/v1/todos' \ 2-H "apikey: <ANON_KEY>" \ 3-H "Authorization: Bearer <ANON_KEY>"
Bonus#
There are several options for accessing your data:
Browser#
You can query the route in your browser, by appending the anon
key as a query parameter:
https://<PROJECT_REF>.supabase.co/rest/v1/users?apikey=<ANON_KEY>
Client libraries#
We provide a numerous Client Libraries.
const { data, error } = await supabase.from('todos').select()
GraphQL#
Every table can be accessed through the GraphQL API by switching /rest/v1
with /graphql/v1
.
import { createClient, useQuery } from 'urql'
const URL = '<SUPABASE_URL>/graphql/v1'
const ANON_KEY = '<SUPABASE_ANON_KEY>'
// Prepare API key and Authorization header
const headers = {
apikey: `${ANON_KEY}`,
authorization: `Bearer ${ANON_KEY}`,
}
const client = createClient({
url: URL,
fetchOptions: function createFetchOptions() {
return { headers }
},
})
// Prepare our GraphQL query
const TodosQuery = `
query {
todosCollection {
edges {
node {
id
task
}
}
}
}
`
// Query for the data (React)
const [result, reexecuteQuery] = useQuery({
query: TodosQuery,
})
// Read the result
const { data, fetching, error } = result