首页 / Skills / 开发提效 / API 与接口设计 API and Interface Design
开发提效

API 与接口设计 API and Interface Design

Addy OsmaniMITSkill 语言: 英文
协议已核对不含脚本低风险
演示真实运行记录 · claude-sonnet-5-5 · 2026年10月
Design the HTTP API for a small invoicing service (fictional): customers, invoices with line items, and a "pay invoice" action that charges a card through a payment provider and must be safe to retry because mobile clients have flaky networks. We expect more fields to be added later and several mobile app versions in the wild. Give me the endpoints, the error format, the pagination and the retry-safety design, with the main TypeScript types.
Skill: api-and-interface-design

Invoicing API design

Principles

  • One version, extended additively. Everything lives under /v1. New fields are optional and added to responses, and nothing is removed or retyped. A /v2 is a last resort.
  • Old app versions must survive. Clients ignore unknown fields and treat enums as open: an unknown value falls back to a default. This is a documented rule for client authors. Server responses always include every field, using null rather than omitting.
  • Money is { amount: integer minor units, currency: ISO-4217 }. Never use floats.
  • Naming: plural nouns, camelCase fields, UPPER_SNAKE enum values, and IDs that are opaque prefixed strings (inv_…, cus_…).

Endpoints

POST   /v1/customers
GET    /v1/customers                      ?limit&cursor&email&createdAfter
GET    /v1/customers/{customerId}
PATCH  /v1/customers/{customerId}         (partial; JSON merge-patch)

POST   /v1/invoices                       (creates DRAFT, line items inline)
GET    /v1/invoices                       ?limit&cursor&customerId&status&issuedAfter
GET    /v1/invoices/{invoiceId}
PATCH  /v1/invoices/{invoiceId}           (DRAFT only; If-Match required)
POST   /v1/invoices/{invoiceId}/finalization   (DRAFT → OPEN, immutable after)
POST   /v1/invoices/{invoiceId}/void           (OPEN → VOID)

POST   /v1/invoices/{invoiceId}/payments  (the pay action; Idempotency-Key required)
GET    /v1/invoices/{invoiceId}/payments
GET    /v1/payments/{paymentId}           (poll target for pending/unknown outcomes)
  • Pay is modeled as creating a payment attempt. That gives the client something to poll and gives us an audit trail.
  • Line items are part of the invoice. They are replaced as a whole via PATCH on a DRAFT, so there is no separate line-item endpoint to keep consistent. After finalization the invoice is immutable.
  • Concurrent edits use ETag / If-Match. A mismatch returns 412 PRECONDITION_FAILED.

Types

type Id<P extends string> = `${P}_${string}`;
type CustomerId = Id<'cus'>; type InvoiceId = Id<'inv'>; type PaymentId = Id<'pay'>;

interface Money { amount: number; currency: string }   // amount: integer minor units

interface Customer {
  id: CustomerId;
  name: string;
  email: string;
  metadata: Record<string, string>;     // escape hatch for future fields
  createdAt: string;                    // RFC 3339 UTC
  updatedAt: string;
}
interface CreateCustomerInput { name: string; email: string; metadata?: Record<string, string> }
type UpdateCustomerInput = Partial<CreateCustomerInput>;

type InvoiceStatus = 'DRAFT' | 'OPEN' | 'PAID' | 'VOID';   // clients: unknown → treat as OPEN-like/readonly

interface LineItem {
  id: string;
  description: string;
  quantity: number;                     // integer
  unitPrice: Money;
  total: Money;                         // server-computed
}
interface LineItemInput { description: string; quantity: number; unitPrice: Money }

interface Invoice {
  id: InvoiceId;
  customerId: CustomerId;
  status: InvoiceStatus;
  lineItems: LineItem[];
  total: Money;                         // server-computed
  amountDue: Money;
  dueDate: string | null;
  createdAt: string;
  updatedAt: string;
}
interface CreateInvoiceInput { customerId: CustomerId; lineItems: LineItemInput[]; dueDate?: string }
type UpdateInvoiceInput = Partial<Omit<CreateInvoiceInput, 'customerId'>>;

// Payment
interface PaymentMethodInput { token: string }   // provider-issued token; raw card data never touches us

