0Pricing
Supabase Backend as a Service · บทเรียน

การผสานรวมกับบริการภายนอก

เรียนรู้รูปแบบการเชื่อมต่อแบ็กเอนด์ของซูเปอร์เบสกับ API และบริการจากผู้ให้บริการภายนอก เพื่อเพิ่มขีดความสามารถของแอปพลิเคชัน

การผสานรวมกับบริการภายนอก เป็นบทเรียน Supabase Backend as a Service ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 3 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Supabase Backend as a Service และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Supabase Backend as a Service มีบทเรียนทั้งหมด 3 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why External Services?

Your app often needs to do more than just manage data in Supabase. Think about sending emails, processing payments, or integrating AI tools.

This is where integrating with external services comes in! It allows your Supabase backend to communicate with other APIs and platforms to extend your application's capabilities.

Common Integration Needs

Many common app features rely on external services:

  • Payment Gateways: Stripe, PayPal for transactions.
  • Email/SMS: SendGrid, Twilio for notifications.
  • AI/ML APIs: OpenAI, Google Cloud AI for advanced features.
  • Geo-location: Google Maps, Mapbox for mapping services.
  • Analytics: Mixpanel, Segment for user behavior tracking.

Supabase's Role: Edge Functions

While your client-side app can call external APIs directly, for secure and backend-driven integrations, Supabase Edge Functions are your best friend.

Edge Functions act as serverless backend logic, running close to your users. They can make HTTP requests to any external API without exposing sensitive information directly in your client-side code.

Making an API Call with Deno

Supabase Edge Functions are built on Deno, which uses the standard fetch API for making network requests, similar to browsers. This makes it straightforward to interact with external services.

The flow is: your client invokes an Edge Function, which then makes a request to the external API, processes the response, and sends it back to your client.

Code Demo: Fetching External Data

Here's a simple Edge Function that fetches a random 'todo' item from a public API (JSONPlaceholder). Notice how we use Deno.serve as the entry point for the function.

import { serve } from 'https://deno.land/std@0.177.0/http/server.ts'

Deno.serve(async (req) => {
  const { name } = await req.json()

  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos/1')
    const data = await response.json()

    return new Response(JSON.stringify({
      message: `Hello ${name}! Here's a todo: ${data.title}`,
    }), {
      headers: { 'Content-Type': 'application/json' },
      status: 200,
    })
  } catch (error) {
    return new Response(JSON.stringify({
      error: error.message,
    }), {
      headers: { 'Content-Type': 'application/json' },
      status: 500,
    })
  }
})

Invoking the Edge Function

Once deployed, your client-side application can invoke this Edge Function using the Supabase client library. The function name here would be, for example, 'fetch-todo'.

The invoke method handles sending data to your function and receiving its response.

// Client-side JavaScript
async function getTodoFromEdgeFunction() {
  try {
    const { data, error } = await supabase.functions.invoke('fetch-todo', {
      body: { name: 'CoddyKit User' },
    })

    if (error) {
      console.error('Function error:', error)
    } else {
      console.log('Function response:', data)
    }
  } catch (err) {
    console.error('Invocation error:', err)
  }
}

// Call the function (e.g., on button click)
// getTodoFromEdgeFunction();

Securing API Keys with Supabase Secrets

Hardcoding API keys directly into your Edge Function code is a security risk. If your code is ever exposed, your keys are compromised.

Supabase provides Secrets to securely store environment variables for your Edge Functions. These are not part of your codebase and are injected at runtime.

Using Secrets in Edge Functions

First, you'd set a secret using the Supabase CLI: supabase secrets set MY_EXTERNAL_API_KEY=your_key_here. Then, in your Edge Function, you access it via Deno.env.get('MY_EXTERNAL_API_KEY').

This keeps your sensitive credentials safe and out of your version control.

import { serve } from 'https://deno.land/std@0.177.0/http/server.ts'

Deno.serve(async (req) => {
  // Access the secret environment variable
  const apiKey = Deno.env.get('MY_EXTERNAL_API_KEY') || 'NO_KEY_SET'

  // Example: Use the apiKey in a header for an external API call
  // const response = await fetch('https://api.example.com/data', {
  //   headers: { 'Authorization': `Bearer ${apiKey}` },
  // })

  return new Response(JSON.stringify({
    message: `API Key accessed: ${apiKey.substring(0, 5)}...`,
  }), {
    headers: { 'Content-Type': 'application/json' },
    status: 200,
  })
})

Handling Responses & Errors Robustly

When integrating external services, always prepare for success and failure. Parse the API's response correctly (often JSON) and handle potential errors.

  • Check HTTP Status: Not all 2xx responses are successes; some APIs use 4xx for business logic errors.
  • Try-Catch Blocks: Essential for network errors or issues parsing responses.
  • Meaningful Error Messages: Return clear error messages to the client without exposing internal API details.

Best Practices for Integrations

To ensure robust and scalable integrations:

  • Rate Limiting: Respect external API rate limits to avoid getting blocked.
  • Retries: Implement exponential backoff for transient network issues.
  • Timeouts: Set reasonable timeouts for external requests to prevent hanging.
  • Logging: Log requests and responses (especially errors) for debugging.
  • Idempotency: Design your functions to handle duplicate requests gracefully for operations like payments.

Quick Check on Integration

You're building an Edge Function to send an email using an external email API. You need to include your email service API key.

Recap: Integrating External Services

You've learned how to extend your Supabase application's capabilities by integrating with external APIs and services.

  • Edge Functions are ideal for secure backend-to-external-service communication.
  • Use fetch within Deno Edge Functions to make HTTP requests.
  • Always secure sensitive credentials like API keys using Supabase Secrets.
  • Implement robust error handling and follow best practices for reliable integrations.

This opens up a world of possibilities for building powerful and feature-rich applications!

คำถามที่พบบ่อย

บทเรียน “การผสานรวมกับบริการภายนอก” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การผสานรวมกับบริการภายนอก” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Supabase Backend as a Service ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Supabase Backend as a Service มีบทเรียนทั้งหมด 3 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การผสานรวมกับบริการภายนอก”

เรียนรู้รูปแบบการเชื่อมต่อแบ็กเอนด์ของซูเปอร์เบสกับ API และบริการจากผู้ให้บริการภายนอก เพื่อเพิ่มขีดความสามารถของแอปพลิเคชัน คุณปฏิบัติ Supabase Backend as a Service ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Supabase Backend as a Service หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Supabase Backend as a Service บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 3 บทเรียน

บทเรียน “การผสานรวมกับบริการภายนอก” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Supabase Backend as a Service นี้ได้ไหม

ได้ บทเรียน Supabase Backend as a Service ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การผสานรวมกับบริการภายนอก
  2. คิวงานด้วยซูเปอร์เบสและผู้ประมวลผลงาน
  3. การจัดกำหนดการงานที่ทำซ้ำด้วย pg_cron
← กลับไปที่ Supabase Backend as a Service