Communitygithub.com

REST API 設計

設計 REST API 表面——資源命名、HTTP 方法與狀態碼語義、錯誤形狀、分頁和過濾——並產出消費者無需提問即可開發的端點規格。當有人問「這個端點該怎麼命名」、「該回傳什麼狀態碼」、「該用 PUT 還是 PATCH」、「如何分頁這個列表」,或在 API 交付外部消費者前進行審查時使用。

REST API 設計 是什麼?

這項技能專門用於設計一致且產品化的 REST API 表面,避免因命名不一致、狀態碼錯誤或分頁策略失當而導致的不可修復的緊耦合問題。它遵循資源優先於方法的嚴格操作流程:先收集消費者類型、領域名詞、集合規模、讀寫比例與驗證模型等輸入,再依序進行資源命名、HTTP 方法與狀態碼分配、錯誤合約統一、分頁與過濾設計,最後設定效能與酬載預算。技能支援 cursor-based 分頁(對成長型集合)與 offset 分頁(僅限小型、受控的管理列表),並強制使用一致的 kebab-case 路徑與 snake_case JSON 欄位命名。最終產出的端點規格包含資源表、共用錯誤形狀、分頁合約、過濾白名單以及每個端點的延遲/酬載預算,確保消費者無需提問即可直接開發客戶端。該技能適用於 Claude Code、Cursor、Codex 等 AI 代理平台,不適用於規劃重大變更的版本棄用、GraphQL 類型設計或用戶端 SDK 生成。

相容平台~Claude Code~Codex CLI✓Cursor
npx skills add https://github.com/SkillMedev/skills/tree/HEAD/skills/api-design

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

REST API 設計 是做什麼的?

API 就是產品:消費者的心智模型,而非你的資料庫結構,決定了 API 的形狀。這項技能要防止的代價高昂的錯誤,是推出不一致的 API 表面——混亂的命名、錯誤的狀態碼、在持續成長的資料表上使用 offset 分頁——每個消費者都會因此寫死應對邏輯,一旦整合就幾乎無法修復。

操作流程

請依此順序進行。資源先於方法,因為方法的語義取決於資源是什麼;錯誤與分頁合約應在撰寫規格前確定,因為事後補救會破壞消費者端相容性。

步驟 1:收集輸入

先收集再設計。將任何假設標記為「猜測」。

  1. 消費者:內部服務、第一方客戶端或外部開發者。外部消費者會提高一致性標準——若未知則預設為外部。
  2. 領域的核心名詞以及哪些名詞擁有哪些名詞(影響巢狀結構)。
  3. 預期的集合大小與成長趨勢。可能超過 ~10,000 筆記錄的列表,排除 offset 分頁。
  4. 每個端點的讀寫比例與延遲期望。
  5. 驗證模型(影響 401 與 403 的正確性)。

步驟 2:命名資源

  • 複數名詞:/users、/orders、/products。
  • 一個層級的擁有關係巢狀:/users/{id}/orders。巢狀不要超過兩層——改用過濾器扁平化(/orders?user_id=... 優於 /users/{id}/orders/{oid}/items/{iid})。
  • 路徑中不要出現動詞;HTTP 方法就是動詞。對於無法對應 CRUD 動詞的實際動作(例如發送發票),以子資源 POST 建模:POST /invoices/{id}/send-attempts。
  • 統一大寫規則:多詞路徑段落使用 kebab-case,JSON 欄位使用 snake_case——選定後一致套用。

步驟 3:指派方法與狀態碼

  • GET:讀取,等冪,無請求主體。回傳 200 加上主體。
  • POST:建立。回傳 201 加上指向新資源的 Location 標頭。在主體中回傳建立的表示,讓客戶端無需額外 GET。
  • PUT:完整取代,等冪。缺少的欄位意味著「清除」,而非「保留」。
  • PATCH:部分更新(JSON Merge Patch 或 JSON Patch——在規格中說明使用哪一種)。
  • DELETE:刪除,等冪,回傳 204。刪除已刪除的資源時,回傳 204 或 404——選一個並記錄下來。
  • 錯誤:400 格式錯誤輸入、401 缺少/無效憑證、403 有效憑證但無權限、404 資源不存在(當揭露存在性是洩漏時,使用 404 而非 403)、409 狀態衝突、422 格式正確但語意無效的輸入、429 速率限制(附上 Retry-After)、500 伺服器錯誤——絕不暴露堆疊追蹤或內部識別碼。

