跳转到主要内容

Unsplash

本指南说明如何将 Unsplash API 整合到您的 superun 应用程序中.此整合使用边缘函数来安全地代理所有 API 请求,确保您的 API 金钥永远不会传送到客户端.

文档

有关 Unsplash API 的更多详细资讯,请参阅官方文件:

环境变数

将以下环境变数新增到您的 supabase secrets 中,plugin_secret_prefix 必须为 SUPERUN
  • UNSPLASH_ACCESS_KEY - Unsplash 存取金钥

步骤 1:建立边缘函数

建立一个 Supabase 边缘函数来安全地代理 Unsplash API 请求.此范例展示了 /search/photos 端点:
// supabase/functions/unsplash-search-photos/index.ts

serve(async (req) => {
  try {
    // 从环境变量中取得 Unsplash 存取金钥
    const accessKey = Deno.env.get("SUPERUN_UNSPLASH_ACCESS_KEY");
    
    if (!accessKey) {
      return new Response(
        JSON.stringify({ error: "Unsplash 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";

    // 向 Unsplash API 发送请求
    const unsplashUrl = `https://api.unsplash.com/search/photos?query=${encodeURIComponent(query)}&page=${page}&per_page=${perPage}`;
    
    const response = await fetch(unsplashUrl, {
      headers: {
        "Authorization": `Client-ID ${accessKey}`,
      },
    });

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

    const data = await response.json();

    // 回传 Unsplash 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 归属

使用 Unsplash API 时,您必须提供适当的归属说明:
  • 显示摄影师姓名并连结到他们的 Unsplash 个人文件
  • 在所有连结中包含 utm_sourceutm_medium 参数
  • 遵循 Unsplash API 指南