本文由 AI 分析生成
建立時間: 2026-03-28 來源: https://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api
Summary
Vinay Sahni’s widely-cited guide to REST API design, written while building the Enchant API. Covers URL structure, versioning, filtering, pagination, authentication, caching, and error handling — prioritizing developer experience and pragmatic tradeoffs over strict REST orthodoxy. The central thesis: an API is a developer’s UI, so invest accordingly.
Vinay Sahni 設計 RESTful API 的實務指南,以開發者體驗為核心,涵蓋 URL 設計、版本管理、分頁、認證、快取與錯誤處理。核心觀點:API 是開發者的 UI,設計時應以使用者體驗為優先。
Key Points
- URL design: plural nouns for resources (
/tickets), nested for relations (/tickets/12/messages), query params for filters/sort/search - Versioning: version in URL (
/v1/) not headers — browser explorability matters - JSON-only: no XML except for enterprise requirements; always JSON input for POST/PUT/PATCH
- snake_case vs camelCase: snake_case is 20% easier to read (eye-tracking study) — use it despite JS conventions
- Pagination: use RFC 5988
Linkheaders, supplement withX-Total-Countcustom header - Authentication: token over HTTP Basic Auth for simple cases; OAuth2 Bearer for delegation; never redirect non-SSL to SSL (hard error instead)
- Caching: ETag (hash-based) and Last-Modified (timestamp-based) for HTTP cache validation
- Errors: always return structured JSON error payloads with
code,message,description— and field-level errors for validation failures - HTTP status codes: 201 + Location for created resources; 204 for no-content DELETE; 422 for validation errors; 429 for rate limiting
Insights
The article’s longevity (written ~2013, still widely referenced) reflects that most REST controversies are aesthetic, not technical. The positions Sahni takes — no HATEOAS, URL versioning, no response envelopes by default — are all minority positions in academic REST discussions but dominant in production APIs. Pragmatism won.
The ?embed=customer.name pattern for auto-loading related resources is elegant: it solves the N+1 problem at the API layer without breaking REST resource boundaries, and it’s explicit (caller-controlled) rather than implicit (always eager-loaded).
The SSL note — “throw a hard error on non-SSL, do not redirect” — is a security stance that’s often skipped in practice, creating a vulnerability where a misconfigured client leaks credentials in plaintext before being redirected.
Connections
Raw Excerpt
An API is a user interface for a developer - so put some effort into making it pleasant. Use RESTful URLs and actions. Use SSL everywhere, no exceptions. An API is only as good as its documentation - so have great documentation.