步驟 4:確定錯誤合約

所有錯誤使用同一形狀,機器可讀的錯誤碼優先:

{
  "error": "validation_error",
  "message": "Email is required",
  "field": "email",
  "request_id": "req_abc123"
}

request_id 必須在伺服端記錄,以便支援人員進行關聯。human message 供開發者查看日誌,絕不用於終端使用者顯示。

步驟 5:確定分頁與過濾

  • 任何會成長的集合使用 cursor-based 分頁:回傳一個不透明 cursor 和 has_more 旗標。Offset 分頁僅可接受用於小型、受控、面向管理員的列表——它會線性退化,並在並行寫入下跳過/重複資料列。
  • 預設頁面大小 25,最大值 100。超過最大值的頁面大小回傳 400 拒絕,不要默默截斷。
  • 透過查詢參數進行過濾與排序:?status=active&sort=created_at:desc。紀錄哪些欄位可過濾;對未知的過濾參數回傳 400 而非忽略(默默忽略會隱藏客戶端錯誤)。

步驟 6:套用效能與酬載預算

  • p95 延遲預算:互動式端點 300 毫秒,報表/匯出 1 秒。若操作無法在 1 秒內完成,則改為非同步:202 Accepted 加上一個可輪詢的狀態資源。
  • 回應酬載預算:典型回應保持在 100 KB 以下;任何經常超過 1 MB 的回應需要分頁、欄位選擇(?fields=)或專用的匯出流程。
  • 在 URL 路徑中標示重大變更版本(/v1/)。新增性變更(新的可選欄位)不需要版本提升。棄用時間表則交給 api-versioning-strategist。

對比範例

錯誤:

POST /getUserOrders?userId=42&page=3
→ 200 { "data": [...], "error": null }

路徑中有動詞,POST 卻有 GET 的語義,offset 分頁,200 包裝一個錯誤欄位,讓客戶端必須解析主體才知道呼叫是否失敗。

正確:

GET /users/42/orders?status=shipped&limit=25&cursor=eyJpZCI6OTh9
→ 200 { "orders": [...], "next_cursor": "eyJpZCI6MTIzfQ", "has_more": true }
→ 404 { "error": "not_found", "message": "User 42 does not exist", "request_id": "req_9f2" }

名詞路徑、擁有關係巢狀、cursor 分頁,狀態碼承載結果。

交付物

產出一個端點規格,包含:資源表(路徑、方法、每個方法的狀態碼)、共用錯誤形狀、分頁合約(cursor 格式、預設值、最大值)、過濾白名單,以及每個端點的延遲/酬載預算。

請勿

  • 不要在 API 中鏡像資料庫結構——消費者會與你日後想更改的內部實作耦合。
  • 不要用 200 回傳失敗並附帶錯誤主體;客戶端和監控系統都依賴狀態碼。
  • 不要在無限制的集合上使用 offset 分頁——它會在寫入時重複和跳過資料列,並線性退化。
  • 不要讓路徑巢狀超過兩層;深巢狀只編碼一種存取路徑,排除了所有其他方式。
  • 不要默默忽略未知的查詢參數——拼錯的過濾器回傳未過濾的資料,是資料外洩等級的錯誤。

品質標準

  • 消費者能夠根據這份規格實作客戶端,無需提出任何問題。
  • 每個端點都說明其狀態碼,包括錯誤情況。
  • 所有集合端點共用一個分頁合約;所有錯誤共用一個形狀。
  • 相同的概念在所有路徑和酬載中使用相同的名稱。
  • 每個端點都有明確的延遲預算,超過 1 秒的端點為非同步。

Individual skills in this repo

This repo contains 19 individual skills — each has its own dedicated page.

SkillMedev/skills

Produce an accurate, properly timed caption track (SRT or WebVTT) from a video's audio - transcribing or aligning to the voiceover script, timing cues to speech, and enforcing line-length and reading-speed rules so captions are readable and in sync. Use when someone says "generate captions", "make subtitles from the audio", "transcribe and caption this", "export an SRT or VTT", "the captions are out of sync", or "the subtitles flash by too fast to read". Do NOT use to burn-in, style, reframe, or position an existing caption track for a platform (9:16, brand styling, safe areas) - that is social-video-formatter; do NOT use to animate text word-by-word as a motion graphic - that is kinetic-typography; do NOT use to write the spoken script in the first place - that is narration-script.

SkillMedev/skills

