本文へスキップ
Skillpedia
APIとサーバー(バックエンド)7.8k · #13038

api-proxy-endpoint

できること

このスキルは、AIエージェントが、APIキーをサーバー側に保持する小さなサーバー側エンドポイントを作る方法を示します。秘密のキーを公開せずに、Webアプリで外部データを使いたい開発者向けです。

使う場面

  • ✓フロントエンドが、秘密のキーを必要とする外部APIのデータを必要とするとき。
  • ✓ダッシュボードのフロントエンドに、1つにまとめたAPIの経路がほしいとき。
  • ✓Vercelでサーバーレスのバックエンドを公開し、CORSとエラー処理が必要なとき。

スキルのリンク

https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/api-proxy-endpoint/SKILL.md

コピーしてAI(Claude、ChatGPT、Cursor)に貼り付け、指示に従うよう頼んでください。

使い方

いちばん簡単な方法:メッセージをコピーしてAIに貼り付けるだけ。AIがスキルを読んで指示に従います。

貼り付け用メッセージ

このスキルを使って手伝ってください:https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/api-proxy-endpoint/SKILL.md このリンクのSKILL.mdファイルを読んで、私の作業でその指示に従ってください。
こういうスキルを、AIが自分で見つけてくれたら?無料のSkillpedia MCPをインストール。1行で、作業の前に15,000+のスキルから探してくれます。1分でインストール →

AIへの頼み方の例

“私のダッシュボードには、有料APIの株式とニュースのデータが必要です。キーがサーバー上に残るように、プロキシのエンドポイントを作ってください。”

毎週5つの新しいスキル。1分で読めます。

仕組み

エージェントは、apiフォルダーの下にAPIごとのファイルを1つずつ作り、CORSヘッダーを扱う共通のヘルパーを作ります。各エンドポイントはサーバー上でキーを読み、外部APIを呼び出し、結果をフロントエンドに返します。

技術的な内容(元のSKILL.md)

作者による元のテキスト(英語)をGitHubからそのまま表示しています。

API Proxy Endpoint Pattern

External APIs often require API keys that must not be exposed in frontend code. Create serverless proxy endpoints that:

  • Hide API keys on the server side
  • Provide a unified /api/* namespace for the frontend
  • Handle CORS, rate limiting, and error wrapping

Endpoint Structure

Each API endpoint is a file in the api/ directory:

api/
├── stocks.ts          # Stock market data proxy
├── news.ts            # News API proxy
├── calendar.ts        # Calendar events proxy
└── _cors.ts           # Shared CORS helper

CORS Helper

// api/_cors.ts
export function corsHeaders() {
  return {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type',
  };
}

export function handleCors(req: Request): Response | null {
  if (req.method === 'OPTIONS') {
    return new Response(null, { status: 204, headers: corsHeaders() });
  }
  return null;
}

Example: Stock Proxy Endpoint

// api/stocks.ts
import type { VercelRequest, VercelResponse } from '@vercel/node';

export default async function handler(req: VercelRequest, res: VercelResponse) {
  // CORS
  res.setHeader('Access-Control-Allow-Origin', '*');
  if (req.method === 'OPTIONS') return res.status(204).end();

  const symbols = (req.query.symbols as string || '').split(',').filter(Boolean);
  if (symbols.length === 0) {
    return res.status(400).json({ error: 'Missing symbols parameter' });
  }

  const apiKey = process.env.FINNHUB_API_KEY;
  if (!apiKey) {
    return res.status(500).json({ error: 'API key not configured' });
  }

  try {
    const quotes = await Promise.all(
      symbols.map(async (sym) => {
        const resp = await fetch(
          `https://finnhub.io/api/v1/quote?symbol=${sym}&token=${apiKey}`
        );
        if (!resp.ok) throw new Error(`Finnhub ${resp.status}`);
        const data = await resp.json();
        return {
          symbol: sym,
          price: data.c,       // current price
          change: data.dp,     // percent change
          high: data.h,
          low: data.l,
          open: data.o,
          prevClose: data.pc,
        };
      })
    );
    res.setHeader('Cache-Control', 's-maxage=30, stale-while-revalidate=60');
    return res.json({ quotes });
  } catch (err) {
    console.error('Stock API error:', err);
    return res.status(502).json({ error: 'Upstream API failed' });
  }
}

Example: News Proxy Endpoint

// api/news.ts
import type { VercelRequest, VercelResponse } from '@vercel/node';

export default async function handler(req: VercelRequest, res: VercelResponse) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  if (req.method === 'OPTIONS') return res.status(204).end();

  const apiKey = process.env.NEWS_API_KEY;
  if (!apiKey) return res.status(500).json({ error: 'API key not configured' });

  const query = req.query.q as string || '';
  const category = req.query.category as string || 'general';
  const lang = req.query.lang as string || 'en';

  try {
    const url = query
      ? `https://gnews.io/api/v4/search?q=${encodeURIComponent(query)}&lang=${lang}&max=20&token=${apiKey}`
      : `https://gnews.io/api/v4/top-headlines?category=${category}&lang=${lang}&max=20&token=${apiKey}`;

    const resp = await fetch(url);
    if (!resp.ok) throw new Error(`GNews ${resp.status}`);
    const data = await resp.json();

    res.setHeader('Cache-Control', 's-maxage=120, stale-while-revalidate=300');
    return res.json({
      articles: (data.articles || []).map((a: any) => ({
        title: a.title,
        description: a.description,
        url: a.url,
        source: a.source?.name || '',
        publishedAt: a.publishedAt,
        image: a.image,
      })),
    });
  } catch (err) {
    console.error('News API error:', err);
    return res.status(502).json({ error: 'Upstream API failed' });
  }
}

Key Patterns

  1. One file per API domain in the api/ directory
  2. Always set CORS headers — frontend runs on different origin during dev
  3. Environment variables for API keys (process.env.FINNHUB_API_KEY)
  4. Cache-Control headers for edge caching (Vercel CDN)
  5. Error wrapping — return structured JSON errors, never raw upstream errors
  6. Input validation — validate query parameters before calling upstream
  7. Typed responses — keep response shapes consistent for frontend consumption

Local Deve

よくある質問

なぜキーをフロントエンドに置かないのですか?

APIキーはフロントエンドのコードに公開してはならないため、プロキシがキーをサーバー上に保持するとスキルは述べています。

CORSのヘルパーは何をしますか?

フロントエンドがエンドポイントを呼び出せるようにするヘッダーを設定し、プリフライトのOPTIONSリクエストに応答します。

どのホスティング向けに設計されていますか?

スキルは、Vercelのサーバーレス関数向けに設計されています。

詳細

作者による元の説明

Create serverless API proxy endpoints that hide API keys and provide a unified backend for the dashboard frontend. Designed for Vercel deployment.

repo: HKUDS/AgentPilot

人気

GitHubのスター
7.8k
ランキング
#13038
ライセンス
MIT
更新日
2026/11/1

このスキルは役に立ちますか?

0

ログイン して投票しましょう。

コメント

  • …

このリポジトリの他のスキル

似ているスキル