Supabase Made Easy: Your First Steps to Building with Open Source Firebase Alternative

Writing Your First API Endpoint: Fetching Data with Functions

Section 3

Building APIs with Supabase Functions

Supabase Made Easy: Your First Steps to Building with Open Source Firebase AlternativeBuilding APIs with Supabase Functions

One of the most common tasks when building web applications is fetching data. Supabase Functions allow you to write serverless functions that can interact with your database and expose this data through API endpoints. In this section, we'll guide you through creating your very first API endpoint to fetch data from your Supabase project.

Let's imagine we have a simple table called todos in our Supabase database with columns like id, task, and is_complete. Our goal is to create a function that, when called via an HTTP request, returns all the tasks from this table.

First, you'll need to navigate to the 'Edge Functions' section in your Supabase project dashboard. From there, click on 'New Function' to start creating a new function. You'll be prompted to give your function a name. Let's call it get-todos.

Supabase provides a pre-written boilerplate for new functions. We'll modify this to fetch our data. The core of our function will be written in JavaScript (or TypeScript if you prefer). Here's how the get-todos function might look:

import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'
import { corsHeaders } from './_shared/cors.ts'

// Supabase client setup (assuming you have your SUPABASE_URL and SUPABASE_ANON_KEY set as environment variables)
import { createClient } from '@supabase/supabase-js'

const supabase = createClient(Deno.env.get('SUPABASE_URL')!, Deno.env.get('SUPABASE_ANON_KEY')!)

serve(async (req) => {
  // Check if it's a CORS preflight request
  if (req.method === 'OPTIONS') {
    return new Response('OK', { headers: corsHeaders })
  }

  // This is where the magic happens: fetching data from Supabase
  try {
    const { data, error } = await supabase
      .from('todos')
      .select('*') // Select all columns

    if (error) {
      throw error
    }

    // Return the fetched data as a JSON response
    return new Response(JSON.stringify(data), {
      headers: {
        ...corsHeaders,
        'Content-Type': 'application/json',
      },
    })
  } catch (error) {
    return new Response(JSON.stringify({ error: error.message }), {
      headers: {
        ...corsHeaders,
        'Content-Type': 'application/json',
      },
      status: 500, // Internal Server Error
    })
  }
})

Let's break down the key parts of this code:

  • Importing Dependencies: We import serve from Deno's standard library for handling HTTP requests and corsHeaders for Cross-Origin Resource Sharing. Crucially, we also import createClient from the Supabase JS library to interact with our database.
  • Supabase Client Initialization: We create an instance of the Supabase client using your project's URL and anonymous key, which are securely stored as environment variables in your Supabase Function's configuration.
チャプターへ戻る