跳转到主要内容

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 指南