Turns data and charts into a decision-driving narrative structured as headline finding, trend, implication, and recommended action - with finding-led chart titles, context for every number, annotation guidance, and honest flags on any conclusion the data cannot support. Use when someone says "turn these numbers into a story", "what's the takeaway from this data", "help me present these results to leadership", or has charts but no narrative. Do NOT use for compressing a long document into a one-pager - use executive-summary instead - or for running the analysis that produces the findings - use eda-playbook instead.

SkillMedev/skills

Use when a task needs live or historical money data - "convert USD to EUR", "current/past exchange rate", "FX rate on this date / over this range", or "current price of Bitcoin/Ethereum, market cap, 24h change". Frankfurter (ECB reference rates, no key) is the FX default; CoinGecko's free keyless tier covers crypto. Do NOT use for stock quotes or equities - no keyless stock API survives verification, say so instead of guessing; do NOT use for country economic indicators like GDP or inflation series - use government-open-data instead; if the request is a vague "I need live data", route through public-data-api-picker.

SkillMedev/skills

Builds a driver-based FP&A operating model linking business inputs to P&L, balance sheet, and cash flow outputs. Use when building an annual plan, preparing investor materials, running scenario analysis, or stress-testing the business.

SkillMedev/skills

Use when a task needs live geographic lookups - "geocode this address", "what's at these coordinates" (reverse geocoding), "lat/lon for this city", "which country/state is this ZIP or postal code in", or "country facts: capital, currency, population, flag". Nominatim (OpenStreetMap) is the geocoding default; Zippopotam for postal codes; APICountries for country facts. All keyless. Do NOT use for weather at a location - use weather-climate instead; do NOT use for country-level statistics over time (GDP, population trends) - use government-open-data instead; if the request is a vague "I need live data", route through public-data-api-picker.

SkillMedev/skills

Runs the full Getting Things Done loop - capture, clarify, organize, reflect, engage - building a trusted system of context lists, a projects list with defined next actions, and a weekly review habit. Use when someone says "I'm overwhelmed and things are slipping through the cracks", "set up GTD for me", "help me do a brain dump and organize it", or "my to-do list is a mess". Do NOT use for just running the weekly review ritual itself - use weekly-review instead - or for clearing an email backlog - use inbox-zero.

SkillMedev/skills

Processes any email backlog to zero using the 4Ds - Delete, Delegate, Defer, Do - with a mass-archive strategy for the obvious, a touch-each-email-once discipline, and a keep-it-clear system of batched processing windows, ruthless unsubscribing, filters, and a minimal folder setup. Use when someone says "I have 5,000 unread emails", "help me get to inbox zero", "email is eating my whole day", or treats their inbox as a to-do list. Do NOT use for drafting the reply emails themselves or prioritization rules for an ongoing support queue - use email-triage instead - or for protecting focus time around the email windows - use deep-work-planner instead.

SkillMedev/skills

Write landing-page copy section by section - hero, social proof, features-as-benefits, objections, CTA - leading with one promise and proving it down the page. Use when someone asks "write my landing page", "improve my hero headline", "what should the homepage say", "turn these features into benefits", or is shipping a new page for a launch or campaign. Do NOT use for testing and optimizing an existing page's conversion rate - use landing-page-cro instead; for the one-line claim itself use positioning-statement; for the full message ladder use messaging-hierarchy.

SkillMedev/skills

Improves an existing landing page's conversion rate through evidence-first CRO - audit heatmaps and recordings, write structured hypotheses, prioritize with ICE scoring, and run one-variable tests to statistical significance. Use when someone asks "why isn't my landing page converting", "audit this page before we scale spend", "which A/B test should we run first", or after a CVR drop or ahead of a paid-traffic push. Do NOT use for writing a new landing page from scratch - use landing-page-copy instead. Do NOT use for auditing the ad accounts sending the traffic - use paid-acquisition-audit instead. Do NOT use for reading the results of a finished experiment - use ab-test-analyzer instead.

SkillMedev/skills

Runs structured coaching sessions using values clarification and the GROW model, ending every session with one committed action, a deadline, and an if-then plan for the likely obstacle. Use when someone says "I feel stuck in my life", "help me figure out what I want", "hold me accountable to my goals", or "coach me through this decision". Do NOT use for building a stress toolkit - use stress-management instead - or a journaling practice - use journal-framework; for a standing goal-tracking system, use goals-accountability. Coaching, not therapy: signs of clinical distress route to a licensed professional.

SkillMedev/skills

