api-proxy-endpoint
Skill này làm gì
Skill này chỉ cho AI agent cách tạo các endpoint nhỏ phía máy chủ giữ API key và phục vụ frontend. Nó dành cho nhà phát triển cần dữ liệu bên ngoài trong một ứng dụng web mà không lộ khóa bí mật.
Khi nào nên dùng
- ✓Khi frontend cần dữ liệu từ một API bên ngoài yêu cầu khóa bí mật.
- ✓Khi bạn muốn một đường dẫn API thống nhất cho frontend bảng điều khiển.
- ✓Khi bạn triển khai backend serverless trên Vercel và cần CORS và xử lý lỗi.
Liên kết skill
https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/api-proxy-endpoint/SKILL.mdSao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.
Cách dùng
Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.
Tin nhắn có sẵn để dán
Dành cho Claude Code, Codex hoặc Cursor: chạy lệnh trong thư mục dự án của bạn và skill sẽ được cài đặt.
Tải tệp SKILL.md về và thả vào thư mục skill của agent.
Ví dụ cách nhờ AI
“Bảng điều khiển của tôi cần dữ liệu cổ phiếu và tin tức từ các API trả phí. Hãy xây dựng các endpoint proxy để khóa vẫn nằm trên máy chủ.”
5 skill mới mỗi tuần. Đọc chỉ 1 phút.
Cách hoạt động
Agent tạo một file cho mỗi API trong thư mục api, cùng một helper dùng chung cho header CORS. Mỗi endpoint đọc khóa trên máy chủ, gọi API bên ngoài và trả kết quả về frontend.
Nội dung kỹ thuật (SKILL.md gốc)
Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.
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
Câu hỏi thường gặp
Tại sao không đặt khóa trong frontend?
Skill nói API key không được lộ trong mã frontend, nên proxy giữ chúng trên máy chủ.
Helper CORS làm gì?
Nó đặt các header cho phép frontend gọi các endpoint và trả lời các yêu cầu preflight OPTIONS.
Nó được thiết kế cho nền tảng hosting nào?
Skill được thiết kế cho các hàm serverless của Vercel.
Chi tiết
Mô tả gốc của tác giả
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
Độ phổ biến
- Sao GitHub
- 7.8k
- Vị trí xếp hạng
- #13038
- Giấy phép
- MIT
- Cập nhật
- 1/11/2026
Bình luận
- …
Thêm skill từ kho mã này
agentpilot
7.8kGiúp agent của bạn cải thiện dự án từng bước bằng cách chuẩn bị tác vụ và chạy vòng lặp AgentPilot, gồm đề xuất, kiểm thử và chấm điểm thay đổi.
openspace
7.8kGiúp agent của bạn thiết lập OpenSpace, công cụ lưu và lấy lại skill của agent, rồi kết nối nó với ứng dụng AI của bạn qua MCP.
rsi-arena
7.8kGiúp agent của bạn thiết lập và chạy các bài kiểm thử benchmark AI chuẩn, như AIME và Terminal-Bench, để so sánh các phương pháp cải tiến khác nhau.
experiment-guide
7.8kGiúp agent của bạn lên kế hoạch các thí nghiệm nhỏ, đọc kết quả và ghi lại phát hiện khi tìm cách cải thiện một chương trình.
Skill tương tự
api-connector-builder
280kGiúp agent của bạn xây dựng kết nối API mới theo đúng mẫu đã có, dùng khi bạn cần thêm một tích hợp mà không tạo cách làm mới.
api-design
280kGiúp agent của bạn thiết kế REST API theo các thực hành tốt nhất, hữu ích để định nghĩa cách API giao tiếp, hiển thị lỗi và tổ chức dữ liệu.
backend-patterns
280kGiúp agent của bạn với các mẫu kiến trúc phía máy chủ và tối ưu cơ sở dữ liệu, hữu ích khi xây dựng hoặc rà soát code chạy trên máy chủ.