3.5 Hours

3. The Auto-Generated REST API (PostgREST)

API

Zero-Code REST APIs From Your Schema

PostgREST is the engine behind Supabase's instant REST API. The moment you create a table in the public schema, PostgREST exposes CRUD endpoints for it. Understanding how PostgREST works under the hood is the key to writing efficient Supabase queries and understanding their HTTP footprint.

PostgREST maps HTTP verbs to SQL operations automatically. GET requests become SELECT queries. POST becomes INSERT. PATCH becomes UPDATE. DELETE becomes DELETE. It also maps URL parameters to SQL filters. This means you can perform complex queries using standard HTTP. The API is self-documenting — you can query the /?select=* endpoint to see the schema. PostgREST also handles relationships automatically using foreign key constraints. You can traverse one-to-many and many-to-many relationships using nested select syntax. Understanding these mappings helps you optimize your queries and debug issues. When you use the Supabase client library, it generates these HTTP requests for you. But knowing the underlying HTTP API helps you understand what's happening on the network.

HTTP Verbs → SQL Operations

PostgREST maps HTTP methods to SQL operations in a predictable way. GET requests perform SELECT queries with optional filtering, ordering, and pagination. POST requests perform INSERT operations and can return the inserted row with the Prefer: return=representation header. PATCH requests perform UPDATE operations on rows matching your filter — never use PATCH without a filter or you'll update all rows. DELETE requests perform DELETE operations on rows matching your filter. RPC endpoints let you call Postgres functions directly via /rpc/function_name. Understanding these mappings is essential for building efficient applications. Always use specific filters to limit the scope of your updates and deletes. The Supabase client library handles these HTTP calls for you, but knowing the underlying protocol helps with debugging and optimization.

GET → SELECT

Fetch rows. Supports filtering, ordering, pagination, column selection, and relationship traversal.

POST → INSERT

Insert one or many rows. Returns the inserted rows if you add the Prefer: return=representation header.

PATCH → UPDATE

Update rows matching your filter. Never updates everything — you must provide a WHERE condition.

DELETE → DELETE

Delete rows matching your filter. Must have RLS enabled to prevent accidents.

POST (RPC) → Function

Call a Postgres function directly via /rpc/function_name. Enables complex multi-step operations.

TypeScript
// SELECT with filtering, ordering, pagination
const { data } = await supabase
  .from('posts')
  .select('id, title, created_at')
  .eq('published', true)
  .gte('created_at', '2024-01-01')
  .order('created_at', { ascending: false })
  .range(0, 9);

Querying Relationships (Joins)

PostgREST can automatically traverse foreign key relationships, eliminating the need for manual JOINs in your API calls. This works in both directions. When you select from a table, you can embed related data using nested syntax. For a one-to-many relationship, you embed the related records as an array. For a many-to-one relationship, you embed a single object. This pattern is called resource embedding and it's one of the most powerful features of PostgREST. It eliminates the N+1 query problem that plagues traditional REST APIs. You can nest as deeply as you need, but be careful about query complexity. The PostgREST engine generates efficient SQL JOINs for you. This makes the API feel like GraphQL but with the simplicity of REST.

TypeScript
// Fetch posts WITH their author profile (forward relationship)
const { data } = await supabase
  .from('posts')
  .select(`
    id,
    title,
    body,
    author:profiles!user_id (username, avatar_url)
  `);
Avoid N+1 Queries:Using the nested select syntax fetches all related data in a single query under the hood. Never call .from(<strong><code>posts) in a loop to get each post's author — use nested selects instead.

RPC: Calling Postgres Functions

For complex operations — multi-step transactions, aggregations, business logic — create a Postgres function and call it via .rpc(). RPC functions are the escape hatch when the REST API isn't expressive enough. They run inside the database transaction with full access to all Postgres features. You can use PL/pgSQL to implement complex business logic that would be difficult or impossible with the REST API alone. RPC functions can return tables, JSON, or scalar values. They can also perform multiple operations atomically. This is essential for implementing features like purchasing items, transferring money, or any operation that requires multiple steps to succeed or fail together. Use SECURITY DEFINER on your RPC functions to control permissions. Always validate inputs and use parameterized queries to prevent SQL injection.

SQL
-- A function that does a safe atomic purchase
CREATE OR REPLACE FUNCTION purchase_item(p_user_id UUID, p_item_id BIGINT, p_quantity INT)
RETURNS JSONB AS $$
DECLARE
  v_price NUMERIC;
  v_stock INT;
BEGIN
  SELECT price, stock INTO v_price, v_stock
  FROM products WHERE id = p_item_id FOR UPDATE;
  IF v_stock < p_quantity THEN
    RETURN jsonb_build_object('success', false, 'error', 'Out of stock');
  END IF;
  UPDATE products SET stock = stock - p_quantity WHERE id = p_item_id;
  INSERT INTO orders (user_id, item_id, quantity, total)
    VALUES (p_user_id, p_item_id, p_quantity, v_price * p_quantity);
  RETURN jsonb_build_object('success', true);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

Column Selection & Performance

Optimizing column selection is critical for performance. Never use .select(*) in production — always specify only the columns you need to reduce payload size and improve query speed. For counting rows without fetching data, use .select(*, { count: exact, head: true }). This sends a HEAD request that returns only the row count. For filtering on related tables, use the .filter() method with a dot notation like profiles.role. For full-text search, use .textSearch() with a search type parameter. These optimizations reduce network traffic and database load. When building public APIs, always implement pagination with .range() to limit result sets. Use indexes on columns you frequently filter by. Monitor your query performance using the dashboard's query statistics. These practices ensure your application remains fast as your data grows.

  • Never use .select(*) in production — always specify the columns you need to reduce payload size.
  • Count without fetching rows: .select(<strong><code>*, { count: exact, head: true })
  • Filtering on related tables: Use .filter(<strong><code>profiles.role, eq, admin) for cross-table conditions.
  • Full-text search: .textSearch(<strong><code>body, supabase postgres, { type: websearch })

Knowledge Check

Ready to test your understanding of 3. The Auto-Generated REST API (PostgREST)?

Back