Adapts English content for a target language and region - swapping idioms, setting the right formality register, replacing cultural references, converting dates, units, and currency - and delivers the localized text with a notes column explaining each adaptation and flagging what needs a native reviewer. Use when someone asks "localize this copy for the Japanese market", "adapt our marketing copy for the Mexican market", "make this translation sound native instead of literal", or a literal translation reads foreign, stiff, or risky. Do NOT use for auditing in-product UI text quality - use ux-writing-audit instead.

SkillMedev/skills

Turns a natural-language video brief into a complete, ready-to-preview Remotion composition - extracts duration, scenes, brand colors, aspect ratio, and real copy; plans the frame budget; and writes data-driven React/TypeScript using useCurrentFrame, interpolate, spring, AbsoluteFill, and Sequence, registered in Root.tsx. Use when someone says "build a 20-second product demo video", "animate a feature walkthrough", "write the Remotion code for this marketing clip", or wants a scene-by-scene composition they can scrub in Studio. Do NOT use for rendering, iterating, or batching the finished MP4 - use remotion-render instead - or for installing and scaffolding the project - use remotion-setup instead.

SkillMedev/skills

Scaffolds a new Remotion video project wired for Claude Code Agent Skills - Node check, create-video scaffold, skills install, folder conventions, Google Fonts, and a smoke-test render. Use whenever someone wants to start making videos with Remotion and Claude, even just "make product videos with Claude.

SkillMedev/skills

Classifies incident severity (SEV1-4) using impact, scope, and urgency signals and decides who to page. Use when an alert fires or a report comes in and a severity call must be made quickly.

SkillMedev/skills

Use the Skill Me catalog from inside any conversation - discover, install, and manage Claude skills through the Skill Me MCP, and load installed skills automatically each session.

SkillMedev/skills

Write one platform-native caption from a topic and brand voice, with a front-loaded hook, native length, and a single earned CTA. Use when the user gives a topic (and optionally brand voice or a described image/video) and asks for an Instagram, LinkedIn, X/Twitter, or TikTok caption. Do NOT use when the user wants a dedicated standalone LinkedIn post - use linkedin-post-writer instead; or a multi-post X thread - use tweet-thread-builder instead; or to adapt one existing piece of content into versions for several channels - use cross-platform-reformatter instead.

SkillMedev/skills

Reframe and export a finished video for social platforms - 9:16 ↔ 16:9 cropping, burned-in captions, a platform-native first frame, loop design, and per-platform specs (aspect, length, safe areas) for TikTok, Reels, Shorts, X, and LinkedIn. Use when someone says "make this vertical", "crop to 9:16", "format for TikTok/Reels/Shorts", "add captions/subtitles", "why is my video cut off on mobile", "resize for Instagram", or "export for social". Do NOT use when the question is about the storyboard or shot order before any video exists (use video-storyboard); the animation craft of how elements move (use motion-design-principles); animated word-by-word caption styling (use kinetic-typography); palette, contrast, or lighting (use motion-color-and-light); directing the product-demo content and screen choreography (use product-demo-director); or scoring, beat-syncing, or audio (use sound-and-music-sync) - this is the craft layer that decides WHAT to format for the feed, then hands a concrete spec to remotion-compo...

SkillMedev/skills

Writes and tunes PySpark jobs - join strategy and broadcast size limits, shuffle-partition sizing, skew diagnosis and salting, UDF avoidance, caching, and output file layout - with concrete size and skew thresholds. Use when someone asks "why is my Spark job slow", "should I broadcast this join", "one task takes forever while the rest finish", "my job OOMs during a join", or is writing a new PySpark ETL job. Do NOT use for Kafka topic, consumer-group, or streaming-pipeline design - use kafka-pipelines instead; do NOT use for single-machine dataframe work that fits in memory - use pandas-expert instead.

SkillMedev/skills

Builds clean, performant, accessible SwiftUI views with correct state ownership, scoped invalidation, and smooth list scrolling, and reviews existing SwiftUI code against a concrete frame-time and re-render budget. Use when someone asks "why does my SwiftUI list stutter", "should this be @State or @Observable", "my whole screen re-renders when one row changes", "how do I animate this transition", or wants a SwiftUI view built or refactored. Do NOT use for cross-platform React Native apps - use react-native-pro instead; do NOT use for Flutter widget trees - use flutter-widget-architect instead; do NOT use for Android Compose UIs - use jetpack-compose-builder instead.

相關技能