본문으로 건너뛰기
Skillpedia
API 및 서버 (백엔드)7.8k · #13038

api-proxy-endpoint

하는 일

이 스킬은 AI 에이전트가 API 키를 보관하고 프런트엔드에 데이터를 제공하는 작은 서버 측 엔드포인트를 만드는 방법을 보여 줍니다. 비밀 키를 노출하지 않고 웹 앱에 외부 데이터를 넣어야 하는 개발자를 위한 스킬입니다.

사용하는 경우

  • ✓프런트엔드가 비밀 키가 필요한 외부 API의 데이터를 필요로 할 때.
  • ✓대시보드 프런트엔드를 위해 하나의 통합 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가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/api-proxy-endpoint/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“제 대시보드에 유료 API에서 주가와 뉴스 데이터가 필요합니다. 키가 서버에 남도록 프록시 엔드포인트를 만들어 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

에이전트는 api 폴더 아래 API마다 파일 하나를 만들고, 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

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