type PaymentStatus = 'PROCESSING' | 'SUCCEEDED' | 'FAILED' | 'REQUIRES_ACTION' | 'UNKNOWN';

interface Payment {
  id: PaymentId;
  invoiceId: InvoiceId;
  status: PaymentStatus;
  amount: Money;
  failure: { code: string; message: string } | null;  // e.g. CARD_DECLINED
  nextAction: { type: string; url?: string } | null;  // e.g. 3-D Secure; open-ended
  createdAt: string;
  updatedAt: string;
}
interface CreatePaymentInput { paymentMethod: PaymentMethodInput }  // amount is NOT client-supplied: it's the invoice's amountDue

// Envelopes
interface Page<T> { data: T[]; page: { nextCursor: string | null; hasMore: boolean } }

The client doesn't send the amount to pay. The server charges amountDue, so a stale or tampered client can't over- or under-charge.

Error format

One shape for every non-2xx response, including 5xx from gateways where we control them:

interface ApiError {
  error: {
    code: string;          // stable, machine-readable; clients switch on this, never on message
    message: string;       // human-readable, English, may change, not a contract
    requestId: string;     // also in the X-Request-Id header
    retryable: boolean;    // tells the client whether retrying the same request can help
    details?: FieldViolation[] | Record<string, unknown>;
  };
}
interface FieldViolation { field: string; code: string; message: string }  // e.g. "lineItems[0].quantity"
Status Code examples Notes
400 MALFORMED_REQUEST Unparseable body, bad header
401 / 403 UNAUTHENTICATED / FORBIDDEN
404 NOT_FOUND
409 INVOICE_NOT_PAYABLE, REQUEST_IN_PROGRESS State conflict, or in-flight duplicate
412 PRECONDITION_FAILED ETag mismatch
422 VALIDATION_FAILED, IDEMPOTENCY_KEY_REUSED Semantically invalid
429 RATE_LIMITED Retry-After header
502/503/504 PROVIDER_UNAVAILABLE, UNAVAILABLE retryable: true
500 INTERNAL No internals leaked

A declined card is a business outcome, not an HTTP error. Pay returns 200 with a Payment whose status is FAILED and failure.code is CARD_DECLINED. A replay then returns exactly the same thing instead of an error that looks like a transport failure.

Pagination

Use cursor pagination, not page numbers. Mobile lists are infinite scroll, and offset pages duplicate or skip rows when invoices are created between fetches.

  • Request: GET /v1/invoices?limit=25&cursor=<opaque>. The default limit is 25 and the maximum is 100.
  • Response: Page<Invoice>. Pass page.nextCursor back verbatim.
  • The cursor is opaque base64 that encodes the sort key (createdAt, id) plus a filter hash. Clients must not parse it. That lets us change the internals without breaking old apps.
  • Sort is fixed at createdAt desc, id desc. Add a sort param later if needed.
  • There is no totalItems. Counts are expensive and drift. If needed later, add it as an opt-in ?include=totalCount.
  • A cursor reused with different filters returns 400 INVALID_CURSOR.

Retry-safe payments

Contract

POST /v1/invoices/{id}/payments requires an Idempotency-Key header, and returns 400 without one.

  • The client generates the key once per user intent, when the user taps "Pay". It persists the key (in memory plus local storage) and reuses it on every retry of that tap. A new tap after a definitive failure gets a new key.
  • The key is never generated inside the HTTP retry layer. If it were, each retry would be a new charge.

Server algorithm

  1. Claim atomically. Insert into idempotency_keys(scope, key, request_hash, payment_id, state, response, created_at) with a unique constraint on (accountId, key). The constraint picks the winner. Never do SELECT then INSERT.
  2. If the insert hits the unique violation, load the existing row:
    • request_hash differs (hash of invoiceId + body): 422 IDEMPOTENCY_KEY_REUSED.
    • State is in_progress: 409 REQUEST_IN_PROGRESS with Retry-After: 2 and retryable: true. Never let a second caller through because the first "seems stuck".
    • State is completed: replay the stored status and body, plus the header Idempotent-Replayed: true.
  3. Record intent before calling out. In the same transaction as the claim, create the Payment row as PROCESSING and lock the invoice. Enforce a partial unique index: at most one PROCESSING or SUCCEEDED payment per invoice. This is a second line of defense if a client uses two different keys for the same invoice.
  4. Call the provider with a derived provider-side idempotency key, for example pay:v1:{paymentId}. It is stable across our own retries and crash recovery, so even our own re-attempts can't double charge.
  5. Persist the outcome. Update the payment to SUCCEEDED or FAILED, mark the invoice PAID in the same transaction, and store the response against the key.
  6. Treat timeouts as a third outcome, UNKNOWN. A provider timeout or a crash after the call tells us nothing about whether the charge applied.
    • The payment stays PROCESSING/UNKNOWN, and the key stays claimed.
    • A reconciler resolves it by querying the provider with the same provider key, or via provider webhooks.
    • Clients that get 409 or an UNKNOWN payment poll GET /v1/payments/{id}. They never re-pay with a new key until the status is definitive.
  7. Validate the provider's responses (shape, amount, currency) before trusting them. They are untrusted input.

