跳轉到主要內容

Pexels

本指南說明如何將 Pexels API 整合到您的 superun 應用程式中.此整合使用邊緣函數來安全地代理所有 API 請求,確保您的 API 金鑰永遠不會傳送到客戶端.

文件

有關 Pexels API 的更多詳細資訊,請參閱官方文件:

環境變數

將以下環境變數新增到您的 supabase secrets 中,plugin_secret_prefix 必須為 SUPERUN
  • PEXELS_ACCESS_KEY - Pexels API 金鑰

步驟 1:建立邊緣函數

建立一個 Supabase 邊緣函數來安全地代理 Pexels API 請求.此範例展示了 /search 端點:
// supabase/functions/pexels-search-photos/index.ts

serve(async (req) => {
  try {
    // 從環境變數中取得 Pexels API 金鑰
    const apiKey = Deno.env.get("SUPERUN_PEXELS_ACCESS_KEY");
    
    if (!apiKey) {
      return new Response(
        JSON.stringify({ error: "Pexels API key not configured" }),
        { status: 500, headers: { "Content-Type": "application/json" } }
      );
    }

    // 從請求中解析查詢參數
    const url = new URL(req.url);
    const query = url.searchParams.get("query");
    if (!query) {
      return new Response(
        JSON.stringify({ error: "query is empty" }),
        { status: 400, headers: { "Content-Type": "application/json" } }
      );
    }
    const page = url.searchParams.get("page") || "1";
    const perPage = url.searchParams.get("per_page") || "10";
    const color = url.searchParams.get("color");
    const orientation = url.searchParams.get("orientation");

    // 建立查詢參數
    const params = new URLSearchParams({
      query: query,
      page: page,
      per_page: perPage,
    });
    
    if (color) {
      params.append("color", color);
    }
    if (orientation) {
      params.append("orientation", orientation);
    }

    // 向 Pexels API 發送請求
    const pexelsUrl = `https://api.pexels.com/v1/search?${params.toString()}`;
    
    const response = await fetch(pexelsUrl, {
      headers: {
        "Authorization": apiKey,
      },
    });

    if (!response.ok) {
      throw new Error(`Pexels API error: ${response.status}`);
    }

    const data = await response.json();

    // 回傳 Pexels API 回應
    return new Response(
      JSON.stringify(data),
      {
        headers: { "Content-Type": "application/json" },
      }
    );
  } catch (error) {
    return new Response(
      JSON.stringify({ error: error.message }),
      { status: 500, headers: { "Content-Type": "application/json" } }
    );
  }
});

步驟 2:前端整合

直接從前端呼叫邊緣函數.API 金鑰會安全地保存在伺服器上:

API 歸屬

使用 Pexels API 時,您必須提供適當的歸屬說明:
  • 顯示攝影師姓名並連結到他們的 Pexels 個人檔案
  • 遵循 Pexels API 指南