SupabaseS
Supabase2y ago
Sam

How to use the HTTP API For Supabase to GET / POST data and return records?

I am struggling to use the Supabase http api, and looking for some more detailed documentation — for example, the required headers for different types of requests. (It took me a long time of searching to realize that a 'PREFER' header is required to try and return a record while inserting, is there any official documentation for requirements like that?

As an example, in a Netlify function, I am trying to make a POST request work. When the function is structured like this:

    const response = await fetch(`${process.env.SUPABASE_URL}/rest/v1/posts?select=*`, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'apikey': process.env.SUPABASE_API_KEY,
        'Authorization': `Bearer ${process.env.SUPABASE_API_KEY}`,
    },
    body: JSON.stringify(newData),
    })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));


It successfully creates a new record in the specified table, but returns an invalid response.

When I try this function instead, using the Prefer header

    const response = await fetch(`${process.env.SUPABASE_URL}/rest/v1/posts?select=*`, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'apikey': process.env.SUPABASE_API_KEY,
        'Authorization': `Bearer ${process.env.SUPABASE_API_KEY}`,
        'Prefer': 'return=representation',
    },
    body: JSON.stringify(newData),
    })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));


I get the following error, which doesn't appear when making the same http request just without the 'Prefer' header.

{
  code: '42501',
  details: null,
  hint: null,
  message: 'new row violates row-level security policy for table "posts"'
}


Can someone help me with some more detailed and simple code examples for the http api, such as inserting a record and returning the result, getting records from a table, getting records with a filter, and getting records with a foreign key reference included?
Was this page helpful?