Client rules

Response Action
2xx with SUCCEEDED Done
2xx with FAILED Show the reason; a new attempt uses a new key
2xx with REQUIRES_ACTION Run the next action, then poll
Network error, timeout, 5xx, 429 Retry with the same key, with exponential backoff and jitter
409 REQUEST_IN_PROGRESS Wait for Retry-After, then retry with the same key
422 IDEMPOTENCY_KEY_REUSED Client bug; don't retry

Retention

Keep keys at least as long as the longest path that can redeliver a request. Our recommendation is 30 days minimum, and never shorter than the provider's dispute window or any dead-letter replay horizon. The Payment rows themselves are kept permanently, so the partial unique index on invoices still guards after the key expires. Expiry is a retention job and is never an on-read check.

Evolving safely

  • Add, don't change. New fields are optional on input and always present on output. Adding an enum value counts as a change, so the open-enum client rule is what makes it safe.
  • metadata maps on customers and invoices absorb ad-hoc fields without a schema change.
  • Send X-App-Version (or the User-Agent) from clients and log it. Before deprecating anything, you can then see which versions still use it. Deprecations are announced with Deprecation and Sunset headers.
  • Minimum supported version: an unsupported client gets 426 UPGRADE_REQUIRED with the standard error body, which gives a graceful "please update" path.
  • Publish an OpenAPI spec generated from these types, and run contract tests that replay recorded requests from old app versions on every release.

Open questions

  • Partial payments and refunds: I assumed one full-amount payment per invoice. Partial payments would change the "one active payment" index into a balance check.
  • Auth model: I assumed a per-account bearer token, with idempotency keys scoped to the account. Tell me if it's multi-tenant in a different way.
  • Currency: one currency per invoice is assumed.

Test run: an invoicing API for a fictional service. The model produced endpoints, types, one error format, cursor pagination and a retry-safe payment design with an atomic idempotency key. Design only; nothing was implemented or run, and some choices (for example returning 200 with a FAILED payment) are opinions.

它做什么

指导 REST 或 GraphQL 接口、模块边界和组件属性的设计。它从契约出发(实现之前先写类型和端点),再套用一组原则:海勒姆定律(每一个可观察的行为都会变成依赖)、单一版本规则、客户端可以据此分支的统一错误响应、只在系统边界做校验,以及宁可新增可选字段也不改动已有字段。它补充了 REST 模式(用名词表示资源、选对动词、部分更新、游标分页、过滤)和 TypeScript 模式(输入输出类型分开、用可辨识联合表示状态、品牌化的 ID、给旧客户端留余地的开放枚举)。对不能执行两次的操作,它还讲到了幂等性。

输出

一份用端点、类型、错误格式、分页和演进计划写成的设计,并列出假设与未决问题。

适合什么场景

设计新的对外或内部 API、评审现有 API,以及避免给无法立即升级的客户端(比如手机 App)造成破坏性变更。

说明与风险

低风险:纯指令文件,没有脚本。它产出的是设计文字和代码草图,不会调用任何服务。已用一个虚构的、支付可安全重试的开票 API 试用一次:给出了端点、类型、统一的错误格式、游标分页和幂等键设计。只是设计,没有实现也没有运行,其中有些取舍(例如银行卡被拒时返回 200 加一个 FAILED 的支付)属于观点,你可以不同意。作者 Addy Osmani,MIT 协议。

SKILL.md 原文包内共 2 个文件