api-proxy-endpoint
它能做什么
这项技能向智能体展示如何创建小型服务器端端点,用来保存 API 密钥并为前端提供数据。适合需要在 Web 应用中获取外部数据,又不想暴露密钥的开发者。
适用场景
- ✓当前端需要从要求密钥的外部 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。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 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
- One file per API domain in the
api/directory - Always set CORS headers — frontend runs on different origin during dev
- Environment variables for API keys (
process.env.FINNHUB_API_KEY) - Cache-Control headers for edge caching (Vercel CDN)
- Error wrapping — return structured JSON errors, never raw upstream errors
- Input validation — validate query parameters before calling upstream
- 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
评论
- …
同一仓库的更多技能
agentpilot
7.8k帮你的智能体准备任务并运行 AgentPilot 循环,逐步改进项目:循环会提出修改、测试修改并为其打分。
openspace
7.8k帮你的智能体设置 OpenSpace,这是一个用于存储和获取智能体技能的工具,并通过 MCP 将其连接到你的 AI 应用。
rsi-arena
7.8k帮你的智能体设置并运行标准 AI 基准测试,例如 AIME 和 Terminal-Bench,用来比较不同的改进方法。
experiment-guide
7.8k帮你的智能体规划小型实验、阅读实验结果并记录发现,同时研究如何改进一个程序。