Skip to content

REST API Design: Constraints, Resources, Idempotency, Versioning ​

"The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components." — Roy T. Fielding، Architectural Styles and the Design of Network-based Software Architectures، فصل ۵، سال ۲۰۰۰

خلاصه (Summary): REST مجموعه‌ای از قیدهاست، نه یک سبک نوشتن URL؛ یک API روی HTTP فقط وقتی مزیت‌هایش (کش، retry بی‌خطر، ابزار عمومی، تکامل مستقل) را می‌گیرد که منبع، متد، کد وضعیت و هدرها را با همان معنایی به کار ببرد که HTTP تعریف کرده است. تمرکز (Focus): شش قید Fielding، منبع و طراحی URI، معنای متدها (safe و idempotent)، JSON Patch در برابر JSON Merge Patch، کد وضعیت دقیق، content negotiation، HATEOAS و مدل بلوغ Richardson، صفحه‌بندی cursor/keyset، فیلتر و مرتب‌سازی و sparse fieldsets، Problem Details طبق RFC 9457، قرارداد Idempotency-Key، هم‌روندی خوش‌بینانه با ETag/If-Match، هدرهای کش و RateLimit، endpointهای bulk، عملیات طولانی، خلاصهٔ نسخه‌بندی، OpenAPI 3.1 به روش contract-first، مبانی امنیت و راهنماهای سبک بزرگ؛ همراه با یک سرویس Go 1.22 روی net/http و یک API در Laravel 13. هدف یادگیری (Learning goal): بتوانید برای یک دامنه، API آن را روی کاغذ طراحی کنید (منبع‌ها، URIها، متدها، کدها، هدرها، صفحه‌ها، خطاها، هم‌روندی، idempotency)، آن را به شکل قرارداد OpenAPI 3.1 بنویسید، در Go و Laravel پیاده کنید و در بازبینی طراحی از تک‌تک کدهای وضعیت و هدرها دفاع کنید.

این فصل در گروه Networking & Protocols بعد از HTTP/1.1، HTTP/2، HTTP/3 (سیم و قاب‌ها) و پیش از GraphQL، gRPC و Protocol Buffers و نسخه‌بندی API می‌آید. مالک طراحی یک API روی HTTP است: منبع‌هایش، قراردادش و معنای HTTP که به آن تکیه می‌کند. موضوع همسایه‌ها را دوباره درس نمی‌دهد: قاب‌بندی و استفادهٔ دوباره از اتصال در HTTP evolution است؛ ذخیرهٔ کلید، TTL و بازیابی پس از crash برای idempotency در API Idempotency؛ SQL پشت صفحه‌بندی keyset در Pagination: Offset vs Keyset؛ ستون version و حلقهٔ retry در Optimistic vs Pessimistic Locking؛ token bucket در Rate Limiting؛ لایه‌های کش در Caching و CDN؛ سیاست deprecation و تغییر شکننده در API Versioning؛ انتخاب سبک ارتباط بین سرویس‌ها در Service Communication؛ نگاه DDD به منبع‌های REST در API Realization؛ و خود router در Go در net/http: Server, Client, 1.22 Routing.

نقشهٔ صفحه ​

دنبال چه هستیدبروید به
کل صفحه در چهار جدولهمه‌چیز در یک دقیقه
چرا REST قید است، نه URLچرا وجود دارد، از کجا آمده
client-server، stateless، cacheable، uniform interface، layered، code on demandقیدها
resource، collection، sub-resource، طراحی URI، تودرتوییمنبع‌ها و URIها
GET، HEAD، POST، PUT، PATCH، DELETE، OPTIONS؛ safe در برابر idempotentمتدها
JSON Patch در برابر JSON Merge Patchقالب‌های PATCH
دقیقاً کدام کد وضعیتکدهای وضعیت
Accept، Content-Type، media type، 406/415بازنمایی‌ها
HATEOAS، مدل بلوغ Richardsonابررسانه
صفحه‌بندی offset، cursor، keysetصفحه‌بندی
فیلتر، مرتب‌سازی، sparse fieldsetsطراحی query
بدنهٔ خطای RFC 9457Problem Details
Idempotency-Key روی POSTکلید idempotency
ETag، If-Match، 412، 428هم‌روندی خوش‌بینانه
Cache-Control، 304، Varyهدرهای کش
RateLimit، RateLimit-Policy، 429، Retry-Afterهدرهای rate limit
ساخت دسته‌ای، موفقیت جزئیendpointهای bulk
202 Accepted و منبع وضعیتعملیات طولانی
نسخه در URI، هدر یا media typeخلاصهٔ نسخه‌بندی
OpenAPI 3.1، contract-first، codegenOpenAPI
احراز هویت، scope، 401 در برابر 403 در برابر 404مبانی امنیت
Google AIP، Microsoft، Zalandoراهنماهای سبک
تنظیمات، دستور زبان هدرها، پیام‌های دقیقسازوکار
کدGo، Laravel
باگ‌های کلاسیک API و راه‌حل‌شانحل مسئله‌های کلاسیک
چه انتخاب کنیمانتخاب
از monolith تا سیستم توزیع‌شدهدر معماری
curl روی سرور Goآزمایشگاه
باورهای غلط، چکیده، آزمون، واژه‌هابدفهمی‌ها، چکیده، خودآزمایی، واژه‌نامه

همه‌چیز در یک دقیقه ​

قیدها (Constraints) طبق بخش 5.1 رسالهٔ Fielding. هر قید یک ویژگی می‌خرد و هزینه‌ای دارد.

قیدبه زبان سادهچه می‌خردچه هزینه‌ای دارد
Client-serverرابط کاربر و ذخیرهٔ داده دو برنامهٔ جدا هستندهر طرف جدا تکامل و مقیاس می‌گیردیک شبکه بینشان
Statelessهر درخواست هرچه برای فهمیدنش لازم است را با خود داردهر سروری می‌تواند جواب دهد؛ مقیاس، retry و بازیابی آسانداده‌های تکراری در هر درخواست (token، context)
Cacheableپاسخ‌ها می‌گویند قابل استفادهٔ دوباره هستند یا نهدرخواست کمتر، تأخیر کمترمدیریت کهنگی داده
Uniform interfaceبرای همهٔ منبع‌ها همان متدها، کدها و media typeهاکلاینت، proxy، کش و ابزار عمومیکم‌بازده‌تر از پروتکل اختصاصی
Layered systemهر جزء فقط لایهٔ کناری را می‌بیندCDN، gateway و load balancer می‌توانند وسط بنشینندhop و تأخیر اضافه
Code on demand (اختیاری)سرور ممکن است کدی بفرستد که کلاینت اجرا کندکلاینت سبک‌تردیدپذیری کمتر؛ به همین دلیل اختیاری است

متدها (Methods) طبق بخش 9 از RFC 9110.

متدSafeIdempotentCacheableکاربرد معمولموفقیت معمول
GETبلهبلهبلهخواندن یک منبع یا مجموعه200، 206، 304
HEADبلهبلهبلهفقط هدرها (اندازه، ETag، وجود)200
OPTIONSبلهبلهخیرقابلیت‌ها، CORS preflight204 یا 200
POSTخیرخیرفقط با freshness صریح، به‌ندرتساختن در مجموعه، اجرای یک فرایند201، 202، 200
PUTخیربلهخیرجایگزینی یا ساختن در URI معلوم200، 201، 204
PATCHخیرخیر (می‌شود چنینش کرد)خیرتغییر جزئی با سند patch200، 204
DELETEخیربلهخیرحذف204، 202، 200

کدهای وضعیتی که واقعاً لازم دارید.

کدوقتی استفاده کنید کههرگز برای
200 OKموفقیت با بدنهخطا با "ok": false در بدنه
201 Createdمنبع تازه ساخته شد؛ Location بفرستیدبه‌روزرسانی
202 Acceptedکار در صف است؛ URI وضعیت بفرستیدکاری که تمام شده
204 No Contentموفقیت بی‌بدنه (DELETE)پاسخی که بدنه دارد
304 Not ModifiedGET شرطی، نسخهٔ کلاینت هنوز معتبر استهر چیزی جز درخواست شرطی
400 Bad Requestنحو خراب، پارامتر query بد، هدر اجباری غایبشکست قاعدهٔ کسب‌وکار
401 Unauthorizedاعتبارنامه غایب یا نامعتبر؛ WWW-Authenticate بفرستیدکاربر شناخته‌شده‌ای که اجازه ندارد
403 Forbiddenکاربر شناخته شده، اجازه ندارد، و وجود منبع راز نیستپنهان کردن وجود منبع (404)
404 Not Foundچنین منبعی برای این فراخوان نیستمجموعهٔ خالی (آن 200 با [] است)
409 Conflictدرخواست با وضعیت فعلی تعارض دارد (گذار نامجاز، تکراری)ETag کهنه (آن 412 است)
412 Precondition FailedIf-Match یا If-Unmodified-Since نادرست درآمدپیش‌شرط غایب (428)
422 Unprocessable ContentJSON سالم اما ناقض قواعد اعتبارسنجیJSON خراب (400)
428 Precondition Requiredسرور نوشتن شرطی را الزامی می‌داندETag کهنه
429 Too Many Requestsبه سقف نرخ رسیده؛ Retry-After بفرستیدبار زیاد سرور (503)
503 Service Unavailableسرور زیر بار یا در تعمیر؛ Retry-Afterاشتباه کلاینت

جعبه‌ابزار هدرها.

هدرجهتکاربخش
LocationپاسخURI منبع ساخته‌شده یا ناظر وضعیتکدهای وضعیت
Accept / Content-Typeهر دوcontent negotiation و media typeبازنمایی‌ها
ETag / If-None-Matchهر دواعتبارسنجی ارزان، 304کش
If-Matchدرخواستجلوگیری از lost update، 412هم‌روندی
Idempotency-Keyدرخواستretry بی‌خطر POSTIdempotency
Linkپاسخصفحهٔ بعد، منبع‌های مرتبطصفحه‌بندی
Cache-Controlپاسخچه کسی، تا کی ذخیره کندکش
RateLimit-Policy / RateLimitپاسخسهمیه و مقدار باقی‌ماندهRate limit
Retry-Afterپاسخکی دوباره تلاش کنیم (429، 503، 202)Rate limit
Accept-Patchپاسخکدام قالب‌های patch پذیرفته می‌شوندPATCH
Null styleno constraintsClient-serverseparation ofconcerns: UI vsdata storageStatelesseach request carriesall it needs; noserver sessionvisibility, reliability,scalabilityCacheableresponses labelledcacheable or notefficiency, fewerround tripsUniform interface1 identificationof resources (URI)2 manipulation viarepresentations3 self-descriptivemessages (methods,media types, codes)4 hypermedia as theengine of app stateevolvability; costssome efficiencyCode on demand(optional)Layered systemeach layer sees onlythe next oneCDN, reverse proxy,gateway, loadbalancer in betweenEach step adds one constraint and the property it buysFielding 2000, chapter 5.1: REST derived from the null style

این تصویر روش استخراج Fielding است: از سبکی بدون هیچ قیدی شروع می‌کند و یکی‌یکی قید اضافه می‌کند. پلهٔ uniform interface از همه بلندتر است چون خودش چهار قید است، و code on demand با خط‌چین آمده چون تنها قید اختیاری است.

چرا وجود دارد ​

پیش از آنکه REST اسم داشته باشد، وب به میلیون‌ها سرور رسیده بود که هرگز کلاینت‌هایشان را ندیده بودند. رسالهٔ Fielding دلیلش را توضیح می‌دهد: هر درخواست خودکفاست، هر پاسخ می‌گوید قابل کش است یا نه، و همهٔ اجزا یک واژگان کوچک مشترک دارند؛ پس کش، proxy و مرورگر بدون شناخت برنامه کار می‌کنند. APIای که فراخوانی‌های رویه‌ای را از تونل POST /api رد می‌کند همهٔ این‌ها را دور می‌ریزد: هیچ کشی نگهش نمی‌دارد، هیچ proxyای retryاش نمی‌کند و هیچ کتابخانهٔ کلاینتی نمی‌فهمد چه چیزی شکست خورد.

RPC تونل‌شده روی HTTPHTTP منبع‌محور (شبه‌REST، سطح ۲ به بالا)
یک endpoint، فعل در بدنهیک URI برای هر منبع، فعل همان متد HTTP
همیشه 200، پرچم خطا در بدنهکد وضعیت به همهٔ واسطه‌ها می‌گوید چه شد
هیچ چیز قابل کش نیستGET قابل کش است، ETag به 304 می‌رسد
retry برای همه‌چیز ناامنGET، PUT، DELETE ذاتاً قابل retry؛ POST با کلید
کلاینت برای هر فراخوانی باید مستند بخواندکلاینت عمومی، codegen از OpenAPI، curl
آزادی برای مدل کردن هر چیز به‌صورت فراخوانیباید اسم را پیدا کرد (cancellation، نه cancelOrder)
کمترین تلاش در روز اولکمی طراحی در ابتدا، بسیار کمتر بعداً

تصویری از زندگی روزمره. یک کتابخانهٔ عمومی. هر کتاب شمارهٔ قفسه دارد (URI). چند فرم استاندارد هست که همه استفاده می‌کنند: امانت، بازگرداندن، رزرو (متدها). میز امانت با چند مُهر کوتاه جواب می‌دهد که همه می‌فهمند: «امانت است»، «چنین کتابی نداریم»، «فردا بیایید» (کدهای وضعیت). کارت فهرست یک علامت «آخرین به‌روزرسانی» دارد تا بدانید کپی شما هنوز معتبر است (ETag)، و برگهٔ رزرو شماره دارد تا اگر دو بار تحویلش دادید دو نسخه رزرو نشود (Idempotency-Key). شعبه‌های کتابخانه می‌توانند از روی نسخهٔ خودشان از فهرست جواب دهند و لازم نیست به شعبهٔ مرکزی زنگ بزنند (layered system و کش). این تمثیل در سراسر صفحه برمی‌گردد.

سه بدفهمی رایج، از همین اول ​

  1. «REST یعنی JSON روی HTTP با URLهای قشنگ.» REST یک سبک معماری با شش قید است؛ JSON و URL زیبا نه لازم‌اند و نه کافی. بیشتر APIهای JSON در سطح ۲ مدل Richardson هستند که مفید است اما آن چیزی نیست که Fielding اسمش را REST می‌گذارد (ابررسانه).
  2. «POST برای ساختن، PUT برای به‌روزرسانی.» PUT یعنی «این بازنمایی را در همین URI ذخیره کن» و idempotent است؛ می‌تواند بسازد. POST یعنی «این را طبق قواعد خودت پردازش کن» و وقتی سرور URI را انتخاب می‌کند ابزار درست است (متدها).
  3. «Idempotent یعنی هر بار همان پاسخ.» یعنی همان اثر موردنظر روی سرور. DELETE دوم ممکن است به‌جای 204، 404 یا 410 بگیرد و باز هم idempotent باشد (متدها).

از کجا آمده ​

سالرویدادمنبع
1996–1999HTTP/1.0 (RFC 1945) و HTTP/1.1 (RFC 2068، سپس RFC 2616 در 1999)؛ Fielding از نویسندگان هر دوRFC 9110 این تبار را فهرست می‌کند
2000رسالهٔ دکترای Fielding، فصل ۵ «Representational State Transfer (REST)»ics.uci.edu
2008Fielding، نوشتهٔ «REST APIs must be hypertext-driven»roy.gbiv.com
2008سخنرانی Leonard Richardson در QCon؛ Fowler در 18 March 2010 آن را با نام Richardson Maturity Model می‌نویسدmartinfowler.com
March 2010RFC 5789 متد PATCH را تعریف می‌کندrfc-editor.org
April 2012RFC 6585: کدهای 428، 429، 431، 511rfc-editor.org
April 2013RFC 6902 یعنی JSON Patchrfc-editor.org
October 2014RFC 7396 یعنی JSON Merge Patch (جایگزین RFC 7386)rfc-editor.org
March 2016RFC 7807 یعنی Problem Details for HTTP APIsrfc-editor.org
26 July 2017انتشار OpenAPI 3.0.0 توسط OpenAPI Initiative (جانشین Swagger 2.0)spec.openapis.org
October 2017RFC 8288 یعنی Web Linking (هدر Link)rfc-editor.org
2010s–2020sانتشار عمومی Google AIP، Microsoft REST API Guidelines و Zalando RESTful API Guidelines؛ changelog راهنمای Azure تا 2024 ادامه داردهر راهنما
15 February 2021OpenAPI 3.1.0: شیء Schema ابرمجموعهٔ JSON Schema 2020-12 می‌شودspec.openapis.org
June 2022RFC 9110 (HTTP Semantics) و RFC 9111 (HTTP Caching) جای RFC 7230 تا 7235 را می‌گیرندrfc-editor.org
July 2023RFC 9457 جایگزین RFC 7807 می‌شودrfc-editor.org
2024-02-06Go 1.22: الگوهای متد و wildcard در net/http.ServeMuxgo.dev
2026پیش‌نویس‌های IETF HTTPAPI: هدر Idempotency-Key (نسخهٔ 09) و RateLimit header fields (نسخهٔ 12)، هنوز Internet-Draftdatatracker.ietf.org

دو نکته برای بقیهٔ صفحه مهم است. اول، رساله معماری وب را پس از وقوع توصیف می‌کند و هرگز مشخصه‌ای برای APIهای JSON نبوده است. دوم، تقریباً هر قاعده در راهنماهای سبک امروز (Google AIP، Microsoft، Zalando) زیرمجموعه‌ای عمل‌گرایانه از معنای RFC 9110 است، به‌علاوهٔ قراردادهایی برای چیزهایی که RFCها باز گذاشته‌اند (صفحه‌بندی، فیلتر، خطا، کارهای طولانی).

فهرست مفاهیم ​

هر بلوک یک ترتیب ثابت دارد: به زبان ساده، باور غلط رایج، تعریف، جریان درخواست، سناریوهای واقعی، رفتار محصولات و راهنماها، و راه درست.

قیدهای Fielding و بی‌حالتی (Statelessness) حیاتی ​

به زبان ساده: REST همان چیزی است که وقتی یک کلاینت و یک سرور برمی‌دارید و قاعده اضافه می‌کنید به دست می‌آید: جدایشان نگه دارید، حالت نشست (session) سمت سرور را ممنوع کنید، پاسخ‌ها را قابل کش یا غیرقابل کش برچسب بزنید، همهٔ منبع‌ها را به یک رابط واحد وادار کنید، اجازهٔ لایه‌های میانی بدهید و در صورت تمایل بگذارید سرور کد بفرستد.

بدفهمی رایج: «Stateless یعنی سرور پایگاه داده ندارد.» بی‌حالتی دربارهٔ حالت نشست (Application State) بین درخواست‌هاست، نه حالت منبع (Resource State). سفارش، کاربر و سبد خرید در پایگاه داده حالت منبع‌اند و مشکلی ندارند. آنچه ممنوع است این است که سرور در حافظه‌اش «یادش بماند این اتصال کدام صفحه بود»، به‌طوری که درخواست دوم فقط روی همان سروری کار کند که درخواست اول را دیده.

تعریف: Fielding: "each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client." رابط یکنواخت (Uniform Interface) خودش چهار قید است: "identification of resources; manipulation of resources through representations; self-descriptive messages; and, hypermedia as the engine of application state." و code on demand تنها قید اختیاری مجموعه است.

text
     Client                  Load balancer            api-1           api-2
1    GET /orders?cursor=c1   ->                       answers page 2
     Authorization: Bearer t
2    GET /orders?cursor=c2   ->                                       answers page 3
     (cursor and token travel with every request; api-2 never saw request 1)
3    api-1 crashes           ->  no session lost, the client just retries the GET

سناریوی واقعی: گروه autoscaling در یک حراج ده نمونهٔ تازه اضافه می‌کند و هیچ‌کدام sticky session لازم ندارند؛ یک deploy وسط ترافیک podها را می‌کشد و کلاینت‌ها بی‌صدا GET را تکرار می‌کنند؛ یک CDN درخواست GET /products/42 را از لبه جواب می‌دهد بدون پرسیدن از origin؛ یک API gateway احراز هویت و rate limit را اضافه می‌کند بی‌آنکه سرویس تغییر کند (layered system).

چه چیزی پشتیبانی‌اش می‌کند یا می‌شکندش:

روشقیدی که حمایت می‌کند یا می‌شکندنمونهٔ محصول
Bearer token یا cookie امضاشده در هر درخواستحامی statelessaccess token در OAuth 2.0، توکن Laravel Sanctum
نشست سمت سرور در حافظهٔ پروسهشکستن stateless (sticky session لازم می‌شود)نشست فایلی پیش‌فرض PHP روی یک ماشین
نشست در Redis با کلید cookieحالت مشترک؛ هنوز stateless به معنای REST نیست اما مقیاس می‌گیردSESSION_DRIVER=redis در Laravel
Cache-Control و ETag روی GETحامی cacheableproxy_cache در NGINX، Cloudflare، Fastly
POST /api برای خواندنشکستن cacheable و uniform interfaceJSON-RPC، SOAP
CDN، reverse proxy، API gatewayLayered systemCloudflare، AWS CloudFront، Envoy، Kong
JavaScriptی که به مرورگر فرستاده می‌شودCode on demandهر برنامهٔ تک‌صفحه‌ای

راه درست: هویت را در token یا cookie بفرستید، موقعیت را در cursor، و حالت گردش کار را در منبع‌ها (/carts/9، /checkouts/3) نگه دارید نه در حافظهٔ سرور؛ برای سرویس‌های بی‌حالت Scaling Strategies و برای سمت مرورگر Web Sessions & Cookies را ببینید.

منبع، مجموعه، زیرمنبع و طراحی URI حیاتی ​

به زبان ساده: منبع (Resource) هر چیزی است که ارزش نام‌گذاری دارد: یک سفارش، یک مشتری، مجموعه‌ای از سفارش‌ها، «نرخ ارز امروز»، حتی یک لغو. هر کدام یک URI می‌گیرد. مجموعه‌ها (Collection) اسم جمع‌اند؛ اعضا زیرشان می‌نشینند؛ چیزهایی که فقط داخل یک والد معنا دارند زیرمنبع (Sub-resource) هستند.

بدفهمی رایج: «هر جدول پایگاه داده یک منبع است و هر منبع یک جدول.» منبع‌ها اسم‌های API هستند که برای کلاینت انتخاب می‌شوند. /orders/7/cancellation یا /payouts/3/approval ممکن است اصلاً جدول نباشند، و join سه جدول ممکن است فقط یک منبع باشد. به قول Fielding: "Any information that can be named can be a resource."

تعریف: منبع هدف یک URI است؛ منبع مجموعه اعضایش را فهرست می‌کند و عضو تازه می‌سازد (/orders)؛ منبع عضو یکی از آن‌هاست (/orders/ord_01h...)؛ زیرمنبع فقط از راه والدش در دسترس است (/orders/{id}/items/{n})؛ زیرمنبع singleton برای هر والد دقیقاً یک نمونه دارد (/users/{id}/settings). طراحی URI (URI Design) خوب یعنی اسم جمع با حروف کوچک، بدون فعل، بدون پسوند فایل، بدون اسلش انتهایی، شناسه‌های پایدار و مات، و حداکثر یک یا دو سطح تودرتویی.

text
     Client                                              Orders API
1    GET  /orders?status=paid                       ->   200 collection page
2    POST /orders            {customer, total}      ->   201 Location: /orders/ord_7
3    GET  /orders/ord_7                             ->   200 item, ETag "ord_7-v1"
4    GET  /orders/ord_7/items                       ->   200 sub-collection
5    POST /orders/ord_7/cancellation                ->   200 the state change is a resource
6    GET  /customers/c_42/orders                    ->   200 the same orders, filtered view

سناریوی واقعی: فروشگاهی که /products، /carts/{id}/lines و /orders/{id}/shipments را عرضه می‌کند؛ بانکی که /accounts/{id}/transactions را بدون PUT و DELETE ارائه می‌دهد (فقط افزودنی)؛ کار مدیریتی «تأیید تسویه» به شکل POST /payouts/{id}/approval؛ API فایلی که /files/{id}/content همان بایت‌هاست و /files/{id} فراداده.

راهنماها چطور نام‌گذاری می‌کنند:

قاعدهGoogle AIP-122راهنمای Microsoft AzureZalando
نام مجموعه‌هاجمع، انگلیسی آمریکایی کوتاه ("Collection identifiers must be concise American English terms")اسم جمع"MUST pluralize resource names"
حالت حروف در مسیر"Collection identifiers must be in camelCase"، مثل publishers/123/books"DO use kebab-casing (preferred) or camel-casing for URL path segments""MUST use kebab-case for path segments"
پارامترهای query و فیلدهای JSONsnake_case در proto، camelCase در JSON"DO use camel case for query parameter names" و برای فیلدهای JSON"MUST use snake_case (never camelCase) for query parameters"
کارهایی که CRUD نیستندcustom method با دونقطه: POST /v1/{name=publishers/*/books/*}:archive (AIP-136)الگوی .../collection/id:action برای actionهاتا جای ممکن به شکل زیرمنبع
تودرتویینام منبع زنجیرهٔ والدها را رمز می‌کندبخش‌های collection، id و action"MUST identify resources and sub-resources via path segments"

راه درست: اول اسم‌ها را پیدا کنید (orders، lines، payments، refunds، cancellations)؛ شناسهٔ عمومی مات (ord_01hx... از نوع ULID یا UUID) بدهید نه کلید auto-increment؛ تودرتویی را به یک سطح محدود کنید و جست‌وجوی تخت هم بدهید (/orders/{id} کار کند حتی اگر /customers/{c}/orders/{id} هم باشد)؛ در Laravel، Route::apiResource('orders', ...) پنج مسیر مجموعه/عضو را می‌دهد و ->shallow() مسیرهای تودرتو را کوتاه نگه می‌دارد؛ در Go 1.22، mux.HandleFunc("GET /orders/{id}", h) و r.PathValue("id").

متدها و معنایشان: safe و idempotent حیاتی ​

به زبان ساده: متد به همه در مسیر می‌گوید این چه نوع کاری است. متدهای امن (Safe) فقط می‌خوانند. متدهای idempotent را می‌شود تکرار کرد و اثرشان مثل یک بار است. کش‌ها، مرورگرها، proxyها و کتابخانه‌های retry بر اساس همین دو ویژگی عمل می‌کنند بی‌آنکه API شما را بشناسند.

بدفهمی رایج: «GET هرگز نباید چیزی بنویسد.» RFC 9110 اجازه می‌دهد GET لاگ کند، بشمارد یا کش را گرم کند؛ آنچه آن را امن می‌کند این است که "the client does not request, and does not expect, any state change on the origin server". GETی که کارت را شارژ می‌کند یا ردیفی را پاک می‌کند باگ است؛ GETی که شمارندهٔ بازدید را بالا می‌برد قابل قبول اما غافلگیرکننده است.

تعریف: بخش 9.2.1 از RFC 9110: متدها امن‌اند "if their defined semantics are essentially read-only"؛ "the GET, HEAD, OPTIONS, and TRACE methods are defined to be safe." بخش 9.2.2: متدی idempotent است "if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request. Of the request methods defined by this specification, PUT, DELETE, and safe request methods are idempotent." RFC 5789: "PATCH is neither safe nor idempotent". POST "requests that the target resource process the representation enclosed in the request according to the resource's own specific semantics."

text
     Client                         API                          Effect
1    PUT /users/7/avatar  (bytes)   -> 201 Created               avatar stored
2    (timeout, retry) PUT again     -> 200 OK                    same avatar, same state
3    DELETE /orders/ord_9           -> 204                       deleted
4    (retry) DELETE /orders/ord_9   -> 410 Gone                  still deleted: idempotent
5    POST /payments {amount: 50}    -> timeout
6    (retry) POST /payments         -> 201                       second payment! not idempotent

سناریوی واقعی: کلاینت موبایل روی شبکهٔ ناپایدار PUT تنظیمات پروفایل را بی‌خطر تکرار می‌کند؛ یک reverse proxy پس از قطع اتصال، GET را روی upstream دیگری تکرار می‌کند (در NGINX با proxy_next_upstream: "normally, requests with a non-idempotent method (POST, LOCK, PATCH) are not passed to the next server" پس از ارسال؛ retry در Envoy برای هر route تنظیم می‌شود)؛ مرورگر پس از دکمهٔ back دوباره GET می‌فرستد اما پیش از فرستادن دوبارهٔ فرم POST هشدار می‌دهد؛ POST پرداخت بدون کلید idempotency پس از timeout در gateway دو بار پول کم می‌کند.

هر متد برای چیست:

متدبدنهٔ درخواستبدنهٔ پاسخچه کسی URI را انتخاب می‌کندبه‌طور پیش‌فرض retry درنکته
GETمعنایی ندارد (نفرستید)بازنمایی—مرورگر، proxy، Envoy، NGINXقابل کش
HEADنداردندارد، همان هدرهای GET—مثل GETدر ServeMux زبان Go الگوی GET با HEAD هم جور می‌شود
OPTIONSبه‌ندرتقابلیت‌ها (Allow)——CORS preflight؛ ببینید CORS
POSTداردنتیجه یا منبع ساخته‌شدهسرورهیچ‌کس (ناامن)Idempotency-Key اضافه کنید
PUTبازنمایی کاملاختیاریکلاینتامن برای retryفیلد غایب یعنی «حذف»، نه «نگه‌داری»
PATCHسند patchمعمولاً وضعیت تازه—نه به‌طور پیش‌فرضبا If-Match یا فقط مقداردهی، idempotent می‌شود
DELETEنبایدمعمولاً ندارد—امن برای retry204 و بعد 404/410

راه درست: متد را بر اساس معنا انتخاب کنید نه عادت: URI به انتخاب کلاینت و جایگزینی کامل یعنی PUT، شناسه به انتخاب سرور یعنی POST به مجموعه، تغییر جزئی یعنی PATCH، یک عمل یعنی POST به یک زیرمنبع؛ POST را با Idempotency-Key قابل retry کنید و PATCH را با If-Match؛ به متد نادرست با 405 و هدر Allow جواب دهید (mux نسخهٔ 1.22 در Go خودش این کار را می‌کند).

قالب‌های PATCH: JSON Merge Patch در برابر JSON Patch مهم ​

به زبان ساده: PATCH توصیفی از تغییرات می‌فرستد و Content-Type می‌گوید آن توصیف به چه زبانی نوشته شده. Merge Patch یعنی «این یک شیء جزئی است، ادغامش کن؛ null یعنی حذف». JSON Patch یعنی «این فهرستی از عملیات است: test، replace، add، remove، move، copy».

بدفهمی رایج: «PATCH با application/json و یک شیء جزئی استاندارد است.» این قراردادی رایج است، اما قالب استاندارد شیء جزئی application/merge-patch+json است (RFC 7396). با application/json ساده هیچ معنای توافق‌شده‌ای برای null، آرایه‌ها یا فیلدهای غایب وجود ندارد.

تعریف: RFC 5789: "The PATCH method requests that a set of changes described in the request entity be applied to the resource identified by the Request-URI." در merge patch طبق RFC 7396، عضوهای موجود جایگزین می‌شوند، null عضو را حذف می‌کند و آرایه‌ها کامل جایگزین می‌شوند. در JSON Patch طبق RFC 6902، آرایه‌ای از عملیات داریم که هر کدام دقیقاً یک "op" (add، remove، replace، move، copy، test) و یک JSON Pointer در "path" دارد؛ سند به‌صورت اتمی اعمال می‌شود، پس شکست یک test همه‌چیز را لغو می‌کند.

text
     Merge Patch (application/merge-patch+json)      JSON Patch (application/json-patch+json)
1    {"status": "paid", "note": null}                 [{"op":"test","path":"/status","value":"pending"},
2                                                      {"op":"replace","path":"/status","value":"paid"},
3                                                      {"op":"remove","path":"/note"}]
4    note removed, status set                         same result, but only if status was still pending
5    cannot say "append to array" or "only if"        can: test is a per-field precondition

سناریوی واقعی: صفحهٔ تنظیمات که فقط فیلدهای تغییرکرده را ذخیره می‌کند (merge patch)؛ ویرایشگر مشترکی که باید فیلدی را فقط وقتی عوض کند که هنوز مقدار قبلی را دارد (test در JSON Patch)؛ افزودن یک عضو به آرایه‌ای بزرگ بدون فرستادن دوبارهٔ کل آن (add روی /tags/-)؛ Kubernetes که هر دو را به‌علاوهٔ strategic merge patch خودش برای فهرست‌ها می‌پذیرد.

قالبMedia typeحذف فیلدویرایش آرایهشرط برای هر فیلدچه کسی استفاده می‌کند
JSON Merge Patchapplication/merge-patch+jsonبله، با nullجایگزینی کل آرایهخیرراهنمای Microsoft Azure ("DO create and update resources using PATCH [RFC 5789] with JSON Merge Patch")، برنامه‌های Laravel طبق قرارداد
JSON Patchapplication/json-patch+jsonremoveadd، remove، move با اندیسtestAPI در Kubernetes ("JSON Patch, as defined in RFC6902")
Strategic merge patchapplication/strategic-merge-patch+jsonبا دستورهاادغام فهرست با کلیدخیرفقط Kubernetes
Field maskفیلد update_mask (AIP-134)با فهرست کردنش بدون مقدارجایگزینیخیرAPIهای Google (google.protobuf.FieldMask)
JSON جزئی سادهapplication/jsonتعریف‌نشدهتعریف‌نشدهخیربسیاری از APIها، مبهم

راه درست: به‌طور پیش‌فرض application/merge-patch+json بپذیرید، وقتی کلاینت‌ها test یا عملیات آرایه لازم دارند application/json-patch+json را هم اضافه کنید، هر دو را با Accept-Patch اعلام کنید، برای بقیه 415 بدهید و همچنان If-Match را الزامی کنید. Laravel بدنه‌های +json را parse می‌کند چون isJson() دنبال /json یا +json می‌گردد؛ قواعد sometimes و nullable معنای merge patch را می‌دهند. مثال Go هر دو قالب را در applyMerge و applyJSONPatch پیاده کرده است.

کدهای وضعیت با کاربرد دقیق حیاتی ​

به زبان ساده: کد وضعیت (Status Code) تنها بخش پاسخ است که همهٔ واسطه‌ها می‌فهمند. کدی را انتخاب کنید که به یک کلاینت عمومی بگوید قدم بعد چیست: از بدنه استفاده کن، دنبال پیوند برو، درخواست را درست کن، احراز هویت کن، صبر کن یا دوباره تلاش کن.

بدفهمی رایج: «400 برای همهٔ خطاهای کلاینت کافی است، بدنه توضیح می‌دهد.» کتابخانهٔ کلاینت، API gateway، سیاست retry و داشبورد مانیتورینگ همه بر اساس کد تصمیم می‌گیرند. 409 و 412 و 422 و 429 به چهار واکنش درست متفاوت می‌رسند (حل تعارض، خواندن دوباره، اصلاح ورودی، صبر).

تعریف: بخش 15 از RFC 9110 کدها را در 1xx اطلاعاتی، 2xx موفق، 3xx تغییر مسیر، 4xx خطای کلاینت و 5xx خطای سرور دسته‌بندی می‌کند، و RFC 6585 کدهای 428 و 429 را اضافه می‌کند. معناهای دقیقی که در این صفحه به کار می‌روند: 202 یعنی "the request has been accepted for processing, but the processing has not been completed"؛ 303 یعنی "the server is redirecting the user agent to a different resource ... intended to provide an indirect response to the original request"؛ 412 یعنی "one or more conditions given in the request header fields evaluated to false"؛ 422 یعنی سرور "understands the content type of the request content ... and the syntax of the request content is correct, but it was unable to process the contained instructions"؛ 428 یعنی "the origin server requires the request to be conditional"؛ 429 یعنی "the user has sent too many requests in a given amount of time".

text
     Request                                             Code  Client's next move
1    POST /orders  (Content-Type: text/plain)            415   send JSON
2    POST /orders  {"customer": ""}                      422   fix field customer
3    POST /orders  no Idempotency-Key                    400   add the header
4    PATCH /orders/7 no If-Match                         428   GET, then send If-Match
5    PATCH /orders/7 If-Match: "7-v1" (now v2)           412   GET again, reapply, retry
6    PATCH /orders/7 {"status":"pending"} from shipped   409   show the user; do not retry
7    GET /orders (101st request this minute)             429   wait Retry-After seconds
8    GET /orders (database down)                         503   retry with backoff

سناریوی واقعی: کلاینت موبایلی که روی 5xx دوباره تلاش می‌کند ولی روی 4xx نه؛ API gatewayای (Kong، AWS API Gateway) که 502/504 از upstream را به هشدار تبدیل می‌کند؛ CDNای که 404 را کوتاه‌مدت و 200 را طولانی‌تر کش می‌کند؛ کلاینت پرداختی که باید 409 «در حال اجرا» را از 422 «کلید تکراری» تشخیص دهد.

جدول کامل با کاربرد دقیق:

کدنام (RFC 9110)کاربرد دقیقهدرهاRetry؟
200OKموفقیت با بازنماییETag—
201Createdمنبع تازه؛ بدنه خود آن استLocation، ETag—
202Acceptedدر صف؛ بدنه منبع وضعیت استLocation، Retry-AfterPoll
204No Contentموفقیت بی‌بدنهETag اختیاری—
206Partial Contentپاسخ به درخواست RangeContent-Range—
301Moved PermanentlyURI برای همیشه جابه‌جا شد؛ کلاینت ممکن است POST را GET کندLocationدنبال کن
302Foundموقت؛ همان ابهام در تغییر متدLocationدنبال کن
303See Otherنتیجه جای دیگری است؛ همیشه با GET بخوانLocationبا GET دنبال کن
304Not ModifiedGET شرطی جور درآمدETag، Cache-Controlاز کش استفاده کن
307Temporary Redirectموقت، متد و بدنه حفظ می‌شوندLocationبا همان متد دنبال کن
308Permanent Redirectدائمی، متد و بدنه حفظ می‌شوندLocationبا همان متد دنبال کن
400Bad Requestمشکل نحو، پارامتر query، هدر—نه، اصلاح کن
401Unauthorizedاعتبارنامهٔ غایب یا نامعتبرWWW-Authenticateپس از احراز هویت
403Forbiddenفراخوان شناخته‌شده، اجازه ندارد—نه
404Not Foundناشناخته، یا از این فراخوان پنهان—نه
405Method Not Allowedمسیر هست، متد نیستAllow (الزامی)نه
406Not Acceptableهیچ نوعی از Accept را نمی‌تواند بسازد—نه
409Conflictتعارض وضعیت، تکراری، کلید idempotency در حال اجرا—پس از حل تعارض
410Goneوجود داشت، عمداً حذف شد—نه
412Precondition FailedIf-Match نادرست—پس از خواندن دوباره
415Unsupported Media Typeقالب بدنه پذیرفته نیستAccept یا Accept-Patchنه، اصلاح کن
422Unprocessable Contentاعتبارسنجی معنایی شکست خورد—نه، اصلاح کن
428Precondition Requiredدرخواست شرطی الزامی است—پس از افزودن If-Match
429Too Many Requestsمحدودیت نرخRetry-After، RateLimitپس از صبر
500Internal Server Errorباگ پیش‌بینی‌نشده—شاید، فقط idempotent
502Bad Gatewayproxy از upstream پاسخ بد گرفت—بله، فقط idempotent
503Service Unavailableبار زیاد، تعمیرRetry-Afterبله، پس از صبر
504Gateway Timeoutupstream به‌موقع جواب نداد—فقط idempotent؛ کار شاید انجام شده باشد

راه درست: این جدول را برای API خودتان، برای هر operation، در قرارداد OpenAPI بنویسید؛ هرگز 200 با پرچم خطا برنگردانید؛ 5xx را برای خطای خودتان نگه دارید تا نرخ 5xx یک SLI صادق باشد (SLO)؛ برای redirect درخواست‌های غیر GET از 307/308 استفاده کنید نه 301/302.

بازنمایی و content negotiation مهم ​

به زبان ساده: کلاینت هیچ‌وقت «خودِ سفارش» را نمی‌گیرد، بلکه بازنمایی (Representation) آن را می‌گیرد: JSON، CSV، PDF، یا شکل قدیمی‌تر JSON. کلاینت با Accept می‌گوید چه چیزی را می‌تواند بخواند؛ سرور با Content-Type می‌گوید چه فرستاد.

بدفهمی رایج: «Content-Type روی درخواست GET مهم است.» روی درخواست، Content-Type بدنهٔ درخواست را توصیف می‌کند و GET بدنه ندارد. آنچه کلاینت می‌خواهد با Accept گفته می‌شود. قاطی کردن این دو روی نوشتن 415 و روی خواندن قالب اشتباه می‌دهد.

تعریف: بازنمایی عکسی از حالت منبع در یک media type است (application/json، application/problem+json، text/csv، نوع‌های vendor مثل application/vnd.api+json). Content negotiation (بخش 12 از RFC 9110) پیش‌دستانه است: سرور با Accept، Accept-Language و Accept-Encoding انتخاب می‌کند و باید Vary را با فهرست هدرهایی که استفاده کرد بفرستد تا کش‌ها گونه‌ها را از هم جدا نگه دارند. نبودن نوع قابل قبول به 406 می‌رسد؛ بدنهٔ درخواست ناخوانا به 415.

text
     Client                                            API / CDN
1    GET /orders/7/invoice  Accept: application/pdf    -> 200 Content-Type: application/pdf, Vary: Accept
2    GET /orders/7/invoice  Accept: text/csv           -> 200 Content-Type: text/csv (separate cache entry)
3    GET /orders/7/invoice  Accept: image/png          -> 406 Not Acceptable
4    POST /orders  Content-Type: application/xml       -> 415 Unsupported Media Type, Accept: application/json

سناریوی واقعی: endpoint خروجی که CSV و JSON Lines می‌دهد؛ خطا به شکل application/problem+json در حالی که موفقیت‌ها application/json هستند؛ سرور JSON:API که با application/vnd.api+json جواب می‌دهد (کلاس JsonApiResource در Laravel 13 "sets the Content-Type header to application/vnd.api+json")؛ API به سبک Zalando که با media type نسخه‌بندی می‌کند.

محصولابزار negotiationپیش‌فرض
Go net/httpچیزی داخلی نیست؛ Accept را خودتان parse کنید، mime.ParseMediaType برای Content-Typeاگر تنظیم نکنید http.DetectContentType حدس می‌زند
Laravel 13$request->expectsJson()، wantsJson()، accepts()، prefers()؛ رندر خطا JSON یا HTML را "based on the Accept header" انتخاب می‌کندبرای api/* وقتی کلاینت JSON بپذیرد، JSON
NGINX / Cloudflareاگر روی Accept مذاکره می‌کنید کلید کش باید آن را شامل شودکلید کش فقط URL است مگر تنظیم شود
JSON:APIapplication/vnd.api+jsonmedia type الزامی

راه درست: به‌طور پیش‌فرض یک media type برای JSON داشته باشید؛ فقط جایی مذاکره کنید که کلاینت‌ها واقعاً چند قالب لازم دارند؛ همیشه در آن حالت Vary: Accept بفرستید؛ روی نوشتن Content-Type را بررسی کنید (Go: mime.ParseMediaType؛ Laravel: isJson()) و با 415 بگویید چه چیزی می‌پذیرید.

HATEOAS و مدل بلوغ Richardson مهم ​

به زبان ساده: HATEOAS (ابررسانه به‌عنوان موتور حالت برنامه) یعنی کلاینت قدم بعدی را از پیوندهای داخل پاسخ کشف کند، مثل آدمی که در یک وب‌سایت کلیک می‌کند، نه اینکه URLها را از روی مستندات بسازد. مدل بلوغ Richardson (Richardson Maturity Model) نردبانی چهارپله‌ای است که نشان می‌دهد یک API روی HTTP چقدر به این ایده نزدیک شده.

بدفهمی رایج: «فقط سطح ۳ REST درست است، پس APIهای سطح ۲ غلط‌اند.» Fielding واقعاً می‌گوید APIای که با hypertext هدایت نشود "cannot be RESTful and cannot be a REST API. Period." اما Fowler صریح است که این مدل "a tool to help us learn about the concepts and not something that should be used in some kind of assessment mechanism" است. سطح ۲ همین حالا کش، retry بی‌خطر و ابزار می‌دهد؛ سطح ۳ وقتی می‌ارزد که کلاینت‌ها زیاد و عمرشان طولانی باشد، یا سرور بخواهد URIها و گردش کار را بدون انتشار نسخهٔ تازهٔ کلاینت عوض کند.

تعریف: مدل (از Leonard Richardson، نوشتهٔ Fowler در 18 March 2010): سطح ۰ یک endpoint و یک متد، HTTP به‌عنوان تونل ("the swamp of POX")؛ سطح ۱ منبع‌های جدا؛ سطح ۲ فعل‌ها و کدهای وضعیت HTTP طبق تعریف؛ سطح ۳ کنترل‌های ابررسانه‌ای. Fielding در 2008: "A REST API should be entered with no prior knowledge beyond the initial URI (bookmark) and set of standardized media types".

text
     Level 0  POST /api {"action":"cancelOrder","id":7}          -> 200 {"ok":false}
     Level 1  POST /orders/7 {"action":"cancel"}                  -> 200
     Level 2  POST /orders/7/cancellation                         -> 200, or 409 if shipped
     Level 3  GET /orders/7 -> {"status":"paid","links":{"cancel":"/orders/7/cancellation"}}
              the client shows a Cancel button only when the link is present
Level 0: the swamp of POXPOST /api {"action":"getOrder","id":7}; always 200Level 1: resourcesPOST /orders/7 {"action":"cancel"}; one URI per thingLevel 2: HTTP verbs and status codesGET /orders/7, PATCH, DELETE; 201, 404, 409, 412Level 3: hypermedia controls"links": {"cancel": "/orders/7/cancellation"}Fielding: required for RESTrare in JSON APIs; JSON:API,HAL, Siren, PayPal linksMost public APIs stop here:caches, retries and toolingalready work at this levelNames, but verbs hide inbodies; caches see littleHTTP as a tunnel: SOAP,JSON-RPC, many internal APIsRichardson maturity model (Fowler, 2010): a learning ladder, not a definition of REST

چرا بیشتر APIها در سطح ۲ می‌مانند: کلاینت‌ها بر اساس سند OpenAPI و SDK تولیدشده نوشته می‌شوند نه کشف در زمان اجرا؛ JSON قالب پیوند استاندارد ندارد (HAL، JSON:API، Siren و هدر Link در RFC 8288 با هم رقابت می‌کنند)؛ هزینهٔ افزودن پیوند کم است اما سودش به کلاینت‌هایی نیاز دارد که واقعاً دنبال پیوند بروند. راه میانهٔ عمل‌گرا «سطح ۲ به‌علاوهٔ چند پیوند» است: Link: rel="next" برای صفحه‌ها، Location برای منبع‌های ساخته‌شده، و پیوندهای عمل وابسته به وضعیت مثل cancel تا UI ماشین حالت سرور را تکرار نکند.

قالبپیوندها کجا هستندچه کسی استفاده می‌کند
هدر Link در RFC 8288هدر پاسخصفحه‌بندی: REST API گیت‌هاب ("You can use the link header from the response to request additional pages")، سرور Go همین صفحه
HAL (application/hal+json)شیء _linksیک قالب Internet-Draft، رایج در APIهای ابررسانه‌محور
JSON:APIlinks و relationshipsJsonApiResource در Laravel 13
Sirenactions با متد و فیلدهاکم، اما غنی‌ترین
شیء links دلخواهبدنهOrderResource در Laravel همین صفحه

راه درست: پیوندهای self، صفحه‌بندی و گذار وضعیت را جایی بگذارید که کلاینت بر اساس وضعیت تصمیم می‌گیرد؛ با این حال URIها را پایدار نگه دارید، چون بیشتر کلاینت‌ها آن‌ها را hard-code می‌کنند.

صفحه‌بندی: offset، cursor و keyset حیاتی ​

به زبان ساده: هرگز فهرست بی‌انتها برنگردانید. صفحه‌بندی offset می‌گوید «۴۰۰ تا را رد کن، ۲۰ تا بده»؛ صفحه‌بندی cursor می‌گوید «۲۰ تا بعد از این نشانک بده». نشانک معمولاً از کلید مرتب‌سازی ساخته می‌شود (keyset)، پس پایگاه داده مستقیم به آن می‌پرد.

بدفهمی رایج: «صفحه‌بندی cursor همان شمارهٔ صفحه با املای دیگر است.» صفحه‌های offset با درج یا حذف ردیف جابه‌جا می‌شوند (تکراری می‌بینید یا ردیفی را از دست می‌دهید)، و OFFSET 100000 پایگاه داده را وادار می‌کند ۱۰۰٬۰۰۰ ردیف بخواند و دور بریزد. cursor از نوع keyset زیر نوشتن هم‌زمان پایدار است و هزینه‌اش در صفحهٔ ۱ و صفحهٔ ۱۰٬۰۰۰ یکی است. چیزی که از دست می‌دهید «پرش به صفحهٔ ۳۷» و معمولاً شمارش دقیق کل است.

تعریف: صفحه‌بندی offset: ?page=3&per_page=20 یا ?offset=40&limit=20 و در SQL LIMIT 20 OFFSET 40. صفحه‌بندی keyset: WHERE (created_at, id) < (:last_created_at, :last_id) ORDER BY created_at DESC, id DESC LIMIT 21 که در آن id یکتا ترتیب را کامل می‌کند. صفحه‌بندی cursor: API مقدارهای keyset (و فیلترها) را در رشته‌ای مات (Opaque Cursor) می‌پیچد و به شکل next_cursor و/یا هدر Link: rel="next" برمی‌گرداند. مستندات Laravel مستقیم می‌گوید: "cursor pagination works by constructing "where" clauses that compare the values of the ordered columns". SQL عمیق و طراحی index در Pagination: Offset vs Keyset است.

text
     Offset under concurrent insert                    Keyset under the same insert
1    GET ?page=1 -> ids 20..11                          GET ?limit=10 -> ids 20..11, cursor(11)
2    new order 21 inserted                              new order 21 inserted
3    GET ?page=2 -> ids 11..2   (11 shown twice)        GET ?cursor(11) -> ids 10..1 (no duplicate)
4    a delete of id 15 instead would skip id 10         a delete changes nothing for later pages

سناریوی واقعی: فید با اسکرول بی‌پایان؛ job همگام‌سازی که هر سفارشی را که از دیروز تغییر کرده می‌کشد؛ جدول مدیریتی که شمارهٔ صفحه و کل لازم دارد (زیر چند هزار ردیف offset مشکلی ندارد)؛ خروجی ۵۰ میلیون ردیف (keyset یا خروجی طولانی، هرگز offset).

محصول یا راهنماسبکنام فیلدها
Google AIP-158token ماتpage_size، page_token، next_page_token؛ "The page_token field must not be required"
Microsoft Azureپیوند ماتآرایهٔ value به‌علاوهٔ URL مطلق nextLink؛ "DO NOT return the nextLink field at all when returning the last page"
Zalandocursor ترجیح دارد"SHOULD prefer cursor-based pagination, avoid offset-based pagination"
Laravel 13paginate() با کل، simplePaginate() بی کل، cursorPaginate() از نوع keysetرشتهٔ cursor در query، next_cursor در JSON
سرور Go همین صفحهcursor از نوع keyset (JSON آخرین id و فیلتر با base64url)limit، cursor، next_cursor، Link: rel="next"

راه درست: limit پیش‌فرض ۲۰ تا ۵۰ و سقف ۱۰۰؛ برای هر چیزی که رشد می‌کند cursor بدهید نه شمارهٔ صفحه؛ فیلترها را در cursor بگذارید یا cursorی را که با فیلتر دیگری آمده رد کنید (سرور Go با 400 و "invalid-cursor" جواب می‌دهد)؛ روی (ستون‌های فیلتر، ستون مرتب‌سازی، id) index بسازید؛ اگر کلاینت کل را لازم دارد، تخمین یا /orders/count جداگانه بدهید.

sql
-- Keyset page for GET /orders?status=paid&limit=20, newest first.
-- Index: (customer_id, status, created_at, id) as in the Laravel migration.
SELECT public_id, status, total_cents, created_at, id
FROM orders
WHERE customer_id = $1
  AND status = 'paid'
  AND (created_at, id) < ($2, $3)        -- values decoded from the cursor
ORDER BY created_at DESC, id DESC
LIMIT 21;                                -- one extra row tells you if there is a next page

فیلتر، مرتب‌سازی و sparse fieldsets مهم ​

به زبان ساده: به کلاینت اجازه دهید مجموعه را باریک کند (?status=paid)، مرتبش کند (?sort=-created_at) و فیلد کمتری بخواهد (?fields=id,status)، اما فقط از راه یک فهرست مجاز (allow-list) که می‌توانید برایش index بسازید و تا ابد پشتیبانی کنید.

بدفهمی رایج: «sort و filter را مستقیم به query builder بدهید، انعطاف دارد.» این همچنین SQL injection از راه نام ستون، اسکن کامل بدون index و قراردادی است که دیگر هرگز نمی‌توانید عوضش کنید. هر فیلتر و مرتب‌سازی که می‌پذیرید یک قول و یک index است.

تعریف: فیلتر (Filtering): پارامتر query برای هر فیلد (status=paid، created_after=...) یا زبان عبارت کوچک (رشتهٔ filter در Google AIP-160، $filter در OData). مرتب‌سازی (Sorting): فهرست فیلد با جهت (sort=-created_at,id؛ در AIP-132 فیلد order_by، که در آن "users append a " desc" suffix; for example: "foo desc, bar""). Sparse fieldsets: کلاینت فیلدهای برگشتی را انتخاب می‌کند (fields=id,status؛ در JSON:API fields[orders]=...؛ field mask در Google؛ در Zalando "SHOULD support partial responses via filtering").

text
     Client                                                    API
1    GET /orders?status=paid&sort=-created_at&fields=id,total_cents&limit=50
2                                                              validate: status in enum, sort in allow-list,
3                                                              fields subset of schema, limit <= 100
4                                                              SELECT ... WHERE status='paid' ORDER BY created_at DESC, id DESC
5    <- 200 {"data":[{"id":"ord_9","total_cents":4999}, ...], "next_cursor":"..."}
6    GET /orders?sort=password_hash                            -> 400 invalid-parameter

سناریوی واقعی: صفحهٔ فهرست در موبایل که فقط id، title و thumbnail_url لازم دارد (sparse fieldsets بار را کم می‌کند)؛ جست‌وجوی پنل مدیریت با ده فیلتر (به‌جای SQL به یک سیستم جست‌وجو فکر کنید)؛ یکپارچه‌سازی شریک که updated_after=... را همگام می‌کند (index روی updated_at, id لازم دارد).

قابلیتGoogle AIPMicrosoft AzureJSON:API / Laravel
فیلتررشتهٔ filter در AIP-160 با دستور زبان تعریف‌شدهگزینهٔ query به نام filterfilter[status]=paid (مستندات Laravel بستهٔ Spatie Laravel Query Builder را پیشنهاد می‌کند)
مرتب‌سازیorder_by در AIP-132orderbysort=-created_at
Sparse fieldsfield mask و read_maskselectfields[orders]=id,status؛ JsonApiResource در Laravel sparse fieldsets را مدیریت می‌کند
همراه با صفحه‌بندیtoken باید فیلترها را رمز کندnextLink شاملشان است ("DO include any query parameters required by the service")withQueryString() روی paginator

راه درست: با allow-list اعتبارسنجی کنید (Rule::in در Laravel، map[string]bool در Go)، نام‌های عمومی را صریح به ستون‌ها نگاشت کنید، برای هر ترکیب پشتیبانی‌شده index بسازید و فیلترها را در cursor بگذارید تا پیوند next سازگار بماند.

خطاها: Problem Details طبق RFC 9457 حیاتی ​

به زبان ساده: هر بدنهٔ خطا یک شکل کوچک و ثابت دارد: یک URI به نام type که کلاینت بر اساسش تصمیم می‌گیرد، یک title برای انسان، status، یک detail اختیاری و instance که خطا رویش رخ داده، به‌علاوهٔ هر فیلد اضافه‌ای که مستند می‌کنید.

بدفهمی رایج: «Problem Details جای کد وضعیت را می‌گیرد.» کد همچنان دستهٔ شکست را حمل می‌کند و بدنه دلیل مشخص را اضافه می‌کند. title برای انسان است و ممکن است ترجمه شود، پس کلاینت بر اساس type تصمیم می‌گیرد، هرگز بر اساس متن.

تعریف: RFC 9457 (July 2023، "This document obsoletes RFC 7807") یک "problem detail" تعریف می‌کند "to carry machine-readable details of errors in HTTP response content"، که با application/problem+json سریال می‌شود و عضوهای type، status، title، detail و instance دارد، به‌علاوهٔ عضوهای توسعه (Extension Members) مثل errors برای اعتبارسنجی در سطح فیلد.

text
     Client                                     API
1    POST /orders {"customer":"","total_cents":0}
2                                               422 Content-Type: application/problem+json
3                                               {"type":"https://api.example.com/problems/validation",
4                                                "title":"Validation failed","status":422,"instance":"/orders",
5                                                "errors":[{"pointer":"#/customer","detail":"is required"}, ...]}
6    client maps pointer #/customer to the form field and shows "is required"

سناریوی واقعی: اپ موبایلی که خطای اعتبارسنجی را کنار هر فیلد نشان می‌دهد؛ SDK شریکی که چون type به out-of-credit ختم می‌شود OutOfCreditError پرتاب می‌کند؛ پشتیبانی که لاگ‌ها را با instance جست‌وجو می‌کند؛ API gatewayای (Kong، Envoy) که 429 خودش را با همین قالب می‌فرستد تا کلاینت یک parser داشته باشد.

محصول یا راهنماقالب خطا
RFC 9457application/problem+json، type/title/status/detail/instance
Zalando"MUST support problem JSON"
Microsoft Azureپوشهٔ خودش: {"error": {"code", "message", "target", "details", "innererror"} } به‌علاوهٔ هدر x-ms-error-code ("values are part of your API contract")
Google AIP-193google.rpc.Status با code، message، details
پیش‌فرض Laravel 13{"message": ..., "errors": {...} } با 422؛ Problem Details داخلی ندارد، پس این صفحه آن را در bootstrap/app.php رندر می‌کند
Go net/httphttp.Error متن ساده (text/plain) می‌نویسد؛ helper خودتان را بنویسید (writeProblem در اینجا)

راه درست: در هر stack یک helper؛ URIهای type که به مستندات برسند؛ هرگز stack trace یا SQL را در detail خطای 5xx نگذارید؛ روی خطاها Cache-Control: no-store؛ همین شکل را در gateway هم نگه دارید.

کلید idempotency برای POST حیاتی ​

به زبان ساده: کلاینت برای یک عملیات منطقی («پرداخت فاکتور ۹، گروه تلاش A») یک کلید یکتا می‌سازد و در هر retry همان را می‌فرستد. سرور کلید را با نتیجه به خاطر می‌سپارد، پس تلاش دوم و سوم و دهم به‌جای انجام دوبارهٔ کار، نتیجهٔ اول را برمی‌گرداند.

بدفهمی رایج: «یک unique constraint روی جدول سفارش کافی است.» جلوی ردیف تکراری را می‌گیرد، اما retry به‌جای 201 اصلی، 409 یا 500 می‌گیرد، کلاینت نمی‌تواند موفقیت را از شکست تشخیص دهد و اثرهای جانبی خارج از آن جدول (شارژ کارت، ایمیل) باز هم دو بار اجرا می‌شوند. کلید باید کل عملیات و پاسخش را بپوشاند.

تعریف: پیش‌نویس IETF (draft-ietf-httpapi-idempotency-key-header-09): "An idempotency key is a unique value generated by the client which the resource uses to recognize subsequent retries of the same request." مقدار از نوع String در structured fields است (Idempotency-Key: "8e03978e-40d5-43e8-bc93-6894a57f9324")؛ "It is RECOMMENDED that a UUID [RFC9562] or a similar random identifier be used". قرارداد: نبودن کلید روی عملیاتی که آن را لازم دارد 400؛ استفادهٔ دوباره از کلید "with a different request payload" یعنی 422؛ retry "while the original request is still being processed" یعنی 409؛ retry پس از پایان "a response consistent with the request being completed" می‌گیرد. سرور استفادهٔ دوباره با بدنهٔ دیگر را با اثر انگشت idempotency (Idempotency Fingerprint) تشخیص می‌دهد و "SHOULD define such expiration policy and publish it". API در Stripe همین شکل را مستند می‌کند: کلیدها "up to 255 characters long" و حذف "after they're at least 24 hours old".

text
     Client                               API                                 Store
1    POST /payments  Idempotency-Key: "k1"   claim k1 (INSERT ... PK)          k1 = in flight
2                                         charge card, 201 {id: pay_5}       k1 = 201 + body
3    (response lost, client times out)
4    POST /payments  Idempotency-Key: "k1"   k1 exists, same fingerprint        -> replay 201 {id: pay_5}
5    POST /payments  "k1", amount changed   fingerprint differs               -> 422
6    two retries race while 2 is running    second sees in flight             -> 409, Retry-After: 1
POST + Idempotency-KeyKey present and valid?Key seen for this client?400 Bad RequestNew: insert row (in flight),run handler, save response422: fingerprint differs409 + Retry-After: in flightCompleted: replay savedstatus, headers, bodyHandler failed (4xx/5xx):delete row, retry allowednoyesnoyesdraft-ietf-httpapi-idempotency-key-header-09

سناریوی واقعی: پرداخت با کارت و تسویه؛ ثبت سفارش از اپ موبایلی که پس از وصل شدن دوباره retry می‌کند؛ فرستندهٔ webhook که دوباره تحویل می‌دهد؛ سرویس داخلی که سرویس دیگری را با سیاست retry صدا می‌زند (Service Communication).

محصولPOST چطور قابل retry می‌شود
پیش‌نویس IETFهدر درخواست Idempotency-Key؛ قرارداد 400 / 409 / 422
StripeIdempotency-Key؛ "the status code and body of the first request" را ذخیره می‌کند (API v1) و دوباره برمی‌گرداند، "including 500 errors"
Google AIP-155فیلد request_id (UUID4) در پیام درخواست؛ "This request is only idempotent if a request_id is provided"
Microsoft Azureهدرهای Repeatability-Request-ID و Repeatability-First-Sent؛ راهنما می‌گوید "all HTTP methods are idempotent"، از جمله POST
Zalando"MAY consider to support Idempotency-Key header"، یا یک کلید ثانویه در بدنه
Laravel 13middleware داخلی ندارد؛ RequireIdempotencyKey همین صفحه جدولی دارد که کلید اصلی‌اش قفل است
Goداخلی ندارد؛ IdempotencyStore.Middleware همین صفحه

راه درست: روی هر POST غیر idempotent که اثر جانبی دارد کلید را الزامی کنید؛ کلیدها را برای هر کلاینت جدا کنید؛ از متد، مسیر و بدنه اثر انگشت بگیرید؛ پاسخ را ذخیره کنید نه فقط «دیده شد»؛ نتیجهٔ 4xx/5xx را به کلید نچسبانید (این صفحه ردیف را حذف می‌کند تا درخواست اصلاح‌شده بتواند همان کلید را به کار ببرد؛ Stripe v1 برعکس انتخاب می‌کند و 500 را هم بازپخش می‌کند، پس انتخابتان را مستند کنید). موتور ذخیره، پاک‌سازی TTL، crash بین شارژ و ذخیره و کلیدهای چندمنطقه‌ای در API Idempotency هستند.

کنترل هم‌روندی: ETag، If-Match و قفل خوش‌بینانه حیاتی ​

به زبان ساده: وقتی منبعی را می‌خوانید سرور برچسب نسخه‌اش را به شما می‌دهد. وقتی می‌نویسید برچسب را پس می‌فرستید: «فقط اگر هنوز همان نسخه‌ای است که دیدم اعمالش کن». اگر کسی در این فاصله تغییرش داده باشد 412 می‌گیرید و باید دوباره بخوانید، به‌جای اینکه بی‌صدا کار او را بازنویسی کنید.

بدفهمی رایج: «تراکنش پایگاه داده از ما محافظت می‌کند.» تراکنش از یک درخواست محافظت می‌کند. lost update اینجا دو درخواست با فاصلهٔ چند دقیقه را در بر می‌گیرد: Alice می‌خواند، Bob می‌خواند، Alice می‌نویسد، Bob وضعیت قدیمی را دوباره می‌نویسد. فقط پیش‌شرطی که همراه درخواست سفر کند (یا version در بدنه) آن را می‌گیرد.

تعریف: ETag یک اعتبارسنج مات برای یک بازنمایی است؛ ETag قوی باید بایت به بایت برابر باشد، ETag ضعیف (W/"...") یعنی هم‌ارز معنایی. If-Match نوشتن را مشروط به برابری قوی می‌کند و شکستش 412 است. If-None-Match روی GET وقتی برچسب هنوز جور است 304 برمی‌گرداند؛ If-None-Match: * روی PUT یعنی «فقط اگر وجود ندارد بساز». RFC 6585 کد 428 را برای سرورهایی که نوشتن شرطی را الزامی می‌کنند اضافه می‌کند، "to avoid the "lost update" problem". سمت سرور این همان هم‌روندی خوش‌بینانه (Optimistic Concurrency) است: UPDATE ... SET version = version + 1 WHERE id = ? AND version = ? و بررسی تعداد ردیف‌های تغییرکرده؛ سازوکار در Optimistic vs Pessimistic Locking.

text
     Alice                              API + DB                               Bob
1    GET /orders/7 -> ETag "7-v1"                                              GET /orders/7 -> ETag "7-v1"
2    PATCH If-Match "7-v1" {status:paid}  UPDATE ... WHERE version=1 (1 row)
3    <- 200 ETag "7-v2"
4                                         UPDATE ... WHERE version=1 (0 rows)  <- PATCH If-Match "7-v1" {note:x}
5                                         412 Precondition Failed              -> Bob re-reads v2, reapplies, PATCH "7-v2"
6                                         200 ETag "7-v3"
AliceOrders API + DBBobGET /orders/7200, ETag: "7-v1"GET /orders/7200, ETag: "7-v1"PATCH, If-Match: "7-v1"WHERE version = 1: 1 row200, ETag: "7-v2"PATCH, If-Match: "7-v1"WHERE version = 1: 0 rows412 Precondition FailedGET again, reapply, PATCH If-Match "7-v2"200, ETag: "7-v3"No If-Match at all: 428 Precondition Required (RFC 6585)

سناریوی واقعی: دو کارشناس پشتیبانی که یک تیکت را ویرایش می‌کنند؛ اپ موبایلی که ویرایش آفلاین دیروز را همگام می‌کند؛ مدیر موجودی و یک job واردکردن که یک محصول را تغییر می‌دهند؛ ابزار پیکربندی (Kubernetes همین کار را با resourceVersion می‌کند: وقتی نسخهٔ "provided is stale), the API server returns a 409 Conflict").

محصول یا راهنمااعتبارسنجپیش‌شرطشکست
RFC 9110ETagIf-Match، If-Unmodified-Since412
Google AIP-154فیلد etag در بدنهٔ منبعدر درخواست update برگردانده می‌شودABORTED (HTTP 409)
Microsoft Azureهدر ETag"DO support caching and optimistic concurrency by honoring the If-Match, If-None-Match"412
Kubernetesmetadata.resourceVersionفیلد بدنه409 Conflict
Laravel 13$response->setEtag() (از Symfony)If-Match را خودتان بخوانید؛ compare-and-set با where('version', ...)->increment('version', 1, $changes)پرتاب PreconditionFailedHttpException
Go net/httpهدر ETag را خودتان بگذاریدhttp.ServeContent برای فایل‌ها If-Match را مدیریت می‌کند؛ برای API تابع precondition() را بنویسید412

راه درست: ETag را از ستون version بسازید نه از hash کردن JSON در هر درخواست؛ روی PATCH/PUT/DELETE منبع‌های مشترک If-Match را الزامی کنید (نبودنش 428)؛ پس از هر نوشتن موفق ETag تازه برگردانید؛ در بدنهٔ 412 توضیح دهید چه باید کرد.

هدرهای کش مهم ​

به زبان ساده: به همهٔ کش‌های مسیر (مرورگر، CDN، reverse proxy) بگویید آیا می‌توانند پاسخ را نگه دارند، تا کی، و چطور ارزان بررسی کنند که هنوز تازه است.

بدفهمی رایج: «no-cache یعنی کش نکن.» در RFC 9111، no-cache یعنی «ذخیره کن، اما پیش از هر استفاده دوباره اعتبارسنجی کن»؛ دستوری که ذخیره را ممنوع می‌کند no-store است. پاسخ‌های API مخصوص هر کاربر private, no-cache به‌علاوهٔ ETag می‌خواهند؛ پاسخ‌های خطا و رازها no-store.

تعریف: دستورهای Cache-Control در RFC 9111: max-age، s-maxage (فقط کش‌های مشترک)، public، private، no-cache، no-store، must-revalidate، stale-while-revalidate. اعتبارسنج‌ها: ETag با If-None-Match، Last-Modified با If-Modified-Since. Vary هدرهایی از درخواست را نام می‌برد که گونه را انتخاب می‌کنند (Accept، Accept-Language؛ پاسخ‌های دارای Authorization را کش‌های مشترک ذخیره نمی‌کنند مگر صریحاً اجازه داده شود).

text
     Browser                         CDN (Cloudflare)               API
1    GET /products/42                miss                           200 Cache-Control: public, max-age=60, s-maxage=300; ETag "p42-v8"
2    GET /products/42 (30 s later)   browser cache hit, no request
3    GET /products/42 (2 min later)  CDN hit (s-maxage 300)
4    GET /products/42 (6 min later)  If-None-Match "p42-v8"   ->    304, 0 bytes of body

سناریوی واقعی: کاتالوگ عمومی با ۵۰٬۰۰۰ درخواست در ثانیه که تقریباً کامل از CDN سرو می‌شود؛ پاسخ‌های GET /me که هرگز نباید در کش مشترک بمانند؛ اپ موبایلی که با 304 پهنای باند صرفه‌جویی می‌کند؛ صفحهٔ قطعی که با stale-while-revalidate سرو می‌شود.

محصولتنظیم
Laravel 13middleware به نام cache.headers: cache.headers:public;max_age=30;s_maxage=300;stale_while_revalidate=600;etag
Go net/httpهدرهای Cache-Control/ETag را بگذارید؛ http.ServeContent برای محتوای بایتی به درخواست شرطی جواب می‌دهد
NGINXproxy_cache، proxy_cache_valid، proxy_cache_use_stale
Cloudflare / Fastly / CloudFrontبه Cache-Control/s-maxage از origin احترام می‌گذارند، به‌علاوهٔ قواعد کش خودشان

راه درست: مدل‌های خواندنی عمومی public, max-age, s-maxage؛ خواندن‌های مخصوص کاربر private, no-cache و ETag؛ نوشتن‌ها و خطاها no-store؛ طراحی عمیق کش در Caching و CDN است.

هدرهای rate limit و Retry-After مهم ​

به زبان ساده: پیش از آنکه کلاینت به سقف برسد سهمیه و مقدار باقی‌مانده را به او بگویید، و وقتی رسید با 429 بگویید چقدر صبر کند.

بدفهمی رایج: «X-RateLimit-* استاندارد است.» قراردادی پرکاربرد است (GitHub، middleware به نام throttle در Laravel) بدون معنای واحد. پیش‌نویس گروه کاری IETF HTTPAPI فیلدهای RateLimit-Policy و RateLimit را به شکل structured field تعریف می‌کند؛ نحوشان بین نسخه‌های پیش‌نویس تغییر کرده، پس نسخه‌ای را که پیاده می‌کنید ثابت کنید.

تعریف: در RFC 6585 کد 429 "MAY include a Retry-After header indicating how long to wait before making a new request". در draft-ietf-httpapi-ratelimit-headers-12: RateLimit-Policy: burst;q=100;w=60,"daily";q=1000;w=86400 سیاست‌های سهمیه را فهرست می‌کند (q سهمیه، w پنجره به ثانیه، qu واحد، pk کلید پارتیشن)؛ RateLimit: default;a=50;w=30 سهمیهٔ در دسترس a و پنجرهٔ مؤثر w را می‌دهد. "If a response contains both the RateLimit and Retry-After fields, the Retry-After field MUST take precedence".

text
     Client app-1                                 API (limit 100/min)
1    GET /orders                                  200 RateLimit-Policy: default;q=100;w=60
2                                                     RateLimit: default;a=99;w=60
3    ... 99 more requests in 20 s ...
4    GET /orders                                  429 Retry-After: 40, RateLimit: default;a=0;w=40
5    client sleeps 40 s (plus jitter), resumes

سناریوی واقعی: API عمومی با سطح رایگان و پولی؛ یکپارچه‌سازی شریک که همگام‌سازی حجیم را با خواندن a تنظیم می‌کند به‌جای شکست خوردن؛ Laravel که وقتی limiter پر شود خودش 429 می‌دهد؛ limit_req در NGINX در لبه، که پیش‌فرضش limit_req_status 503; است (آن را 429 کنید).

محصولهدرهای ارسالی
ThrottleRequests در Laravel 13X-RateLimit-Limit، X-RateLimit-Remaining؛ روی 429 همچنین Retry-After و X-RateLimit-Reset (کد منبع فریم‌ورک)
GitHub REST APIx-ratelimit-limit، x-ratelimit-remaining، x-ratelimit-reset (قرارداد، نه منبع این صفحه)
پیش‌نویس IETF نسخهٔ 12RateLimit-Policy، RateLimit (و RateLimit-Partition)
Zalando"MUST use code 429 with headers for rate limits"
سرور Go همین صفحهفیلدهای نسخهٔ 12 به‌علاوهٔ Retry-After

راه درست: هر جا ممکن است برای هر کلاینت احرازشده محدود کنید نه برای هر IP؛ فیلدها را در هر پاسخ بفرستید؛ 429 برای سهمیه، 503 برای بار زیاد (Load Shedding)؛ الگوریتم‌ها (token bucket، sliding window، شمارندهٔ توزیع‌شده) در Rate Limiting هستند.

endpointهای bulk و دسته‌ای تکمیلی ​

به زبان ساده: وقتی کلاینت باید صدها چیز را بسازد یا تغییر دهد، یک درخواست با چندین قلم از صدها درخواست بهتر است، اما باید تصمیم بگیرید اگر قلم ۳۷ شکست خورد چه شود.

بدفهمی رایج: «200 و فهرستی از نتیجه‌ها برگردان، تمام.» آن‌وقت کلاینتی که بدنه را نادیده می‌گیرد خیال می‌کند همه‌چیز کار کرد. یا دسته را اتمی کنید (همه یا هیچ، با کد وضعیت عادی) یا موفقیت جزئی را صریح کنید (نتیجهٔ جدا برای هر قلم به سبک 207، یا عملیات طولانی با گزارش).

تعریف: endpoint bulk (Bulk Endpoint) مجموعه‌ای از قلم‌ها را در یک درخواست می‌پذیرد: POST /orders:batchCreate (custom method در Google AIP-233: "Some APIs need to allow users to create multiple resources in a single transaction"؛ AIP-233 موفقیت اتمی در برابر جزئی را بررسی می‌کند و متدهای دسته‌ای همگام را به اتمی محدود می‌کند)، یا POST /orders/bulk. اندازه سقف دارد و هر قلم می‌تواند کلید idempotency خودش را داشته باشد.

text
     Client                                    API
1    POST /orders:batchCreate {requests:[500 items]}  Idempotency-Key: "b1"
2                                              validate all first; any invalid -> 422 listing pointers #/requests/37/total_cents
3                                              all valid -> one transaction -> 200 {orders:[...]}
4    too big for one transaction -> 202 + /operations/op_9, report lists per-item status

سناریوی واقعی: واردکردن CSV محصولات؛ پایانهٔ فروشگاهی که فروش آفلاین یک روز را بارگذاری می‌کند؛ برچسب‌زدن ۱۰٬۰۰۰ ایمیل؛ خوانده‌شده کردن اعلان‌ها.

انتخابوضعیتچه وقت
دستهٔ همگام اتمی200/201 یا یک 4xxدسته‌های کوچک، یک پایگاه داده
موفقیت جزئی با نتیجهٔ هر قلم200 با status برای هر قلم (یا 207 از WebDAV)قلم‌های مستقل، کلاینت می‌تواند شکست‌خورده‌ها را تکرار کند
دستهٔ ناهمگام202 + منبع وضعیتدسته‌های بزرگ یا کند

راه درست: تعداد قلم‌ها را محدود کنید (۱۰۰ تا ۱٬۰۰۰)، پیش از نوشتن هر چیزی همه را اعتبارسنجی کنید، دسته را idempotent کنید و هرگز شکست را پشت یک 200 خالی پنهان نکنید.

عملیات طولانی (Long-running Operations) مهم ​

به زبان ساده: اگر کار بیشتر از عمر معقول یک درخواست طول می‌کشد (خروجی، تبدیل ویدئو، راه‌اندازی منابع)، بپذیرید، فوراً با 202 و یک URI برای پیگیری جواب دهید، و وقتی تمام شد به نتیجه اشاره کنید.

بدفهمی رایج: «202 یعنی کار شد.» RFC 9110: درخواست "might or might not eventually be acted upon"؛ "The 202 response is intentionally noncommittal." منبع وضعیت تنها جایی است که نتیجه ظاهر می‌شود.

تعریف: POST /exports → 202 Accepted با Location: /operations/op_1 و Retry-After: 1، و بدنه همان operation است {id, status: running}. GET /operations/op_1 تا وقتی اجرا می‌شود 200 می‌دهد؛ پس از پایان، یا 200 با status: succeeded و پیوند نتیجه، یا 303 See Other با Location نتیجه. Google AIP-151 یک google.longrunning.Operation با فیلد done برمی‌گرداند؛ Microsoft Azure کد 202 با هدر operation-location به یک ناظر وضعیت می‌دهد.

text
     Client                              API                         Worker
1    POST /exports?format=csv            -> 202 Location: /operations/op_1, Retry-After: 1
2                                        enqueue job op_1           picks op_1
3    GET /operations/op_1                -> 200 {status: running}, Retry-After: 1
4                                                                    writes file, marks succeeded
5    GET /operations/op_1                -> 303 See Other, Location: /exports/exp_1
6    GET /exports/exp_1                  -> 200 text/csv (or a presigned object-storage URL)

سناریوی واقعی: خروجی صورت‌حساب ماهانه؛ job پیش‌بینی دسته‌ای ML؛ ساختن cluster پایگاه داده در کنسول ابری؛ واردکردن حجیم با گزارش هر ردیف.

محصول یا راهنماشروعPollپایان
Google AIP-151متد Operation برمی‌گرداندGET /v1/{name=operations/*}done: true با response یا error
Microsoft Azure202 + operation-locationمنبع ناظر وضعیتstatus: Succeeded/Failed
این صفحه (Go و Laravel)202 + Location + Retry-AfterGET /operations/{id}303 به نتیجه
جایگزین‌های pushwebhook یا SSE/WebSocket—callback

راه درست: شروع را idempotent کنید (Idempotency-Key)، operationها را پایدار ذخیره کنید تا restart آن‌ها را گم نکند، به نتیجه‌ها تاریخ انقضا بدهید و برای کلاینت‌هایی که نباید poll کنند webhook بگذارید؛ اجرای job در Laravel یک queued job است (Durable Workflows & Jobs).

خلاصهٔ نسخه‌بندی مهم ​

به زبان ساده: طوری طراحی کنید که بیشتر تغییرها افزودنی باشند و نسخه نخواهند؛ وقتی ناچار به شکستن هستید، به قرارداد تازه نسخه بدهید و مدتی هر دو را اجرا کنید.

بدفهمی رایج: «از روز اول /v1/ را در همهٔ URLها بگذار و برای هر تغییر بالا ببر.» بالا بردن نسخه برای هر کلاینت یک مهاجرت است. افزودن فیلد اختیاری، endpoint تازه یا مقدار enum تازه (اگر به کلاینت‌ها گفته شده مقدار ناشناخته را تحمل کنند) شکننده نیست.

تعریف: راهبردهای اصلی: مسیر URI (/v1/orders، APIهای Google)، پارامتر query (?api-version=2021-06-04، Microsoft Azure، که در نبودش 400 با "MissingApiVersionParameter" می‌دهد)، هدر (یک هدر نسخهٔ سفارشی مثل Api-Version: 2026-11-01) و media type (Accept: application/vnd.example.order+json;version=2؛ در Zalando "MUST use media type versioning" و "MUST not use URL versioning"). قواعد تغییر شکننده، هدرهای deprecation، سیاست sunset و مهاجرت expand/contract در API Versioning & Evolution هستند.

text
     Change                                    Breaking?   Action
1    add optional response field "eta"         No          ship; clients ignore unknown fields
2    add optional request field                No          ship with a default
3    rename "total" to "total_cents"           Yes         add new field, deprecate old, remove in v2
4    make "note" required                      Yes         new version or keep optional
5    change 200 to 202 for POST /orders        Yes         new version
راهبردمثالسازگار با کشچه کسی استفاده می‌کند
مسیر URI/v1/ordersبلهAPIهای Google (مثال‌های AIP از /v1/... استفاده می‌کنند)، بسیاری از APIهای عمومی
پارامتر query?api-version=2021-06-04بلهMicrosoft Azure
هدر سفارشیApi-Version: 2026-11-01Vary لازم داردAPIهایی که نسخه را با تاریخ ثابت می‌کنند
Media typeapplication/vnd.example+json;v=2Vary: Accept لازم داردZalando

OpenAPI 3.1، contract-first و codegen حیاتی ​

به زبان ساده: API را پیش از کد (یا هم‌زمان با آن) به شکل قراردادی ماشین‌خوان بنویسید، مثل کد بازبینی‌اش کنید و مستندات، SDK کلاینت، stub سرور، mock و تست را از آن تولید کنید.

بدفهمی رایج: «فایل OpenAPI را از annotationها تولید می‌کنیم، پس قرارداد داریم.» خروجی code-first هر کاری را که کد اتفاقاً می‌کند توصیف می‌کند، از جمله تغییرهای شکنندهٔ تصادفی. Contract-first یعنی قرارداد بازبینی، نسخه‌بندی و در CI مقایسه می‌شود و پیاده‌سازی در برابرش تست می‌شود.

تعریف: مشخصهٔ OpenAPI "defines a standard, programming language-agnostic interface description for HTTP APIs". در نسخهٔ 3.1.0 (15 February 2021) "The Schema Object ... is a superset of JSON Schema Specification Draft 2020-12"، پس type: [string, 'null'] جای nullable: true نسخهٔ 3.0 را می‌گیرد و webhookها درجه‌یک می‌شوند. Contract-first (در Zalando: "MUST follow API first principle") سند را اول می‌نویسد؛ codegen آن را به کلاینت و رابط سرور تبدیل می‌کند (OpenAPI Generator، oapi-codegen برای Go، Kiota)؛ lint (Spectral) راهنمای سبک را اجرا می‌کند؛ مقایسهٔ تغییر شکننده (oasdiff) در CI دروازه می‌شود.

text
     Step                                        Tool (examples)
1    write orders.yaml, open a pull request      editor, Spectral lint with your style rules
2    review resources, codes, headers            humans
3    CI: diff against main                       oasdiff -> fail on breaking change
4    generate Go server interface + TS client    oapi-codegen, OpenAPI Generator
5    mock for frontend work                      Prism
6    contract tests: real server vs document     schemathesis or Pact-style tests

قرارداد سرویس این صفحه (هر دو پیاده‌سازی از آن پیروی می‌کنند):

yaml
openapi: 3.1.0
info:
  title: Orders API
  version: 1.4.0
  description: Contract-first definition of the orders resource used on this page.
servers:
  - url: https://api.example.com
paths:
  /orders:
    get:
      operationId: listOrders
      parameters:
        - { name: status, in: query, schema: { $ref: '#/components/schemas/Status' } }
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100, default: 20 } }
        - { name: cursor, in: query, description: 'Opaque; copy it from next_cursor or the Link header.', schema: { type: string } }
        - { name: fields, in: query, description: 'Sparse fieldset, e.g. id,status', schema: { type: string } }
      responses:
        '200':
          description: One page of orders.
          headers:
            Link: { description: 'rel="next" when another page exists', schema: { type: string } }
            RateLimit: { schema: { type: string } }
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data: { type: array, items: { $ref: '#/components/schemas/Order' } }
                  next_cursor: { type: string }
        '400': { $ref: '#/components/responses/Problem' }
        '429': { $ref: '#/components/responses/TooManyRequests' }
    post:
      operationId: createOrder
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/NewOrder' }
      responses:
        '201':
          description: Created.
          headers:
            Location: { required: true, schema: { type: string, format: uri-reference } }
            ETag: { required: true, schema: { type: string } }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Order' }
        '400': { $ref: '#/components/responses/Problem' }
        '409': { $ref: '#/components/responses/Problem' }
        '415': { $ref: '#/components/responses/Problem' }
        '422': { $ref: '#/components/responses/Problem' }
  /orders/{id}:
    parameters:
      - { name: id, in: path, required: true, schema: { type: string, pattern: '^ord_[0-9a-z]+$' } }
    get:
      operationId: getOrder
      parameters:
        - { name: If-None-Match, in: header, schema: { type: string } }
      responses:
        '200':
          description: The order.
          headers:
            ETag: { required: true, schema: { type: string } }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Order' }
        '304': { description: Not modified; reuse your cached copy. }
        '404': { $ref: '#/components/responses/Problem' }
        '410': { $ref: '#/components/responses/Problem' }
    patch:
      operationId: updateOrder
      parameters:
        - { name: If-Match, in: header, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/merge-patch+json:
            schema: { $ref: '#/components/schemas/OrderPatch' }
          application/json-patch+json:
            schema:
              type: array
              items:
                type: object
                required: [op, path]
                properties:
                  op: { enum: [add, remove, replace, test] }
                  path: { type: string }
                  value: {}
      responses:
        '200':
          description: Updated; new ETag.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Order' }
        '409': { $ref: '#/components/responses/Problem' }
        '412': { $ref: '#/components/responses/Problem' }
        '415': { $ref: '#/components/responses/Problem' }
        '422': { $ref: '#/components/responses/Problem' }
        '428': { $ref: '#/components/responses/Problem' }
    delete:
      operationId: deleteOrder
      responses:
        '204': { description: Deleted. }
        '404': { $ref: '#/components/responses/Problem' }
        '410': { $ref: '#/components/responses/Problem' }
components:
  parameters:
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: true
      description: Structured-field string, e.g. "8e03978e-40d5-43e8-bc93-6894a57f9324". Kept 24 h.
      schema: { type: string, maxLength: 257 }
  schemas:
    Status: { type: string, enum: [pending, paid, shipped, cancelled] }
    NewOrder:
      type: object
      additionalProperties: false
      required: [customer, total_cents]
      properties:
        customer: { type: string, minLength: 1 }
        total_cents: { type: integer, minimum: 1 }
        note: { type: [string, 'null'], maxLength: 500 }
    OrderPatch:
      type: object
      additionalProperties: false
      properties:
        customer: { type: string, minLength: 1 }
        status: { $ref: '#/components/schemas/Status' }
        note: { type: [string, 'null'], description: 'null removes the note (RFC 7396)' }
    Order:
      type: object
      required: [id, customer, status, total_cents, version, created_at]
      properties:
        id: { type: string, readOnly: true }
        customer: { type: string }
        status: { $ref: '#/components/schemas/Status' }
        total_cents: { type: integer }
        note: { type: [string, 'null'] }
        version: { type: integer, readOnly: true }
        created_at: { type: string, format: date-time, readOnly: true }
    Problem:
      type: object
      properties:
        type: { type: string, format: uri-reference }
        title: { type: string }
        status: { type: integer }
        detail: { type: string }
        instance: { type: string, format: uri-reference }
        errors:
          type: array
          items:
            type: object
            properties:
              pointer: { type: string }
              detail: { type: string }
  responses:
    Problem:
      description: RFC 9457 Problem Details.
      content:
        application/problem+json:
          schema: { $ref: '#/components/schemas/Problem' }
    TooManyRequests:
      description: Rate limited.
      headers:
        Retry-After: { schema: { type: integer } }
      content:
        application/problem+json:
          schema: { $ref: '#/components/schemas/Problem' }
ابزارنقش
OpenAPI 3.1قالب قرارداد
JSON Schema 2020-12schema بدنه‌ها درون آن
Spectrallint در برابر راهنمای سبک
oapi-codegen (Go)، OpenAPI Generator، Kiotastub سرور و SDK
Prismسرور mock
Laravel: Scribe، dedoc/scramble (بستهٔ شخص ثالث)تولید مستندات از کد Laravel (code-first)

مبانی امنیت مهم ​

به زبان ساده: هر درخواست را احراز هویت کنید (قید stateless)، هر شیء را مجوزدهی کنید (نه فقط هر route را)، به شناسه‌های آمده از کلاینت اعتماد نکنید و در خطاها چیزی لو ندهید.

بدفهمی رایج: «route میان‌افزار auth دارد، پس endpoint امن است.» این بررسی می‌کند فراخوان کیست، نه اینکه سفارش ۷ مال او هست یا نه. مجوزدهی شکسته در سطح شیء (عوض کردن id در URL برای خواندن دادهٔ دیگری) همان "API1:2023 Broken Object Level Authorization" است، اولین قلم OWASP API Security Top 10.

تعریف: 401 یعنی اعتبارنامهٔ غایب یا نامعتبر و WWW-Authenticate الزامی است؛ 403 یعنی «می‌شناسمت، و نه»؛ 404 را می‌شود به‌جای 403 به کار برد تا وجود منبع لو نرود (Response::denyAsNotFound() در Laravel). توکن‌ها: bearer token در OAuth 2.0 با scope (OAuth 2.0 & OIDC، JWT)، توکن شخصی Laravel Sanctum با ability (tokenCan). انتقال: TLS همه‌جا (Cryptography & TLS). کلاینت مرورگری: CORS و CSRF (Sessions, Cookies & CORS).

text
     Request                                         Check                     Answer
1    GET /orders/ord_7  (no token)                   authentication            401 WWW-Authenticate: Bearer
2    GET /orders/ord_7  (token of user 42, owns it)  policy view: allow        200
3    GET /orders/ord_8  (token of user 42, not his)  policy view: deny         404 (not 403, hide existence)
4    PATCH /orders/ord_7 (token without orders:write) policy update: deny      404 or 403 by policy
دغدغهGoLaravel 13
احراز هویتمیان‌افزاری که JWT یا نشست را بررسی می‌کندمیان‌افزار auth:sanctum
مجوزدهی شیءبررسی مالک در handler یا یک تابع policyPolicy به‌علاوهٔ Gate::authorize('view', $order)؛ authorize() در Form Request کد 403 می‌دهد
Mass assignmentdecode در struct درخواست، DisallowUnknownFields$fillable، $request->validated()
اندازهٔ ورودیhttp.MaxBytesReaderpost_max_size، قاعدهٔ اعتبارسنجی max:
خطاهاProblem Details بدون جزئیات داخلیcallback به نام render()، APP_DEBUG=false

مطالب عمیق‌تر: OWASP Top 10، Authorization Models، Authentication.

قواعد نام‌گذاری و راهنماهای سبک API تکمیلی ​

به زبان ساده: یک راهنمای سبک API منتشرشده انتخاب کنید، با فهرست کوتاهی از استثناها بپذیریدش و در برابرش lint کنید، تا ۴۰ تیم یک API بسازند نه ۴۰ API.

بدفهمی رایج: «راهنمای سبک یعنی بحث بی‌حاصل سر رنگ دوچرخه‌خانه.» این راهنماها صفحه‌بندی، خطا، کار طولانی، نسخه‌بندی و idempotency را تعیین می‌کنند که بعداً تغییرشان گران است؛ حالت حروف کوچک‌ترین بخش آن است.

تعریف: راهنمای سبک API (API Style Guide) مجموعه‌ای از قواعد هنجاری (MUST/SHOULD) برای APIهای یک سازمان است. سه راهنمای پرارجاع: Google AIP (API Improvement Proposals در google.aip.dev: طراحی منبع‌محور AIP-121، نام منبع AIP-122، متدهای استاندارد AIP-131 تا 135، custom methods در AIP-136، LRO در AIP-151، etag در AIP-154، request id در AIP-155، صفحه‌بندی AIP-158، فیلتر AIP-160، دسته‌ای AIP-231 تا 235)؛ Microsoft REST API Guidelines (github.com/microsoft/api-guidelines، همراه با راهنمای مخصوص Azure)؛ Zalando RESTful API Guidelines (opensource.zalando.com).

text
     Team writes orders.yaml -> Spectral ruleset "company-api-style" -> CI comment:
1    error  path segment "/orderItems" must be kebab-case            (Zalando rule)
2    error  operation createOrder has no 4xx Problem response         (house rule)
3    warn   list operation without cursor parameter                   (house rule)
موضوعGoogle AIPMicrosoft AzureZalando
صفحه‌بندیpage_token / next_page_tokennextLinkcursor ترجیح دارد
خطاgoogle.rpc.Statusپوشهٔ error + x-ms-error-codeProblem JSON
PATCHupdate با update_maskJSON Merge PatchJSON Merge Patch یا JSON Patch
Idempotencyrequest_idهدرهای RepeatabilityIdempotency-Key (MAY)
نسخه‌بندینسخهٔ اصلی در مسیرپارامتر query به نام api-versionmedia type
کار طولانیgoogle.longrunning.Operation202 + operation-location202 + منبع وضعیت
حالت حروفcamelCase در JSONcamelCasesnake_case در JSON، kebab-case در مسیر

سازوکار (Mechanics) ​

دستور زبان HTTP که باید دقیقاً درست باشد ​

چیزشکل دقیقنکته
ETag قویETag: "ord_000001-v2"گیومه‌ها بخشی از مقدارند
ETag ضعیفETag: W/"ord_000001-v2"هرگز با If-Match جور نمی‌شود (مقایسهٔ قوی)
فهرست If-MatchIf-Match: "a", "b" یا ** یعنی «هر بازنمایی فعلی»
Idempotency-KeyIdempotency-Key: "8e03978e-40d5-43e8-bc93-6894a57f9324"String از structured fields: با گیومه
Link صفحهٔ بعدLink: </orders?cursor=eyJh...&limit=2>; rel="next"RFC 8288؛ URI داخل براکت زاویه‌ای
Retry-AfterRetry-After: 40 یا یک HTTP-dateثانیه بهتر است (بدون اختلاف ساعت)
RateLimit-PolicyRateLimit-Policy: default;q=100;w=60نحو نسخهٔ 12 پیش‌نویس
RateLimitRateLimit: default;a=99;w=60a یعنی در دسترس، w یعنی پنجره به ثانیه
Accept-PatchAccept-Patch: application/merge-patch+json, application/json-patch+jsonروی 415 برای PATCH و روی OPTIONS بفرستید
AllowAllow: DELETE, GET, HEAD, PATCHهمراه 405 الزامی است

تنظیمات هر stack ​

تنظیممقدار این صفحهچرا
http.Server.ReadHeaderTimeout در Go5 sمحافظت در برابر هدرهای کند (Slowloris)؛ مقدار صفر یعنی بی‌حد
http.MaxBytesReader در Go1 MiBسقف بدنه برای هر درخواست
json.Decoder.DisallowUnknownFields در Goروشن برای createعضو ناشناخته به‌جای نادیده گرفته شدن بی‌صدا، 400 می‌شود
limit صفحهپیش‌فرض 20، حداکثر 100پاسخ محدود
TTL کلید idempotency24 hدر قرارداد منتشر شده، برابر کمینهٔ v1 در Stripe
Limit::perMinute(120)->by('user:'.$id) در Laravel120 در دقیقه برای هر کاربر، 20 برای هر IPسهمیهٔ منصفانه برای هر کلاینت
cursorPaginate(25) در Laravel25به orderBy روی ستون‌های جدول صفحه‌بندی‌شده نیاز دارد
cache.headers در Laravelprivate;etag برای دادهٔ کاربربا etag اگر ETag تنظیم نشده بدنه را hash می‌کند (xxh128) و isNotModified() را صدا می‌زند

پیام‌های خطایی که واقعاً می‌بینید ​

کجاپیاممعنا
ServeMux در Go، متد نادرست405 Method Not Allowed با بدنهٔ Method Not Allowed و Allowالگو برای متدهای دیگر وجود دارد
ServeMux در Go، هنگام ثبتpanic: pattern "GET /orders/{name}" (registered at main.go:8) conflicts with pattern "GET /orders/{id}" (registered at main.go:7): GET /orders/{name} matches the same requests as GET /orders/{id}دو الگو با درخواست‌های یکسان جورند و هیچ‌کدام مشخص‌تر نیست (با Go 1.27 بازتولید شد)
json.Decoder در Gojson: unknown field "admin"DisallowUnknownFields عضوی را رد کرد
http.MaxBytesReader در Gohttp: request body too largeبدنه از سقف گذشت
اعتبارسنجی LaravelThe total cents field must be at least 1. (422)قاعدهٔ Form Request شکست خورد
Laravel، throttle429 Too Many Attempts.ThrottleRequestsException که ThrottleRequests پرتاب می‌کند
Laravel، رد policy403 This action is unauthorized.AuthorizationException به 403 تبدیل شد
Laravel، مدل غایب404 No query results for model [App\Models\Order] ...route model binding چیزی پیدا نکرد (با Problem Details جایگزین کنید)
AzureMissingApiVersionParameter (400)پارامتر query به نام api-version نیامده

Go ​

ماژول academy/rest-api-design (دستور go 1.24، فقط کتابخانهٔ استاندارد) نسخهٔ اول بد، بستهٔ سرویس و یک سرور قابل اجرا دارد.

Before ​

یک تونل RPC: یک URI، عمل‌ها در بدنه، 200 برای خطا، صفحه‌بندی offset روی یک map، آخرین نوشتن برنده است و createOrder تکرارشده سفارش دوم می‌سازد.

go
// Command before is the RPC-over-HTTP shape many first APIs take.
// It works, but every request is POST /api, every answer is 200,
// errors hide in the body, nothing is cacheable and a retried
// "createOrder" creates a second order.
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"strconv"
	"sync"
)

type order struct {
	ID       int    `json:"id"`
	Customer string `json:"customer"`
	Status   string `json:"status"`
}

var (
	mu     sync.Mutex
	nextID = 1
	orders = map[int]*order{}
)

type call struct {
	Action string          `json:"action"`
	Params json.RawMessage `json:"params"`
}

func api(w http.ResponseWriter, r *http.Request) {
	var c call
	_ = json.NewDecoder(r.Body).Decode(&c)
	w.Header().Set("Content-Type", "application/json")
	mu.Lock()
	defer mu.Unlock()
	switch c.Action {
	case "createOrder":
		var o order
		_ = json.Unmarshal(c.Params, &o)
		o.ID, o.Status = nextID, "pending"
		nextID++
		orders[o.ID] = &o
		_ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "order": o})
	case "getOrder":
		var p struct{ ID int }
		_ = json.Unmarshal(c.Params, &p)
		o, found := orders[p.ID]
		if !found {
			// 200 with an error flag: caches, proxies and clients see success.
			_ = json.NewEncoder(w).Encode(map[string]any{"ok": false, "error": "not found"})
			return
		}
		_ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "order": o})
	case "listOrders":
		// Offset paging over a map: unstable order, skipped and repeated rows.
		var p struct{ Page, Size int }
		_ = json.Unmarshal(c.Params, &p)
		list := []*order{}
		for _, o := range orders {
			list = append(list, o)
		}
		start := p.Page * p.Size
		if start > len(list) {
			start = len(list)
		}
		end := min(start+p.Size, len(list))
		_ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "orders": list[start:end], "total": strconv.Itoa(len(list))})
	case "updateOrder":
		// Last write wins: no version, no precondition, lost updates.
		var o order
		_ = json.Unmarshal(c.Params, &o)
		orders[o.ID] = &o
		_ = json.NewEncoder(w).Encode(map[string]any{"ok": true})
	default:
		_ = json.NewEncoder(w).Encode(map[string]any{"ok": false, "error": fmt.Sprintf("unknown action %q", c.Action)})
	}
}

func main() {
	http.HandleFunc("/api", api)
	log.Fatal(http.ListenAndServe("127.0.0.1:8080", nil))
}

After ​

Problem Details در یک helper. kind بخش آخر type می‌شود تا کلاینت روی یک رشتهٔ پایدار تصمیم بگیرد.

go
// Package orders is a small REST service built on the Go 1.22+ net/http
// router: resources and collections, Problem Details (RFC 9457) errors,
// ETag/If-Match optimistic concurrency, cursor (keyset) pagination,
// sparse fieldsets, Idempotency-Key on POST, RateLimit headers and a
// long-running operation behind 202 Accepted.
package orders

import (
	"encoding/json"
	"net/http"
)

// ProblemTypeBase prefixes every problem "type" URI. A real API points it at
// documentation pages that explain each problem.
const ProblemTypeBase = "https://api.example.com/problems/"

// Problem is an RFC 9457 problem details object with one extension member.
type Problem struct {
	Type     string       `json:"type"`
	Title    string       `json:"title"`
	Status   int          `json:"status"`
	Detail   string       `json:"detail,omitempty"`
	Instance string       `json:"instance,omitempty"`
	Errors   []FieldError `json:"errors,omitempty"`
}

// FieldError is the "errors" extension used for 422 validation failures.
type FieldError struct {
	Pointer string `json:"pointer"`
	Detail  string `json:"detail"`
}

// writeProblem sends application/problem+json. kind becomes the last segment of
// the type URI so clients can switch on it without parsing the title.
func writeProblem(w http.ResponseWriter, r *http.Request, status int, kind, title, detail string, errs ...FieldError) {
	p := Problem{
		Type:     ProblemTypeBase + kind,
		Title:    title,
		Status:   status,
		Detail:   detail,
		Instance: r.URL.Path,
		Errors:   errs,
	}
	w.Header().Set("Content-Type", "application/problem+json")
	w.Header().Set("Cache-Control", "no-store")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(p)
}

Store برای هر سفارش یک Version نگه می‌دارد (منبع ETag)، به‌روزرسانی compare-and-set انجام می‌دهد، برای 410 سنگ قبر (tombstone) نگه می‌دارد و به queryهای keyset جواب می‌دهد.

go
package orders

import (
	"errors"
	"fmt"
	"sort"
	"sync"
	"time"
)

// Order is the resource. Version is the optimistic-concurrency counter that
// the ETag is derived from; a SQL table carries it as a "version" column.
type Order struct {
	ID         string    `json:"id"`
	Customer   string    `json:"customer"`
	Status     string    `json:"status"`
	TotalCents int64     `json:"total_cents"`
	Note       *string   `json:"note"`
	Version    int64     `json:"version"`
	CreatedAt  time.Time `json:"created_at"`
}

// Errors the handlers map to status codes.
var (
	ErrNotFound        = errors.New("not found")
	ErrGone            = errors.New("gone")
	ErrVersionMismatch = errors.New("version mismatch")
	ErrBadTransition   = errors.New("invalid status transition")
)

// allowed lists legal status transitions; anything else is a 409 Conflict.
var allowed = map[string][]string{
	"pending":   {"paid", "cancelled"},
	"paid":      {"shipped", "cancelled"},
	"shipped":   {},
	"cancelled": {},
}

func canMove(from, to string) bool {
	if from == to {
		return true
	}
	for _, s := range allowed[from] {
		if s == to {
			return true
		}
	}
	return false
}

// Store is an in-memory stand-in for a table ordered by primary key.
type Store struct {
	mu      sync.Mutex
	seq     int
	rows    map[string]*Order
	deleted map[string]bool
	now     func() time.Time
}

// NewStore returns an empty store; now is injectable for tests.
func NewStore(now func() time.Time) *Store {
	return &Store{rows: map[string]*Order{}, deleted: map[string]bool{}, now: now}
}

// Create inserts a new order with version 1. IDs are zero-padded so their
// string order equals insertion order, which keyset pagination relies on.
func (s *Store) Create(customer string, total int64, note *string) Order {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.seq++
	o := &Order{
		ID:         fmt.Sprintf("ord_%06d", s.seq),
		Customer:   customer,
		Status:     "pending",
		TotalCents: total,
		Note:       note,
		Version:    1,
		CreatedAt:  s.now().UTC(),
	}
	s.rows[o.ID] = o
	return *o
}

// Get returns a copy of one order, ErrGone for a deleted one.
func (s *Store) Get(id string) (Order, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.deleted[id] {
		return Order{}, ErrGone
	}
	o, ok := s.rows[id]
	if !ok {
		return Order{}, ErrNotFound
	}
	return *o, nil
}

// Update applies fn only when the stored version equals want: the same
// compare-and-set as UPDATE ... WHERE id = $1 AND version = $2.
func (s *Store) Update(id string, want int64, fn func(*Order) error) (Order, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.deleted[id] {
		return Order{}, ErrGone
	}
	o, ok := s.rows[id]
	if !ok {
		return Order{}, ErrNotFound
	}
	if o.Version != want {
		return *o, ErrVersionMismatch
	}
	next := *o
	if err := fn(&next); err != nil {
		return *o, err
	}
	if !canMove(o.Status, next.Status) {
		return *o, ErrBadTransition
	}
	next.Version++
	*o = next
	return next, nil
}

// Delete removes an order and keeps a tombstone so later reads answer 410.
func (s *Store) Delete(id string, want int64) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.deleted[id] {
		return ErrGone
	}
	o, ok := s.rows[id]
	if !ok {
		return ErrNotFound
	}
	if want != 0 && o.Version != want {
		return ErrVersionMismatch
	}
	delete(s.rows, id)
	s.deleted[id] = true
	return nil
}

// ListAfter is keyset pagination: rows with id > after, ordered by id,
// optionally filtered by status. It returns limit+1 rows at most so the
// caller can tell whether another page exists.
func (s *Store) ListAfter(after, status string, limit int) []Order {
	s.mu.Lock()
	defer s.mu.Unlock()
	ids := make([]string, 0, len(s.rows))
	for id := range s.rows {
		ids = append(ids, id)
	}
	sort.Strings(ids)
	out := []Order{}
	for _, id := range ids {
		if id <= after {
			continue
		}
		o := s.rows[id]
		if status != "" && o.Status != status {
			continue
		}
		out = append(out, *o)
		if len(out) == limit+1 {
			break
		}
	}
	return out
}

Handlerها از الگوهای Go 1.22 استفاده می‌کنند ("GET /orders/{id}"، r.PathValue("id")). mux برای مسیر شناخته‌شده با متد نادرست 405 و Allow می‌دهد، و الگوی GET به HEAD هم جواب می‌دهد. نوشتن‌ها Content-Type را بررسی می‌کنند (415)، PATCH به If-Match نیاز دارد (428، 412)، هر دو قالب merge patch و JSON Patch پشتیبانی می‌شوند، مجموعه با cursor و هدر Link و sparse fieldsets صفحه‌بندی می‌شود، حذف یک tombstone برای 410 می‌گذارد، لغو یک زیرمنبع است و خروجی یک عملیات طولانی است (202 و بعد 303).

go
package orders

import (
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"mime"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"sync"
	"time"
)

// Server wires the store, the idempotency layer and the rate limiter.
type Server struct {
	store   *Store
	idem    *IdempotencyStore
	limiter *Limiter

	mu  sync.Mutex
	ops map[string]*Operation
	op  int

	// Exporter does the slow work behind POST /exports. Tests replace it.
	Exporter func(format string) string
}

// Operation is the status resource of a long-running job (202 + poll).
type Operation struct {
	ID     string `json:"id"`
	Status string `json:"status"` // running | succeeded
	Result string `json:"result,omitempty"`
}

// New builds a server. limit is requests per window per client.
func New(store *Store, now func() time.Time, limit int, window time.Duration) *Server {
	return &Server{
		store:    store,
		idem:     NewIdempotencyStore(now, 24*time.Hour),
		limiter:  NewLimiter(now, limit, window),
		ops:      map[string]*Operation{},
		Exporter: func(string) string { time.Sleep(200 * time.Millisecond); return "exp_1" },
	}
}

// Handler registers Go 1.22 method-and-wildcard patterns. The mux answers
// 405 with an Allow header for a known path and a wrong method, and a
// "GET" pattern also serves HEAD.
func (s *Server) Handler() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /orders", s.list)
	mux.Handle("POST /orders", s.idem.Middleware(http.HandlerFunc(s.create)))
	mux.HandleFunc("GET /orders/{id}", s.get)
	mux.HandleFunc("PATCH /orders/{id}", s.patch)
	mux.HandleFunc("DELETE /orders/{id}", s.delete)
	mux.HandleFunc("POST /orders/{id}/cancellation", s.cancel)
	mux.Handle("POST /exports", s.idem.Middleware(http.HandlerFunc(s.startExport)))
	mux.HandleFunc("GET /operations/{id}", s.operation)
	return s.limiter.Middleware(mux)
}

func etag(o Order) string { return fmt.Sprintf(`"%s-v%d"`, o.ID, o.Version) }

// versionFromETag turns `"ord_000001-v3"` back into 3 for that id.
func versionFromETag(tag, id string) (int64, bool) {
	tag = strings.TrimSpace(tag)
	if strings.HasPrefix(tag, "W/") { // If-Match needs strong comparison
		return 0, false
	}
	tag = strings.Trim(tag, `"`)
	prefix := id + "-v"
	if !strings.HasPrefix(tag, prefix) {
		return 0, false
	}
	v, err := strconv.ParseInt(strings.TrimPrefix(tag, prefix), 10, 64)
	return v, err == nil
}

func writeJSON(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(v)
}

func hasMediaType(r *http.Request, want ...string) bool {
	mt, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
	if err != nil {
		return false
	}
	for _, w := range want {
		if mt == w {
			return true
		}
	}
	return false
}

func (s *Server) storeError(w http.ResponseWriter, r *http.Request, err error) {
	switch {
	case errors.Is(err, ErrNotFound):
		writeProblem(w, r, http.StatusNotFound, "not-found", "Order not found", "")
	case errors.Is(err, ErrGone):
		writeProblem(w, r, http.StatusGone, "gone", "Order was deleted", "")
	case errors.Is(err, ErrVersionMismatch):
		writeProblem(w, r, http.StatusPreconditionFailed, "stale-etag", "Precondition failed",
			"The order changed since you read it. GET it again, reapply your change, retry with the new ETag.")
	case errors.Is(err, ErrBadTransition):
		writeProblem(w, r, http.StatusConflict, "invalid-transition", "Status change not allowed", err.Error())
	default:
		writeProblem(w, r, http.StatusInternalServerError, "internal", "Internal error", "")
	}
}

// ---- collection ----

type cursor struct {
	After  string `json:"a"`
	Status string `json:"s,omitempty"`
}

func encodeCursor(c cursor) string {
	b, _ := json.Marshal(c)
	return base64.RawURLEncoding.EncodeToString(b)
}

func decodeCursor(s string) (cursor, error) {
	var c cursor
	b, err := base64.RawURLEncoding.DecodeString(s)
	if err != nil {
		return c, err
	}
	return c, json.Unmarshal(b, &c)
}

var listable = map[string]bool{"id": true, "customer": true, "status": true, "total_cents": true, "note": true, "version": true, "created_at": true}

// sparse keeps only the requested top-level fields (fields=id,status).
func sparse(o Order, fields []string) map[string]any {
	b, _ := json.Marshal(o)
	var all map[string]any
	_ = json.Unmarshal(b, &all)
	if len(fields) == 0 {
		return all
	}
	out := map[string]any{}
	for _, f := range fields {
		out[f] = all[f]
	}
	return out
}

func (s *Server) list(w http.ResponseWriter, r *http.Request) {
	q := r.URL.Query()
	limit := 20
	if v := q.Get("limit"); v != "" {
		n, err := strconv.Atoi(v)
		if err != nil || n < 1 || n > 100 {
			writeProblem(w, r, http.StatusBadRequest, "invalid-parameter", "Invalid limit", "limit must be an integer from 1 to 100",
				FieldError{Pointer: "#/query/limit", Detail: "out of range"})
			return
		}
		limit = n
	}
	c := cursor{Status: q.Get("status")}
	if v := q.Get("cursor"); v != "" {
		dc, err := decodeCursor(v)
		if err != nil || (q.Has("status") && dc.Status != c.Status) {
			writeProblem(w, r, http.StatusBadRequest, "invalid-cursor", "Invalid cursor",
				"Use the cursor exactly as returned, with the same filters.")
			return
		}
		c = dc
	}
	var fields []string
	if v := q.Get("fields"); v != "" {
		for _, f := range strings.Split(v, ",") {
			if !listable[f] {
				writeProblem(w, r, http.StatusBadRequest, "invalid-parameter", "Unknown field", f,
					FieldError{Pointer: "#/query/fields", Detail: "unknown field " + f})
				return
			}
			fields = append(fields, f)
		}
	}
	rows := s.store.ListAfter(c.After, c.Status, limit)
	page := map[string]any{}
	data := []map[string]any{}
	for i, o := range rows {
		if i == limit {
			break
		}
		data = append(data, sparse(o, fields))
	}
	page["data"] = data
	if len(rows) > limit {
		next := encodeCursor(cursor{After: rows[limit-1].ID, Status: c.Status})
		nq := url.Values{"cursor": {next}, "limit": {strconv.Itoa(limit)}}
		if len(fields) > 0 {
			nq.Set("fields", strings.Join(fields, ","))
		}
		page["next_cursor"] = next
		w.Header().Set("Link", fmt.Sprintf(`</orders?%s>; rel="next"`, nq.Encode()))
	}
	w.Header().Set("Cache-Control", "private, no-cache")
	writeJSON(w, http.StatusOK, page)
}

type createReq struct {
	Customer   string  `json:"customer"`
	TotalCents int64   `json:"total_cents"`
	Note       *string `json:"note"`
}

func (s *Server) create(w http.ResponseWriter, r *http.Request) {
	if !hasMediaType(r, "application/json") {
		writeProblem(w, r, http.StatusUnsupportedMediaType, "unsupported-media-type", "Send application/json", "")
		return
	}
	dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
	dec.DisallowUnknownFields()
	var in createReq
	if err := dec.Decode(&in); err != nil {
		writeProblem(w, r, http.StatusBadRequest, "malformed-json", "Malformed request body", err.Error())
		return
	}
	var errs []FieldError
	if strings.TrimSpace(in.Customer) == "" {
		errs = append(errs, FieldError{Pointer: "#/customer", Detail: "is required"})
	}
	if in.TotalCents <= 0 {
		errs = append(errs, FieldError{Pointer: "#/total_cents", Detail: "must be greater than 0"})
	}
	if len(errs) > 0 {
		writeProblem(w, r, http.StatusUnprocessableEntity, "validation", "Validation failed", "", errs...)
		return
	}
	o := s.store.Create(in.Customer, in.TotalCents, in.Note)
	w.Header().Set("Location", "/orders/"+o.ID)
	w.Header().Set("ETag", etag(o))
	writeJSON(w, http.StatusCreated, o)
}

// ---- item ----

func (s *Server) get(w http.ResponseWriter, r *http.Request) {
	o, err := s.store.Get(r.PathValue("id"))
	if err != nil {
		s.storeError(w, r, err)
		return
	}
	tag := etag(o)
	w.Header().Set("ETag", tag)
	w.Header().Set("Cache-Control", "private, no-cache")
	for _, t := range strings.Split(r.Header.Get("If-None-Match"), ",") {
		t = strings.TrimPrefix(strings.TrimSpace(t), "W/") // weak comparison for GET
		if t == tag || t == "*" {
			w.WriteHeader(http.StatusNotModified)
			return
		}
	}
	writeJSON(w, http.StatusOK, o)
}

// precondition enforces If-Match on writes: 428 when absent, 412 when it
// cannot match. It returns the version the client claims to have read.
func (s *Server) precondition(w http.ResponseWriter, r *http.Request, id string) (int64, bool) {
	h := r.Header.Get("If-Match")
	if h == "" {
		writeProblem(w, r, http.StatusPreconditionRequired, "precondition-required", "If-Match required",
			"GET the order and send its ETag in If-Match.")
		return 0, false
	}
	v, ok := versionFromETag(h, id)
	if !ok {
		writeProblem(w, r, http.StatusPreconditionFailed, "stale-etag", "Precondition failed", "ETag does not belong to this order")
		return 0, false
	}
	return v, true
}

// applyMerge implements RFC 7396 for the writable members: a member with
// null removes the value, an absent member leaves it unchanged.
func applyMerge(o *Order, patch map[string]json.RawMessage) []FieldError {
	var errs []FieldError
	for k, raw := range patch {
		switch k {
		case "customer", "status":
			var v string
			if err := json.Unmarshal(raw, &v); err != nil || v == "" {
				errs = append(errs, FieldError{Pointer: "#/" + k, Detail: "must be a non-empty string"})
				continue
			}
			if k == "customer" {
				o.Customer = v
			} else {
				o.Status = v
			}
		case "note":
			if string(raw) == "null" {
				o.Note = nil
				continue
			}
			var v string
			if err := json.Unmarshal(raw, &v); err != nil {
				errs = append(errs, FieldError{Pointer: "#/note", Detail: "must be a string or null"})
				continue
			}
			o.Note = &v
		default:
			errs = append(errs, FieldError{Pointer: "#/" + k, Detail: "is read-only or unknown"})
		}
	}
	return errs
}

type jsonPatchOp struct {
	Op    string          `json:"op"`
	Path  string          `json:"path"`
	Value json.RawMessage `json:"value"`
}

// applyJSONPatch supports the RFC 6902 ops that make sense on a flat
// resource: test, replace, add and remove. Any failed test aborts the whole
// document, which is how RFC 6902 makes a patch atomic.
func applyJSONPatch(o *Order, ops []jsonPatchOp) []FieldError {
	for i, op := range ops {
		name := strings.TrimPrefix(op.Path, "/")
		ptr := fmt.Sprintf("#/%d", i)
		switch op.Op {
		case "test":
			cur := sparse(*o, []string{name})[name]
			var want any
			_ = json.Unmarshal(op.Value, &want)
			if fmt.Sprint(cur) != fmt.Sprint(want) {
				return []FieldError{{Pointer: ptr, Detail: "test failed for " + op.Path}}
			}
		case "replace", "add":
			if errs := applyMerge(o, map[string]json.RawMessage{name: op.Value}); errs != nil {
				return errs
			}
		case "remove":
			if name != "note" {
				return []FieldError{{Pointer: ptr, Detail: "only /note can be removed"}}
			}
			o.Note = nil
		default:
			return []FieldError{{Pointer: ptr, Detail: "unsupported op " + op.Op}}
		}
	}
	return nil
}

func (s *Server) patch(w http.ResponseWriter, r *http.Request) {
	id := r.PathValue("id")
	w.Header().Set("Accept-Patch", "application/merge-patch+json, application/json-patch+json")
	merge := hasMediaType(r, "application/merge-patch+json")
	if !merge && !hasMediaType(r, "application/json-patch+json") {
		writeProblem(w, r, http.StatusUnsupportedMediaType, "unsupported-media-type", "Unsupported patch format",
			"Use application/merge-patch+json or application/json-patch+json")
		return
	}
	want, ok := s.precondition(w, r, id)
	if !ok {
		return
	}
	body := http.MaxBytesReader(w, r.Body, 1<<20)
	var mergeDoc map[string]json.RawMessage
	var ops []jsonPatchOp
	var err error
	if merge {
		err = json.NewDecoder(body).Decode(&mergeDoc)
	} else {
		err = json.NewDecoder(body).Decode(&ops)
	}
	if err != nil {
		writeProblem(w, r, http.StatusBadRequest, "malformed-json", "Malformed patch document", err.Error())
		return
	}
	var verrs []FieldError
	o, err := s.store.Update(id, want, func(o *Order) error {
		if merge {
			verrs = applyMerge(o, mergeDoc)
		} else {
			verrs = applyJSONPatch(o, ops)
		}
		if verrs != nil {
			return errors.New("validation")
		}
		return nil
	})
	if verrs != nil {
		writeProblem(w, r, http.StatusUnprocessableEntity, "validation", "Patch cannot be applied", "", verrs...)
		return
	}
	if err != nil {
		s.storeError(w, r, err)
		return
	}
	w.Header().Set("ETag", etag(o))
	writeJSON(w, http.StatusOK, o)
}

func (s *Server) delete(w http.ResponseWriter, r *http.Request) {
	id := r.PathValue("id")
	var want int64
	if h := r.Header.Get("If-Match"); h != "" {
		v, ok := versionFromETag(h, id)
		if !ok {
			writeProblem(w, r, http.StatusPreconditionFailed, "stale-etag", "Precondition failed", "")
			return
		}
		want = v
	}
	if err := s.store.Delete(id, want); err != nil {
		s.storeError(w, r, err)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

// cancel is a state change modelled as creating a "cancellation"
// sub-resource instead of a verb in the URI (POST /cancelOrder).
// Cancelling an already cancelled order returns the same 200: the
// effect is idempotent even though POST is not by definition.
func (s *Server) cancel(w http.ResponseWriter, r *http.Request) {
	id := r.PathValue("id")
	cur, err := s.store.Get(id)
	if err != nil {
		s.storeError(w, r, err)
		return
	}
	o, err := s.store.Update(id, cur.Version, func(o *Order) error { o.Status = "cancelled"; return nil })
	if err != nil {
		s.storeError(w, r, err)
		return
	}
	w.Header().Set("ETag", etag(o))
	writeJSON(w, http.StatusOK, o)
}

// ---- long-running operation ----

func (s *Server) startExport(w http.ResponseWriter, r *http.Request) {
	s.mu.Lock()
	s.op++
	op := &Operation{ID: fmt.Sprintf("op_%d", s.op), Status: "running"}
	s.ops[op.ID] = op
	snapshot := *op
	s.mu.Unlock()
	format := r.URL.Query().Get("format")
	go func() {
		res := s.Exporter(format)
		s.mu.Lock()
		op.Status, op.Result = "succeeded", "/exports/"+res
		s.mu.Unlock()
	}()
	w.Header().Set("Location", "/operations/"+op.ID)
	w.Header().Set("Retry-After", "1")
	writeJSON(w, http.StatusAccepted, snapshot)
}

// operation answers 200 while the job runs and 303 See Other, pointing at
// the result, once it has finished.
func (s *Server) operation(w http.ResponseWriter, r *http.Request) {
	s.mu.Lock()
	op, ok := s.ops[r.PathValue("id")]
	var snap Operation
	if ok {
		snap = *op
	}
	s.mu.Unlock()
	if !ok {
		writeProblem(w, r, http.StatusNotFound, "not-found", "Operation not found", "")
		return
	}
	if snap.Status == "succeeded" {
		w.Header().Set("Location", snap.Result)
		w.WriteHeader(http.StatusSeeOther)
		return
	}
	w.Header().Set("Retry-After", "1")
	writeJSON(w, http.StatusOK, snap)
}

میان‌افزار Idempotency-Key که قرارداد 400/409/422/بازپخش پیش‌نویس را پیاده می‌کند، برای هر کلاینت جدا و با اثر انگشت روی متد، مسیر و بدنه:

go
package orders

import (
	"bytes"
	"crypto/sha256"
	"encoding/hex"
	"io"
	"net/http"
	"strings"
	"sync"
	"time"
)

// IdempotencyStore implements the API contract of the IETF Idempotency-Key
// draft for POST: 400 when the key is missing, 409 while the first request
// is still running, 422 when the key is reused with a different payload, and
// a replay of the stored response otherwise. Storage design (SQL table,
// Redis, TTL sweeps) is the subject of /system-design/api-idempotency; this
// one is in memory.
type IdempotencyStore struct {
	mu   sync.Mutex
	rows map[string]*idemRow
	now  func() time.Time
	ttl  time.Duration
}

type idemRow struct {
	fingerprint string
	done        bool
	status      int
	header      http.Header
	body        []byte
	expires     time.Time
}

// NewIdempotencyStore keeps keys for ttl (the draft asks servers to publish it).
func NewIdempotencyStore(now func() time.Time, ttl time.Duration) *IdempotencyStore {
	return &IdempotencyStore{rows: map[string]*idemRow{}, now: now, ttl: ttl}
}

// parseKey accepts the draft's sf-string form ("abc") and, leniently, a bare token.
func parseKey(h string) string {
	h = strings.TrimSpace(h)
	if len(h) >= 2 && h[0] == '"' && h[len(h)-1] == '"' {
		h = h[1 : len(h)-1]
	}
	if len(h) > 255 {
		return ""
	}
	return h
}

type recorder struct {
	http.ResponseWriter
	status int
	buf    bytes.Buffer
}

func (r *recorder) WriteHeader(code int) { r.status = code; r.ResponseWriter.WriteHeader(code) }
func (r *recorder) Write(b []byte) (int, error) {
	if r.status == 0 {
		r.status = http.StatusOK
	}
	r.buf.Write(b)
	return r.ResponseWriter.Write(b)
}

// Middleware wraps a POST handler.
func (s *IdempotencyStore) Middleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		key := parseKey(r.Header.Get("Idempotency-Key"))
		if key == "" {
			writeProblem(w, r, http.StatusBadRequest, "idempotency-key-missing", "Idempotency-Key is missing",
				"This operation requires an Idempotency-Key header (1 to 255 characters).")
			return
		}
		body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
		if err != nil {
			writeProblem(w, r, http.StatusRequestEntityTooLarge, "too-large", "Body too large", "")
			return
		}
		r.Body = io.NopCloser(bytes.NewReader(body))
		sum := sha256.Sum256(append([]byte(r.Method+" "+r.URL.Path+"\n"), body...))
		fp := hex.EncodeToString(sum[:])
		// Scope keys by caller so two tenants cannot collide or probe each other.
		scoped := r.Header.Get("X-Client-Id") + "|" + key

		s.mu.Lock()
		row, seen := s.rows[scoped]
		if seen && s.now().After(row.expires) {
			delete(s.rows, scoped)
			seen = false
		}
		switch {
		case seen && row.fingerprint != fp:
			s.mu.Unlock()
			writeProblem(w, r, http.StatusUnprocessableEntity, "idempotency-key-reused", "Idempotency-Key is already used",
				"The key was used with a different request payload.")
			return
		case seen && !row.done:
			s.mu.Unlock()
			w.Header().Set("Retry-After", "1")
			writeProblem(w, r, http.StatusConflict, "idempotency-key-in-flight", "A request is outstanding for this Idempotency-Key", "")
			return
		case seen:
			s.mu.Unlock()
			for k, v := range row.header {
				w.Header()[k] = v
			}
			w.Header().Set("Idempotent-Replayed", "true")
			w.WriteHeader(row.status)
			_, _ = w.Write(row.body)
			return
		}
		row = &idemRow{fingerprint: fp, expires: s.now().Add(s.ttl)}
		s.rows[scoped] = row
		s.mu.Unlock()

		rec := &recorder{ResponseWriter: w}
		next.ServeHTTP(rec, r)

		s.mu.Lock()
		defer s.mu.Unlock()
		if rec.status >= 400 {
			// Do not pin a failure to the key: the client may fix the request
			// (4xx) or the server may recover (5xx) and the same key retried.
			delete(s.rows, scoped)
			return
		}
		// Replay only the headers that describe the result, not per-response
		// ones such as RateLimit.
		keep := http.Header{}
		for _, k := range []string{"Content-Type", "Location", "ETag"} {
			if v := w.Header().Values(k); len(v) > 0 {
				keep[k] = v
			}
		}
		row.done, row.status, row.header, row.body = true, rec.status, keep, rec.buf.Bytes()
	})
}

هدرهای RateLimit (نحو نسخهٔ 12 پیش‌نویس) روی یک limiter با پنجرهٔ ثابت:

go
package orders

import (
	"fmt"
	"net"
	"net/http"
	"strconv"
	"sync"
	"time"
)

// Limiter is a fixed-window counter per client that advertises its policy
// with the IETF RateLimit-Policy / RateLimit fields (draft-ietf-httpapi-
// ratelimit-headers-12 syntax) and answers 429 with Retry-After. The
// algorithms themselves live in /system-design/rate-limiting-algorithms.
type Limiter struct {
	mu     sync.Mutex
	now    func() time.Time
	limit  int
	window time.Duration
	counts map[string]*windowCount
}

type windowCount struct {
	start time.Time
	n     int
}

// NewLimiter allows limit requests per window per client key.
func NewLimiter(now func() time.Time, limit int, window time.Duration) *Limiter {
	return &Limiter{now: now, limit: limit, window: window, counts: map[string]*windowCount{}}
}

func clientKey(r *http.Request) string {
	if id := r.Header.Get("X-Client-Id"); id != "" {
		return id // an authenticated client id in a real API
	}
	host, _, err := net.SplitHostPort(r.RemoteAddr)
	if err != nil {
		return r.RemoteAddr
	}
	return host
}

// Middleware applies the limit to every request.
func (l *Limiter) Middleware(next http.Handler) http.Handler {
	w := int(l.window / time.Second)
	policy := fmt.Sprintf("default;q=%d;w=%d", l.limit, w)
	return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
		now := l.now()
		l.mu.Lock()
		c, ok := l.counts[clientKey(r)]
		if !ok || now.Sub(c.start) >= l.window {
			c = &windowCount{start: now}
			l.counts[clientKey(r)] = c
		}
		c.n++
		remaining := max(l.limit-c.n, 0)
		reset := int((l.window - now.Sub(c.start) + time.Second - 1) / time.Second)
		over := c.n > l.limit
		l.mu.Unlock()

		rw.Header().Set("RateLimit-Policy", policy)
		rw.Header().Set("RateLimit", fmt.Sprintf("default;a=%d;w=%d", remaining, reset))
		if over {
			rw.Header().Set("Retry-After", strconv.Itoa(reset))
			writeProblem(rw, r, http.StatusTooManyRequests, "rate-limited", "Too many requests",
				fmt.Sprintf("Limit is %d requests per %d s. Retry after %d s.", l.limit, w, reset))
			return
		}
		next.ServeHTTP(rw, r)
	})
}

تست با httptest. httptest.NewServer همان handler واقعی را روی پورت loopback اجرا می‌کند؛ ساعت تزریقی پنجره‌های rate limit را قطعی می‌کند. تست‌ها این‌ها را می‌پوشانند: 201 با Location و ETag، چهار حالت Idempotency-Key، 422/415/400 به شکل Problem Details، 304، 428، 412، شکست test در JSON Patch، 409 برای گذار نامجاز، صفحه‌های cursor که هر ردیف را دقیقاً یک بار با sparse fields می‌بینند، 204 و بعد 410، 405 با Allow، HEAD، 429 با Retry-After، و 202 و بعد 303.

go
package orders

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"
)

type clock struct{ t time.Time }

func (c *clock) now() time.Time { return c.t }

func newTest(t *testing.T, limit int) (*Server, *httptest.Server, *clock) {
	t.Helper()
	c := &clock{t: time.Date(2026, 11, 26, 10, 0, 0, 0, time.UTC)}
	s := New(NewStore(c.now), c.now, limit, time.Minute)
	ts := httptest.NewServer(s.Handler())
	t.Cleanup(ts.Close)
	return s, ts, c
}

func do(t *testing.T, ts *httptest.Server, method, path, body string, hdr ...string) *http.Response {
	t.Helper()
	req, err := http.NewRequest(method, ts.URL+path, strings.NewReader(body))
	if err != nil {
		t.Fatal(err)
	}
	for i := 0; i+1 < len(hdr); i += 2 {
		req.Header.Set(hdr[i], hdr[i+1])
	}
	cl := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
	res, err := cl.Do(req)
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { res.Body.Close() })
	return res
}

func decode[T any](t *testing.T, res *http.Response) T {
	t.Helper()
	var v T
	if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
		t.Fatal(err)
	}
	return v
}

func create(t *testing.T, ts *httptest.Server, key, body string) *http.Response {
	return do(t, ts, "POST", "/orders", body, "Content-Type", "application/json", "Idempotency-Key", `"`+key+`"`)
}

func TestCreateReturns201LocationAndETag(t *testing.T) {
	_, ts, _ := newTest(t, 100)
	res := create(t, ts, "k1", `{"customer":"c-42","total_cents":4999}`)
	if res.StatusCode != 201 || res.Header.Get("Location") != "/orders/ord_000001" || res.Header.Get("ETag") != `"ord_000001-v1"` {
		t.Fatalf("got %d %q %q", res.StatusCode, res.Header.Get("Location"), res.Header.Get("ETag"))
	}
}

func TestIdempotencyKeyContract(t *testing.T) {
	_, ts, _ := newTest(t, 100)
	body := `{"customer":"c-42","total_cents":4999}`
	if res := do(t, ts, "POST", "/orders", body, "Content-Type", "application/json"); res.StatusCode != 400 {
		t.Fatalf("missing key: want 400, got %d", res.StatusCode)
	}
	first := decode[Order](t, create(t, ts, "k1", body))
	replay := create(t, ts, "k1", body)
	again := decode[Order](t, replay)
	if replay.StatusCode != 201 || replay.Header.Get("Idempotent-Replayed") != "true" || again.ID != first.ID {
		t.Fatalf("replay: %d %q %s vs %s", replay.StatusCode, replay.Header.Get("Idempotent-Replayed"), again.ID, first.ID)
	}
	if res := create(t, ts, "k1", `{"customer":"c-42","total_cents":1}`); res.StatusCode != 422 {
		t.Fatalf("reuse with other payload: want 422, got %d", res.StatusCode)
	}
	if res := create(t, ts, "k2", body); decode[Order](t, res).ID == first.ID {
		t.Fatal("a new key must create a new order")
	}
}

func TestValidationIsProblemDetails(t *testing.T) {
	_, ts, _ := newTest(t, 100)
	res := create(t, ts, "k1", `{"customer":"","total_cents":0}`)
	if res.StatusCode != 422 || res.Header.Get("Content-Type") != "application/problem+json" {
		t.Fatalf("got %d %s", res.StatusCode, res.Header.Get("Content-Type"))
	}
	p := decode[Problem](t, res)
	if p.Type != ProblemTypeBase+"validation" || len(p.Errors) != 2 || p.Status != 422 {
		t.Fatalf("problem: %+v", p)
	}
	if res := do(t, ts, "POST", "/orders", `x`, "Content-Type", "text/plain", "Idempotency-Key", "k9"); res.StatusCode != 415 {
		t.Fatalf("want 415, got %d", res.StatusCode)
	}
	if res := create(t, ts, "k8", `{"customer":"a","total_cents":1,"admin":true}`); res.StatusCode != 400 {
		t.Fatalf("unknown member: want 400, got %d", res.StatusCode)
	}
}

func TestConditionalGetAndOptimisticConcurrency(t *testing.T) {
	_, ts, _ := newTest(t, 100)
	create(t, ts, "k1", `{"customer":"c-42","total_cents":4999,"note":"leave at door"}`)
	res := do(t, ts, "GET", "/orders/ord_000001", "")
	tag := res.Header.Get("ETag")
	if res := do(t, ts, "GET", "/orders/ord_000001", "", "If-None-Match", tag); res.StatusCode != 304 {
		t.Fatalf("want 304, got %d", res.StatusCode)
	}
	merge := []string{"Content-Type", "application/merge-patch+json"}
	if res := do(t, ts, "PATCH", "/orders/ord_000001", `{"status":"paid"}`, merge...); res.StatusCode != 428 {
		t.Fatalf("no If-Match: want 428, got %d", res.StatusCode)
	}
	// Alice patches with the ETag she read: 200 and a new ETag.
	ok := do(t, ts, "PATCH", "/orders/ord_000001", `{"status":"paid","note":null}`, append(merge, "If-Match", tag)...)
	o := decode[Order](t, ok)
	if ok.StatusCode != 200 || o.Version != 2 || o.Note != nil || ok.Header.Get("ETag") != `"ord_000001-v2"` {
		t.Fatalf("patch: %d %+v", ok.StatusCode, o)
	}
	// Bob still holds the old ETag: 412, his write cannot silently win.
	if res := do(t, ts, "PATCH", "/orders/ord_000001", `{"customer":"bob"}`, append(merge, "If-Match", tag)...); res.StatusCode != 412 {
		t.Fatalf("stale If-Match: want 412, got %d", res.StatusCode)
	}
	// JSON Patch with a failing test op changes nothing.
	jp := []string{"Content-Type", "application/json-patch+json", "If-Match", `"ord_000001-v2"`}
	if res := do(t, ts, "PATCH", "/orders/ord_000001", `[{"op":"test","path":"/status","value":"pending"},{"op":"replace","path":"/status","value":"shipped"}]`, jp...); res.StatusCode != 422 {
		t.Fatalf("failed test op: want 422, got %d", res.StatusCode)
	}
	if res := do(t, ts, "PATCH", "/orders/ord_000001", `[{"op":"test","path":"/status","value":"paid"},{"op":"replace","path":"/status","value":"shipped"}]`, jp...); res.StatusCode != 200 {
		t.Fatalf("json patch: want 200, got %d", res.StatusCode)
	}
	// shipped -> pending is not a legal transition: 409.
	if res := do(t, ts, "PATCH", "/orders/ord_000001", `{"status":"pending"}`, append(merge, "If-Match", `"ord_000001-v3"`)...); res.StatusCode != 409 {
		t.Fatalf("bad transition: want 409, got %d", res.StatusCode)
	}
	if res := do(t, ts, "PATCH", "/orders/ord_000001", `{"status":"paid"}`, "Content-Type", "application/json", "If-Match", `"ord_000001-v3"`); res.StatusCode != 415 || res.Header.Get("Accept-Patch") == "" {
		t.Fatalf("wrong patch type: want 415 + Accept-Patch, got %d", res.StatusCode)
	}
}

func TestCursorPaginationWalksEveryRowOnce(t *testing.T) {
	_, ts, _ := newTest(t, 1000)
	for i := 0; i < 7; i++ {
		create(t, ts, "k"+string(rune('a'+i)), `{"customer":"c","total_cents":100}`)
	}
	type page struct {
		Data []map[string]any `json:"data"`
		Next string           `json:"next_cursor"`
	}
	seen := map[string]bool{}
	path := "/orders?limit=3&fields=id,status"
	for pages := 0; path != ""; pages++ {
		res := do(t, ts, "GET", path, "")
		p := decode[page](t, res)
		for _, row := range p.Data {
			if len(row) != 2 {
				t.Fatalf("sparse fieldset ignored: %v", row)
			}
			id := row["id"].(string)
			if seen[id] {
				t.Fatalf("duplicate %s", id)
			}
			seen[id] = true
		}
		path = ""
		if link := res.Header.Get("Link"); link != "" {
			path = strings.TrimSuffix(strings.TrimPrefix(link, "<"), `>; rel="next"`)
		}
		if pages > 5 {
			t.Fatal("too many pages")
		}
	}
	if len(seen) != 7 {
		t.Fatalf("saw %d rows, want 7", len(seen))
	}
	if res := do(t, ts, "GET", "/orders?cursor=not-a-cursor!", ""); res.StatusCode != 400 {
		t.Fatalf("bad cursor: want 400, got %d", res.StatusCode)
	}
}

func TestDeleteThen410AndMethodNotAllowed(t *testing.T) {
	_, ts, _ := newTest(t, 100)
	create(t, ts, "k1", `{"customer":"c","total_cents":100}`)
	if res := do(t, ts, "DELETE", "/orders/ord_000001", ""); res.StatusCode != 204 {
		t.Fatalf("want 204, got %d", res.StatusCode)
	}
	if res := do(t, ts, "DELETE", "/orders/ord_000001", ""); res.StatusCode != 410 {
		t.Fatalf("second delete: want 410, got %d", res.StatusCode)
	}
	if res := do(t, ts, "GET", "/orders/ord_999999", ""); res.StatusCode != 404 {
		t.Fatalf("want 404, got %d", res.StatusCode)
	}
	res := do(t, ts, "PUT", "/orders/ord_000001", "{}")
	if res.StatusCode != 405 || !strings.Contains(res.Header.Get("Allow"), "PATCH") {
		t.Fatalf("want 405 with Allow, got %d %q", res.StatusCode, res.Header.Get("Allow"))
	}
	if res := do(t, ts, "HEAD", "/orders", ""); res.StatusCode != 200 {
		t.Fatalf("HEAD: want 200, got %d", res.StatusCode)
	}
}

func TestRateLimitHeadersAnd429(t *testing.T) {
	_, ts, c := newTest(t, 2)
	res := do(t, ts, "GET", "/orders", "", "X-Client-Id", "app-1")
	if res.Header.Get("RateLimit-Policy") != "default;q=2;w=60" || res.Header.Get("RateLimit") != "default;a=1;w=60" {
		t.Fatalf("headers: %q %q", res.Header.Get("RateLimit-Policy"), res.Header.Get("RateLimit"))
	}
	do(t, ts, "GET", "/orders", "", "X-Client-Id", "app-1")
	c.t = c.t.Add(20 * time.Second)
	res = do(t, ts, "GET", "/orders", "", "X-Client-Id", "app-1")
	if res.StatusCode != 429 || res.Header.Get("Retry-After") != "40" {
		t.Fatalf("want 429 Retry-After 40, got %d %q", res.StatusCode, res.Header.Get("Retry-After"))
	}
	if res := do(t, ts, "GET", "/orders", "", "X-Client-Id", "app-2"); res.StatusCode != 200 {
		t.Fatalf("other client: want 200, got %d", res.StatusCode)
	}
}

func TestLongRunningOperation(t *testing.T) {
	s, ts, _ := newTest(t, 1000)
	release := make(chan struct{})
	s.Exporter = func(string) string { <-release; return "exp_7" }
	res := do(t, ts, "POST", "/exports?format=csv", "", "Idempotency-Key", "e1")
	if res.StatusCode != 202 || res.Header.Get("Location") != "/operations/op_1" {
		t.Fatalf("want 202 + Location, got %d %q", res.StatusCode, res.Header.Get("Location"))
	}
	if res := do(t, ts, "GET", "/operations/op_1", ""); res.StatusCode != 200 {
		t.Fatalf("running: want 200, got %d", res.StatusCode)
	}
	close(release)
	deadline := time.Now().Add(2 * time.Second)
	for time.Now().Before(deadline) {
		res := do(t, ts, "GET", "/operations/op_1", "")
		if res.StatusCode == 303 {
			if res.Header.Get("Location") != "/exports/exp_7" {
				t.Fatalf("Location %q", res.Header.Get("Location"))
			}
			return
		}
		time.Sleep(10 * time.Millisecond)
	}
	t.Fatal("operation never finished")
}

سروری که در آزمایشگاه استفاده می‌شود:

go
// Command server runs the orders API on 127.0.0.1:8080 for the lab.
package main

import (
	"log"
	"net/http"
	"time"

	"academy/rest-api-design/orders"
)

func main() {
	srv := orders.New(orders.NewStore(time.Now), time.Now, 100, time.Minute)
	h := &http.Server{
		Addr:              "127.0.0.1:8080",
		Handler:           srv.Handler(),
		ReadHeaderTimeout: 5 * time.Second,
		ReadTimeout:       10 * time.Second,
		WriteTimeout:      10 * time.Second,
	}
	log.Println("listening on", h.Addr)
	log.Fatal(h.ListenAndServe())
}

نگاه Go ​

قابلیت Goکاربرد اینجانکته
الگوهای http.ServeMux (Go 1.22 به بعد)"GET /orders/{id}"، "POST /orders/{id}/cancellation""the most specific pattern wins"؛ 405 با Allow خودکار
Request.PathValueخواندن {id}{path...} بقیه را می‌گیرد؛ {$} فقط مسیر دقیق با اسلش انتهایی
mime.ParseMediaTypeبررسی‌های 415پارامترهایی مثل charset را کنار می‌گذارد
json.Decoder.DisallowUnknownFieldsبدنهٔ create سخت‌گیربرای PATCH decoder جدا به کار ببرید
http.MaxBytesReaderسقف بدنهپس از سقف خطا برمی‌گرداند
net/http/httptestNewServer و NewRecorder برای تستجز loopback شبکهٔ واقعی لازم نیست
encoding/base64.RawURLEncodingcursorهای مات و امن برای URLاگر cursor نباید جعل شود امضا یا رمزش کنید
http.ServeContentبازه‌های بایتی (206) و GET شرطی برای فایلنه برای منبع‌های JSON
اکوسیستمoapi-codegen (از OpenAPI به Go)، routerهای chi، echo، ginاز نسخهٔ 1.22، mux استاندارد برای بیشتر سرویس‌ها کافی است

Laravel ​

Before ​

فعل در URI، mass assignment از $request->all()، سریال کردن مدل همان‌طور که هست، 200 برای «پیدا نشد»، بدون بررسی مالکیت، صفحه‌های offset با اندازه‌ای که کلاینت تعیین می‌کند.

php
<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * The shape many first Laravel APIs take: verbs in the URI, 200 for
 * everything, the model serialized as-is, offset paging, no ownership
 * check, last write wins and a retried POST creates a second order.
 *
 * Route::post('/api/createOrder', [OrderControllerBefore::class, 'create']);
 * Route::get('/api/getOrders', [OrderControllerBefore::class, 'list']);
 * Route::post('/api/updateOrder/{id}', [OrderControllerBefore::class, 'update']);
 */
class OrderControllerBefore
{
    public function create(Request $request): JsonResponse
    {
        // Mass assignment straight from input, no validation.
        $order = Order::create($request->all());

        return response()->json(['success' => true, 'order' => $order]);
    }

    public function list(Request $request): JsonResponse
    {
        // Every column (internal ones too), offset paging, COUNT(*) per page.
        $orders = Order::paginate($request->integer('per_page', 1000));

        return response()->json(['success' => true, 'data' => $orders]);
    }

    public function update(Request $request, int $id): JsonResponse
    {
        $order = Order::find($id);
        if ($order === null) {
            // A "not found" that every cache and client reads as success.
            return response()->json(['success' => false, 'error' => 'not found']);
        }
        $order->update($request->all());

        return response()->json(['success' => true]);
    }
}

After ​

Routeها. Route::apiResource مسیرهای index، store، show، update و destroy را بدون create/edit مخصوص HTML ثبت می‌کند؛ middlewareFor('store', ...) میان‌افزار idempotency را فقط به یک action وصل می‌کند؛ withTrashed(['show']) اجازه می‌دهد سفارش‌های soft-delete شده به show() برسند تا 410 بدهد.

php
<?php

use App\Http\Controllers\OperationController;
use App\Http\Controllers\OrderController;
use App\Http\Middleware\RequireIdempotencyKey;
use Illuminate\Support\Facades\Route;

// bootstrap/app.php loads this file with the "api" prefix, so these are
// /api/orders, /api/orders/{order}, /api/exports and /api/operations/{operation}.
Route::middleware(['auth:sanctum'])->group(function () {
    // index, store, show, update, destroy; no HTML-only create/edit routes.
    // {order} is resolved by Order::getRouteKeyName() (public_id).
    // withTrashed(['show']) lets show() see soft-deleted rows and answer 410.
    Route::apiResource('orders', OrderController::class)
        ->middlewareFor('store', RequireIdempotencyKey::class)
        ->withTrashed(['show']);

    // A state change modelled as a sub-resource, not POST /cancelOrder.
    Route::post('orders/{order}/cancellation', [OrderController::class, 'cancel'])
        ->name('orders.cancel');

    // Long-running work: 202 Accepted + a status resource.
    Route::post('exports', [OperationController::class, 'store'])
        ->middleware([RequireIdempotencyKey::class, 'throttle:exports'])
        ->name('exports.store');
    Route::get('operations/{operation}', [OperationController::class, 'show'])
        ->whereUuid('operation')
        ->name('operations.show');
});

مدل: getRouteKeyName() باعث می‌شود route model binding پارامتر {order} را با public_id مات پیدا کند؛ ستون version منبع ETag است.

php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Order extends Model
{
    use HasFactory, SoftDeletes;

    public const STATUSES = ['pending', 'paid', 'shipped', 'cancelled'];

    private const TRANSITIONS = [
        'pending' => ['paid', 'cancelled'],
        'paid' => ['shipped', 'cancelled'],
        'shipped' => [],
        'cancelled' => [],
    ];

    protected $fillable = ['customer_id', 'total_cents', 'note', 'status'];

    protected $attributes = ['status' => 'pending', 'version' => 1];

    protected static function booted(): void
    {
        // Public, non-guessable identifier; the integer key never leaves the database.
        static::creating(fn (Order $order) => $order->public_id ??= 'ord_'.Str::lower((string) Str::ulid()));
    }

    /** Route model binding resolves {order} by this column. */
    public function getRouteKeyName(): string
    {
        return 'public_id';
    }

    public function etag(): string
    {
        return "{$this->public_id}-v{$this->version}";
    }

    public function canMoveTo(string $status): bool
    {
        return $status === $this->status || in_array($status, self::TRANSITIONS[$this->status] ?? [], true);
    }

    protected function casts(): array
    {
        return ['total_cents' => 'integer', 'version' => 'integer'];
    }
}

Form Requestها. اگر authorize() مقدار false برگرداند پیش از اجرای controller کد 403 می‌آید؛ قاعدهٔ شکست‌خورده 422 می‌دهد. sometimes به‌علاوهٔ nullable معنای JSON Merge Patch را می‌دهد و prohibited عضوهای فقط‌خواندنی را رد می‌کند.

php
<?php

namespace App\Http\Requests;

use App\Models\Order;
use Illuminate\Foundation\Http\FormRequest;

class StoreOrderRequest extends FormRequest
{
    /** A false return becomes 403 before the controller runs. */
    public function authorize(): bool
    {
        return $this->user()->can('create', Order::class);
    }

    /** Failing rules become 422; bootstrap/app.php renders it as Problem Details. */
    public function rules(): array
    {
        return [
            'total_cents' => ['required', 'integer', 'min:1'],
            'note' => ['nullable', 'string', 'max:500'],
        ];
    }
}
php
<?php

namespace App\Http\Requests;

use App\Models\Order;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

/**
 * JSON Merge Patch (RFC 7396) semantics with Laravel rules: "sometimes"
 * means an absent member is left unchanged, "nullable" lets null clear it.
 * Laravel parses application/merge-patch+json because isJson() accepts
 * any Content-Type containing "+json".
 */
class UpdateOrderRequest extends FormRequest
{
    public function authorize(): bool
    {
        // Route model binding already resolved {order}.
        return $this->user()->can('update', $this->route('order'));
    }

    public function rules(): array
    {
        return [
            'status' => ['sometimes', 'required', Rule::in(Order::STATUSES)],
            'note' => ['sometimes', 'nullable', 'string', 'max:500'],
            // Read-only members are rejected, not silently ignored.
            'id' => ['prohibited'],
            'version' => ['prohibited'],
            'total_cents' => ['prohibited'],
        ];
    }
}

API Resource: بازنمایی یک قرارداد است، با sparse fieldsets و پیوندهای وابسته به وضعیت.

php
<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Arr;

/**
 * The representation is a contract, not the table: the integer key, the
 * customer foreign key and deleted_at never leave the server.
 */
class OrderResource extends JsonResource
{
    public const FIELDS = ['id', 'status', 'total_cents', 'note', 'version', 'created_at', 'links'];

    public function toArray(Request $request): array
    {
        $data = [
            'id' => $this->public_id,
            'status' => $this->status,
            'total_cents' => $this->total_cents,
            'note' => $this->note,
            'version' => $this->version,
            'created_at' => $this->created_at?->toIso8601ZuluString(),
            // A little hypermedia: what the client may do next.
            'links' => array_filter([
                'self' => route('orders.show', $this->resource),
                'cancel' => $this->canMoveTo('cancelled') && $this->status !== 'cancelled'
                    ? route('orders.cancel', $this->resource) : null,
            ]),
        ];

        // Sparse fieldsets: ?fields=id,status (validated in the controller).
        $fields = $request->query('fields');

        return is_string($fields) ? Arr::only($data, explode(',', $fields)) : $data;
    }
}

Policy: سفارش دیگران با Response::denyAsNotFound() به 404 می‌رسد؛ نوشتن ability به نام orders:write در Sanctum لازم دارد.

php
<?php

namespace App\Policies;

use App\Models\Order;
use App\Models\User;
use Illuminate\Auth\Access\Response;

class OrderPolicy
{
    public function viewAny(User $user): bool
    {
        return true; // the query is scoped to the user's own orders
    }

    /** Someone else's order answers 404, not 403, so ids cannot be probed. */
    public function view(User $user, Order $order): Response
    {
        return $order->customer_id === $user->id
            ? Response::allow()
            : Response::denyAsNotFound();
    }

    public function create(User $user): bool
    {
        return $user->tokenCan('orders:write');
    }

    public function update(User $user, Order $order): Response
    {
        return $this->view($user, $order)->allowed() && $user->tokenCan('orders:write')
            ? Response::allow()
            : Response::denyAsNotFound();
    }

    public function delete(User $user, Order $order): Response
    {
        return $this->update($user, $order);
    }
}

Controller: cursorPaginate() با فیلتر و مرتب‌سازی مجاز، 201 با Location و ETag، GET شرطی با isNotModified()، If-Match با compare-and-set از راه increment('version', 1, $changes)، 204 برای حذف و 410 پس از آن، لغو به‌عنوان زیرمنبع.

php
<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreOrderRequest;
use App\Http\Requests\UpdateOrderRequest;
use App\Http\Resources\OrderResource;
use App\Models\Order;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Gate;
use Illuminate\Validation\Rule;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
use Symfony\Component\HttpKernel\Exception\GoneHttpException;
use Symfony\Component\HttpKernel\Exception\PreconditionFailedHttpException;
use Symfony\Component\HttpKernel\Exception\PreconditionRequiredHttpException;

class OrderController extends Controller
{
    /** GET /api/orders?status=paid&sort=-created_at&fields=id,status&limit=25&cursor=... */
    public function index(Request $request): AnonymousResourceCollection
    {
        Gate::authorize('viewAny', Order::class);

        $q = $request->validate([
            'status' => ['sometimes', Rule::in(Order::STATUSES)],
            'sort' => ['sometimes', Rule::in(['created_at', '-created_at'])], // allow-list, never raw input
            'fields' => ['sometimes', 'string', function (string $attr, string $value, \Closure $fail) {
                if (array_diff(explode(',', $value), OrderResource::FIELDS) !== []) {
                    $fail('Unknown field in fields.');
                }
            }],
            'limit' => ['sometimes', 'integer', 'between:1,100'],
        ]);
        $dir = ($q['sort'] ?? '-created_at') === '-created_at' ? 'desc' : 'asc';

        // Keyset under the hood: WHERE (created_at, id) < (?, ?) ORDER BY created_at, id.
        // The id tie-breaker makes the order total, so no row is skipped or repeated.
        $orders = Order::query()
            ->where('customer_id', $request->user()->id)
            ->when($q['status'] ?? null, fn ($query, $status) => $query->where('status', $status))
            ->orderBy('created_at', $dir)
            ->orderBy('id', $dir)
            ->cursorPaginate($q['limit'] ?? 25)
            ->withQueryString();

        return OrderResource::collection($orders);
    }

    /** POST /api/orders (RequireIdempotencyKey runs first). */
    public function store(StoreOrderRequest $request): JsonResponse
    {
        $order = Order::create([...$request->validated(), 'customer_id' => $request->user()->id]);

        return $order->toResource(OrderResource::class)
            ->response()
            ->setStatusCode(201)
            ->header('Location', route('orders.show', $order))
            ->setEtag($order->etag());
    }

    /** GET /api/orders/{order}: ETag + If-None-Match gives 304. */
    public function show(Request $request, Order $order): JsonResponse
    {
        Gate::authorize('view', $order);

        if ($order->trashed()) {
            throw new GoneHttpException('This order was deleted.');
        }

        $response = $order->toResource(OrderResource::class)
            ->response()
            ->setEtag($order->etag())
            ->header('Cache-Control', 'private, no-cache');

        $response->isNotModified($request); // turns it into an empty 304 when the tag matches

        return $response;
    }

    /** PATCH /api/orders/{order} with application/merge-patch+json and If-Match. */
    public function update(UpdateOrderRequest $request, Order $order): JsonResponse
    {
        $expected = $this->versionFromIfMatch($request, $order);
        $changes = $request->validated();

        if (isset($changes['status']) && ! $order->canMoveTo($changes['status'])) {
            throw new ConflictHttpException("Cannot move from {$order->status} to {$changes['status']}.");
        }

        // Compare-and-set: UPDATE orders SET ..., version = version + 1
        // WHERE id = ? AND version = ?  -- 0 rows means someone else won.
        $affected = Order::query()
            ->whereKey($order->getKey())
            ->where('version', $expected)
            ->increment('version', 1, $changes);

        if ($affected === 0) {
            throw new PreconditionFailedHttpException('The order changed since you read it.');
        }

        $order->refresh();

        return $order->toResource(OrderResource::class)->response()->setEtag($order->etag());
    }

    /** DELETE /api/orders/{order}: 204, then 410 on later reads. */
    public function destroy(Request $request, Order $order): Response
    {
        Gate::authorize('delete', $order);

        if ($request->hasHeader('If-Match')) {
            $this->versionFromIfMatch($request, $order);
        }
        $order->delete();

        return response()->noContent();
    }

    /** POST /api/orders/{order}/cancellation: repeating it changes nothing. */
    public function cancel(Request $request, Order $order): JsonResponse
    {
        Gate::authorize('update', $order);

        if (! $order->canMoveTo('cancelled')) {
            throw new ConflictHttpException("A {$order->status} order cannot be cancelled.");
        }
        if ($order->status !== 'cancelled') {
            $order->forceFill(['status' => 'cancelled', 'version' => $order->version + 1])->save();
        }

        return $order->toResource(OrderResource::class)->response()->setEtag($order->etag());
    }

    /** 428 when If-Match is missing, 412 when it names another version. */
    private function versionFromIfMatch(Request $request, Order $order): int
    {
        $header = $request->header('If-Match');
        if ($header === null) {
            throw new PreconditionRequiredHttpException('Send the ETag you read in If-Match.');
        }
        $tag = trim($header);
        if ($tag !== '"'.$order->etag().'"') { // strong comparison: W/ tags never match
            throw new PreconditionFailedHttpException('The order changed since you read it.');
        }

        return $order->version;
    }
}

میان‌افزار Idempotency-Key که کلید اصلی جدول قفل آن است:

php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;

/**
 * The Idempotency-Key API contract (IETF draft): 400 without a key, 409
 * while the first request with the key is still running, 422 when the key
 * is reused with another payload, otherwise replay the stored response.
 * The primary key (client_id, idempotency_key) is the lock. Storage design,
 * TTL sweeps and crash recovery: /system-design/api-idempotency.
 */
class RequireIdempotencyKey
{
    private const REPLAYED_HEADERS = ['Content-Type', 'Location', 'ETag'];

    public function handle(Request $request, Closure $next): Response
    {
        $key = trim((string) $request->header('Idempotency-Key'), " \t\"");
        if ($key === '' || strlen($key) > 255) {
            return $this->problem(400, 'idempotency-key-missing', 'Idempotency-Key is missing',
                'This operation requires an Idempotency-Key header (1 to 255 characters).');
        }

        $clientId = (string) ($request->user()?->getAuthIdentifier() ?? $request->ip());
        $fingerprint = hash('sha256', $request->method().' '.$request->path()."\n".$request->getContent());
        $where = ['client_id' => $clientId, 'idempotency_key' => $key];

        try {
            DB::table('idempotency_keys')->insert($where + [
                'fingerprint' => $fingerprint,
                'expires_at' => now()->addDay(),
                'created_at' => now(),
            ]);
        } catch (UniqueConstraintViolationException) {
            $row = DB::table('idempotency_keys')->where($where)->first();

            if ($row->fingerprint !== $fingerprint) {
                return $this->problem(422, 'idempotency-key-reused', 'Idempotency-Key is already used',
                    'The key was used with a different request payload.');
            }
            if ($row->status_code === null) {
                return $this->problem(409, 'idempotency-key-in-flight',
                    'A request is outstanding for this Idempotency-Key', null, ['Retry-After' => '1']);
            }

            return response($row->response_body, $row->status_code,
                json_decode($row->response_headers, true) + ['Idempotent-Replayed' => 'true']);
        }

        $response = $next($request);

        if ($response->getStatusCode() >= 400) {
            // Do not pin a failure to the key: the client may fix the request and retry.
            DB::table('idempotency_keys')->where($where)->delete();

            return $response;
        }

        $headers = [];
        foreach (self::REPLAYED_HEADERS as $name) {
            if ($response->headers->has($name)) {
                $headers[$name] = $response->headers->get($name);
            }
        }
        DB::table('idempotency_keys')->where($where)->update([
            'status_code' => $response->getStatusCode(),
            'response_headers' => json_encode($headers),
            'response_body' => $response->getContent(),
        ]);

        return $response;
    }

    private function problem(int $status, string $kind, string $title, ?string $detail, array $headers = []): Response
    {
        return response()->json(array_filter([
            'type' => "https://api.example.com/problems/{$kind}",
            'title' => $title,
            'status' => $status,
            'detail' => $detail,
        ]), $status, $headers + ['Content-Type' => 'application/problem+json']);
    }
}

Rate limiting: limiterهای نام‌دار در AppServiceProvider، به‌علاوهٔ یک میان‌افزار کوچک که فیلدهای IETF را کنار X-RateLimit-* لاراول اضافه می‌کند:

php
<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        // Used by throttle:api ($middleware->throttleApi() in bootstrap/app.php).
        // Over the limit Laravel answers 429 with Retry-After; bootstrap/app.php
        // turns the ThrottleRequestsException into Problem Details.
        RateLimiter::for('api', function (Request $request) {
            return $request->user()
                ? Limit::perMinute(120)->by('user:'.$request->user()->id)
                : Limit::perMinute(20)->by('ip:'.$request->ip());
        });

        // Expensive endpoints get their own, smaller bucket.
        RateLimiter::for('exports', fn (Request $request) => Limit::perHour(10)->by('user:'.$request->user()?->id));
    }
}
php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Laravel's ThrottleRequests middleware emits X-RateLimit-Limit and
 * X-RateLimit-Remaining (plus Retry-After and X-RateLimit-Reset on 429).
 * This adds the IETF draft fields (draft-ietf-httpapi-ratelimit-headers-12)
 * next to them so standard clients can pace themselves. Register it
 * before throttling in the api group so it sees the throttle headers.
 */
class AddRateLimitFields
{
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);
        $limit = $response->headers->get('X-RateLimit-Limit');
        $remaining = $response->headers->get('X-RateLimit-Remaining');

        if ($limit !== null && $remaining !== null) {
            $response->headers->set('RateLimit-Policy', "api;q={$limit};w=60");
            $retry = $response->headers->get('Retry-After');
            $response->headers->set('RateLimit', "api;a={$remaining}".($retry !== null ? ";w={$retry}" : ''));
        }

        return $response;
    }
}

رندر استثنا به شکل Problem Details برای همهٔ مسیرهای api/*:

php
<?php

use App\Http\Middleware\AddRateLimitFields;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->throttleApi();                       // throttle:api on the api group
        $middleware->prependToGroup('api', AddRateLimitFields::class);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        // Every error under /api/* becomes RFC 9457 Problem Details. By the time
        // this runs Laravel has already mapped ModelNotFoundException to a 404
        // and AuthorizationException to a 403 HttpException.
        $exceptions->render(function (Throwable $e, Request $request) {
            if (! $request->is('api/*')) {
                return null; // keep the default HTML/JSON rendering elsewhere
            }

            [$status, $kind, $extra] = match (true) {
                $e instanceof ValidationException => [422, 'validation', ['errors' => collect($e->errors())
                    ->map(fn (array $messages, string $field) => [
                        'pointer' => '#/'.str_replace('.', '/', $field),
                        'detail' => $messages[0],
                    ])->values()->all()]],
                $e instanceof AuthenticationException => [401, 'unauthenticated', []],
                $e instanceof HttpExceptionInterface => [$e->getStatusCode(), 'http-'.$e->getStatusCode(), []],
                default => [500, 'internal', []],
            };

            $headers = $e instanceof HttpExceptionInterface ? $e->getHeaders() : [];
            if ($status === 401) {
                $headers['WWW-Authenticate'] = 'Bearer';
            }

            return response()->json([
                'type' => "https://api.example.com/problems/{$kind}",
                'title' => Response::$statusTexts[$status] ?? 'Error',
                'status' => $status,
                // Never leak exception messages from 5xx; 4xx messages are ours.
                'detail' => $status < 500 && $e->getMessage() !== '' ? $e->getMessage() : null,
                'instance' => '/'.$request->path(),
                ...$extra,
            ], $status, $headers + ['Content-Type' => 'application/problem+json', 'Cache-Control' => 'no-store']);
        });
    })->create();

خروجی طولانی: 202 با Location، یک queued job، و 303 در پایان.

php
<?php

namespace App\Http\Controllers;

use App\Jobs\ExportOrders;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

/**
 * Long-running operation: POST answers 202 with a status resource;
 * the status resource answers 200 while running and 303 See Other to the
 * result when done.
 */
class OperationController extends Controller
{
    public function store(Request $request): JsonResponse
    {
        $request->validate(['format' => ['required', 'in:csv,jsonl']]);

        $id = (string) Str::uuid();
        DB::table('operations')->insert([
            'id' => $id,
            'user_id' => $request->user()->id,
            'status' => 'running',
            'created_at' => now(),
            'updated_at' => now(),
        ]);
        ExportOrders::dispatch($id, $request->user()->id, $request->input('format'));

        return response()
            ->json(['id' => $id, 'status' => 'running'], 202)
            ->header('Location', route('operations.show', $id))
            ->header('Retry-After', '2');
    }

    public function show(Request $request, string $operation): JsonResponse|RedirectResponse
    {
        $op = DB::table('operations')
            ->where('id', $operation)
            ->where('user_id', $request->user()->id)
            ->first();
        abort_if($op === null, 404);

        if ($op->status === 'succeeded') {
            return redirect()->to($op->result_url, 303);
        }

        return response()
            ->json(['id' => $op->id, 'status' => $op->status, 'error' => $op->error], 200)
            ->header('Retry-After', '2');
    }
}
php
<?php

namespace App\Jobs;

use App\Models\Order;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Throwable;

class ExportOrders implements ShouldQueue
{
    use Queueable;

    public function __construct(
        public string $operationId,
        public int $userId,
        public string $format,
    ) {}

    public function handle(): void
    {
        $path = "exports/{$this->operationId}.{$this->format}";
        $lines = [];
        Order::query()->where('customer_id', $this->userId)->orderBy('id')
            ->lazyById(1000)
            ->each(function (Order $o) use (&$lines) {
                $lines[] = $this->format === 'csv'
                    ? "{$o->public_id},{$o->status},{$o->total_cents}"
                    : json_encode(['id' => $o->public_id, 'status' => $o->status, 'total_cents' => $o->total_cents]);
            });
        Storage::put($path, implode("\n", $lines));
        // temporaryUrl() needs a disk that supports it (S3, or local with 'serve' => true).

        DB::table('operations')->where('id', $this->operationId)->update([
            'status' => 'succeeded',
            'result_url' => Storage::temporaryUrl($path, now()->addHour()),
            'updated_at' => now(),
        ]);
    }

    public function failed(?Throwable $e): void
    {
        DB::table('operations')->where('id', $this->operationId)->update([
            'status' => 'failed',
            'error' => 'export_failed',
            'updated_at' => now(),
        ]);
    }
}

Schema برای سفارش‌ها (ستون version، indexهای keyset، soft delete)، کلیدهای idempotency و operationها:

php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('orders', function (Blueprint $table) {
            $table->id();
            $table->string('public_id', 40)->unique();       // what URIs expose
            $table->foreignId('customer_id')->constrained('users');
            $table->string('status', 16)->default('pending');
            $table->unsignedBigInteger('total_cents');
            $table->string('note', 500)->nullable();
            $table->unsignedInteger('version')->default(1);  // ETag source, optimistic lock
            $table->timestamps();
            $table->softDeletes();                           // deleted rows answer 410
            // Keyset pagination: filter, then the sort key plus a unique tie-breaker.
            $table->index(['customer_id', 'status', 'created_at', 'id']);
            $table->index(['customer_id', 'created_at', 'id']);
        });

        Schema::create('idempotency_keys', function (Blueprint $table) {
            $table->string('client_id', 64);
            $table->string('idempotency_key', 255);
            $table->char('fingerprint', 64);
            $table->unsignedSmallInteger('status_code')->nullable(); // null = still running
            $table->json('response_headers')->nullable();
            $table->longText('response_body')->nullable();
            $table->timestamp('expires_at')->index();
            $table->timestamp('created_at');
            $table->primary(['client_id', 'idempotency_key']);        // the lock
        });

        Schema::create('operations', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->foreignId('user_id')->constrained();
            $table->string('status', 16);                             // running | succeeded | failed
            $table->text('result_url')->nullable();
            $table->string('error', 64)->nullable();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('operations');
        Schema::dropIfExists('idempotency_keys');
        Schema::dropIfExists('orders');
    }
};

Feature test برای 201/بازپخش/422، Problem Details، 428/412 و 404/410:

php
<?php

namespace Tests\Feature;

use App\Models\Order;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

class OrderApiTest extends TestCase
{
    use RefreshDatabase;

    public function test_create_is_201_with_location_and_replays_on_retry(): void
    {
        Sanctum::actingAs(User::factory()->create(), ['orders:write']);
        $headers = ['Idempotency-Key' => '"k-1"'];

        $first = $this->postJson('/api/orders', ['total_cents' => 4999], $headers)
            ->assertCreated()
            ->assertHeader('Location')
            ->assertHeader('ETag');

        $this->postJson('/api/orders', ['total_cents' => 4999], $headers)
            ->assertCreated()
            ->assertHeader('Idempotent-Replayed', 'true')
            ->assertJsonPath('data.id', $first->json('data.id'));

        $this->postJson('/api/orders', ['total_cents' => 1], $headers)->assertStatus(422);
        $this->assertSame(1, Order::count());
    }

    public function test_validation_errors_are_problem_details(): void
    {
        Sanctum::actingAs(User::factory()->create(), ['orders:write']);

        $this->postJson('/api/orders', ['total_cents' => 0], ['Idempotency-Key' => '"k-2"'])
            ->assertStatus(422)
            ->assertHeader('Content-Type', 'application/problem+json')
            ->assertJsonPath('errors.0.pointer', '#/total_cents');
    }

    public function test_patch_needs_if_match_and_rejects_a_stale_etag(): void
    {
        $user = User::factory()->create();
        Sanctum::actingAs($user, ['orders:write']);
        $order = Order::create(['customer_id' => $user->id, 'total_cents' => 100]);
        $uri = "/api/orders/{$order->public_id}";
        $merge = ['CONTENT_TYPE' => 'application/merge-patch+json'];
        $body = json_encode(['status' => 'paid']);

        $this->call('PATCH', $uri, [], [], [], $merge, $body)->assertStatus(428);

        $this->call('PATCH', $uri, [], [], [], $merge + ['HTTP_IF_MATCH' => '"'.$order->etag().'"'], $body)
            ->assertOk()
            ->assertJsonPath('data.version', 2);

        // Same old ETag again: someone (we) already moved it to version 2.
        $this->call('PATCH', $uri, [], [], [], $merge + ['HTTP_IF_MATCH' => '"'.$order->etag().'"'], $body)
            ->assertStatus(412);
    }

    public function test_someone_elses_order_is_404_and_deleted_is_410(): void
    {
        $owner = User::factory()->create();
        $order = Order::create(['customer_id' => $owner->id, 'total_cents' => 100]);

        Sanctum::actingAs(User::factory()->create(), ['orders:write']);
        $this->getJson("/api/orders/{$order->public_id}")->assertNotFound();

        Sanctum::actingAs($owner, ['orders:write']);
        $this->deleteJson("/api/orders/{$order->public_id}")->assertNoContent();
        $this->getJson("/api/orders/{$order->public_id}")->assertStatus(410);
    }
}

نگاه Laravel ​

قابلیت Laravel 13کاربردنکته
Route::apiResource() / apiResources()پنج مسیر REST برای هر منبعcreate و edit را حذف می‌کند
->shallow()، ->scoped()، scopeBindings()منبع‌های تودرتوbinding فرزند به والد محدود می‌شود
->middlewareFor()، ->withTrashed()میان‌افزار برای هر action، binding رکورد soft-deleteدر ثبت resource route
Route model binding، getRouteKeyName(){order} با public_idمدل غایب 404 می‌شود
Form Request (make:request)authorize() یعنی 403، rules() یعنی 422فقط $request->validated()
API Resource (JsonResource، toResource())لایهٔ بازنماییwhenLoaded() جلوی N+1 را می‌گیرد
JsonApiResourceJSON:API با sparse fieldsets و includeapplication/vnd.api+json را تنظیم می‌کند
Policy، Gate::authorize()، Response::denyAsNotFound()مجوزدهی در سطح شیءAuthorizationException به 403 تبدیل می‌شود
cursorPaginate()، simplePaginate()، paginate()keyset در برابر offsetcursor به orderBy نیاز دارد
RateLimiter::for()، Limit::perMinute()->by()، throttle:rate limiting429 خودکار؛ $middleware->throttleApi()
میان‌افزار cache.headersCache-Control و ETagدستور etag مدیریت 304 را اضافه می‌کند
$exceptions->render()، shouldRenderJsonWhen()Problem Detailsپس از نگاشت model-not-found به 404 توسط Laravel اجرا می‌شود
response()->noContent()204—

حل مسئله‌های کلاسیک ​

سفارش دوتایی پس از timeout ​

راه‌حلچطورمزیتهزینه
Idempotency-Keyکلید کلاینت برای هر عملیات، سرور بازپخش می‌کنددقیقاً همان پاسخ اول، اثرهای جانبی را هم می‌پوشاندیک store با TTL
شناسه به انتخاب کلاینت + PUTPUT /orders/{uuid}با تعریف متد idempotent استکلاینت باید شناسه بسازد
unique constraint طبیعیUNIQUE(customer_id, cart_id)جدول اضافه لازم نیستretry خطا می‌گیرد نه نتیجهٔ اصلی

ترجیح: Idempotency-Key (Go، Laravel)؛ سازوکار ذخیره در API Idempotency.

lost update بین دو ویرایشگر ​

راه‌حلچطورمزیتهزینه
ETag + If-Match412 برای نوشتن کهنه، 428 بدون آناستاندارد، از proxy هم عبور می‌کندکلاینت باید ETag را نگه دارد
version در بدنه (Kubernetes، AIP-154)فیلد version/etagدر بدنهٔ دسته‌ای هم کار می‌کندبرای ابزار HTTP دیده نمی‌شود
endpoint قفل بدبینانهPOST /docs/7/lockبرای انسان ساده استانقضا و رها شدن قفل
sql
-- What If-Match becomes in the database (the Laravel increment() call generates this shape)
UPDATE orders
SET status = 'paid', version = version + 1, updated_at = now()
WHERE id = 7 AND version = 1;     -- 0 rows affected -> 412 Precondition Failed

صفحه‌هایی که ردیف جا می‌اندازند یا تکرار می‌کنند ​

راه‌حلچطورمزیتهزینه
cursor از نوع keyset(کلید مرتب‌سازی، id) در cursor ماتپایدار، سریع در هر عمقیپرش تصادفی به صفحه ندارد
token snapshotcursor یک زمان snapshot را ثابت می‌کند (as_of)نمای سازگارتاریخچه یا خواندن MVCC لازم دارد
offset با مرتب‌سازی پایدارORDER BY created_at, idشمارهٔ صفحهباز هم زیر نوشتن جابه‌جا می‌شود و در عمق کند است

خطاهایی که هیچ‌کس نمی‌تواند مدیریتشان کند ​

راه‌حلچطورمزیتهزینه
Problem Details همه‌جایک helper در هر stack، gateway همیک parser برای کلاینت‌هامهاجرت از شکل‌های قدیمی
URIهای type پایدارکاتالوگ مستندکلاینت روی آن تصمیم می‌گیردنباید تغییر کند
اشاره‌گر فیلدerrors[].pointerفرم خطا را به فیلد نگاشت می‌کندextension که باید مستند شود

endpoint کندی که در gateway به timeout می‌خورد ​

راه‌حلچطورمزیتهزینه
202 + منبع وضعیتصف، poll، 303 به نتیجهاز timeout کلاینت و gateway جان سالم به در می‌بردstore برای job، پاک‌سازی
webhook در پایانcallback با امضاpoll لازم نیستکلاینت باید endpoint داشته باشد
پاسخ جریانیchunked یا SSEپیشرفت دیده می‌شوداتصال باز می‌ماند

کلاینت‌هایی که API را می‌کوبند ​

راه‌حلچطورمزیتهزینه
RateLimit + 429 + Retry-Afterسهمیهٔ هر کلاینت، هدرهای پیداکلاینت خودش را تنظیم می‌کندstore مشترک برای شمارنده
هدرهای کشETag، max-ageبار را کلاً حذف می‌کندکهنگی
endpoint bulkیک درخواست برای چندین قلمرفت‌وبرگشت کمترطراحی شکست جزئی

انتخاب ​

وضعیتپیشنهادتکنیک اضافهدلیل
API عمومی، کلاینت‌های ناشناس زیادREST سطح ۲، OpenAPI 3.1، Problem Detailsراهنمای سبک + lint، صفحه‌بندی cursorابزار، کش و SDK کار می‌کنند
ارتباط داخلی سرویس‌به‌سرویس با حجم بالاgRPC یا RESTببینید gRPCقرارداد باینری، جریان
UI که در هر صفحه چندین موجودیت را جمع می‌کندREST + BFF یا GraphQLببینید GraphQLپرهیز از over/under-fetching
پرداخت، سفارش، هر چیزی با پولPOST + Idempotency-Key، If-Match روی updateoutbox برای رویدادها (Outbox)retry قطعی است
ویرایش مشترکPATCH + If-Match، 412test در JSON Patch برای بررسی سطح فیلدوگرنه lost update بی‌صداست
کار بزرگ یا کند202 + منبع وضعیتwebhook، URL امضاشده برای نتیجههیچ درخواستی نباید دقیقه‌ها طول بکشد
فهرست‌هایی که رشد می‌کنندصفحه‌بندی cursor (keyset)فیلتر داخل cursorپایدار و متناسب با اندازهٔ صفحه
جدول مدیریتی با شمارهٔ صفحه، دادهٔ کمصفحه‌بندی offsetشمارش کلUI ساده‌تر
دادهٔ عمومی پرخواندنیهدرهای کش + CDNs-maxage، stale-while-revalidateبیشتر درخواست‌ها هرگز به شما نمی‌رسند
کلاینت‌های عمر طولانی و گردش کار متغیرافزودن پیوندهای ابررسانه‌ای (بخش‌هایی از سطح ۳)پیوند عمل وابسته به وضعیتسرور بدون انتشار کلاینت تکامل می‌یابد

در معماری: از یک پروسه تا سیستم توزیع‌شده ​

همان قرارداد API باید با ماشین‌های بیشتر و بیشتر پشتش زنده بماند. چیزی که عوض می‌شود این است که حالت کجا زندگی می‌کند، چه کسی می‌تواند به درخواست جواب دهد و کدام تضمین‌ها هنوز برقرارند.

Monolith: یک پروسه، یک پایگاه داده ​

یک monolith در Laravel یا Go مستقیم از پایگاه داده‌اش /api/orders را عرضه می‌کند. ETag از ستون version می‌آید، کلیدهای idempotency از جدولی در همان پایگاه داده (پس «گرفتن کلید، درج سفارش، ذخیرهٔ پاسخ» می‌تواند یک تراکنش باشد)، و cursor از یک index. ساده‌ترین چیدمان درست: apiResource، Form Request، Policy، cursorPaginate()، رندر Problem Details و throttle:api. همهٔ آنچه در این صفحه آمد در یک پروسه جا می‌شود.

Modular monolith: مرزها داخل یک deployable ​

Orders، Billing و Catalog ماژول‌هایی با جدول‌های خودشان هستند. API عمومی هنوز یکی است، اما هر ماژول منبع‌های خودش (/orders، /invoices، /products) و تکهٔ OpenAPI خودش را دارد؛ یک پشتهٔ میان‌افزار مشترک Problem Details، rate limit و idempotency را فراهم می‌کند. قاعده: هیچ ماژولی از راه لایهٔ API به جدول ماژول دیگر نمی‌نویسد؛ کارهای بین‌ماژولی فراخوانی داخلی یا رویدادند، نه HTTP به خودتان.

Microservices: هر پیکان یک API است ​

text
     Mobile app        API gateway (Envoy/Kong)       orders-svc                billing-svc
1    POST /orders  ->  auth, RateLimit, 429           -> POST /orders  Idempotency-Key k1
2                                                      claim k1, insert order, outbox OrderPlaced
3                                                      201 Location /orders/ord_7
4                                                      relay -> broker                 consumes, charges
5    GET /orders/ord_7 -> gateway -> orders-svc -> 200 {"status":"paid", "links":{...}}

آنچه از مرز عبور می‌کند: کدهای وضعیت، Problem Details، Idempotency-Key (آن را جلو بفرستید یا کلیدهای فرزند مثل k1:charge بسازید) و ETag هر سرویس. آنچه عبور نمی‌کند: تراکنشی که orders و billing را با هم بپوشاند؛ پس سازگاری بین سرویس‌ها از saga و outbox می‌آید و API آن را صادقانه نشان می‌دهد (status: pending، 202، یا پیوند وضعیت). gateway و BFF در API Gateway, BFF & Service Mesh آمده‌اند.

دادهٔ توزیع‌شده: replica، کش، منطقه ​

  • Read replica: کلاینت سفارشی می‌سازد (201) و بلافاصله آن را از replicaای عقب‌مانده GET می‌کند و 404 می‌گیرد. راه‌حل: read-your-writes با فرستادن خواندن‌های پس از نوشتن به primary برای چند ثانیه، یا برگرداندن بازنمایی کامل در 201 تا کلاینت لازم نباشد بخواند. ببینید Replication Topologies.
  • کش و CDN: private در برابر public، Vary، و ETagهایی که از ستون version می‌آیند تا همهٔ گره‌ها یک برچسب حساب کنند. نقطهٔ ضعف: ETagی که از hash درون پروسه ساخته شود بین گره‌ها فرق می‌کند و 304 را می‌شکند.
  • Idempotency بین منطقه‌ها: retry ممکن است در منطقهٔ دیگری فرود آید؛ store کلیدها باید سراسری باشد یا کلیدها به منطقه وابسته شوند. جزئیات در API Idempotency.
  • Rate limit بین نمونه‌ها: شمارندهٔ درون پروسه حد را در تعداد نمونه‌ها ضرب می‌کند؛ از Redis یا gateway استفاده کنید (Rate Limiting).

مسیر مقیاس: 1x، 10x، 100x ​

بارچه چیزی در API عوض می‌شودچه چیزی پشت آن عوض می‌شود
1x (صدها درخواست در ثانیه)Contract-first، Problem Details، صفحه‌بندی cursor، Idempotency-Keyیک برنامه، یک پایگاه داده
10x (هزاران درخواست در ثانیه)هدر کش روی خواندن‌ها، هدرهای RateLimit، endpoint bulk برای کلاینت‌های سنگینCDN، Redis برای limit و کلید، read replica، گره‌های بی‌حالت بیشتر
100x (ده‌ها هزار درخواست در ثانیه و بیشتر)202 برای هر کار سنگین، webhook به‌جای poll، حد سخت‌تر برای هر سطح، قرارداد نسخه‌دار برای هر بخش از کلاینت‌هاgateway در جلو، API برای هر سرویس، دادهٔ shard شده (Sharding)، استقرار منطقه‌ای

آزمایشگاه: سرویس Go با curl ​

سرور Go یک پروسهٔ تنها با store درون حافظه است، پس این آزمایشگاه روی همین ماشین با go run ./cmd/server اجرا شد (toolchain نسخهٔ Go 1.27، دستور ماژول go 1.24)؛ خروجی‌های زیر از همان اجراست و هدرهای Date حذف شده‌اند. گام‌های Laravel در انتها «خروجی موردانتظار؛ اجرا نشده» هستند.

آماده‌سازی

bash
cd docs/snippets/system-design/rest-api-design/go
go test ./...                 # ok  academy/rest-api-design/orders
go run ./cmd/server           # listening on 127.0.0.1:8080

۱. ساختن، سپس retry با همان کلید (بازپخش)، سپس استفادهٔ دوباره از کلید با بدنهٔ دیگر (422).

text
$ curl -si -X POST localhost:8080/orders -H 'Content-Type: application/json' \
    -H 'Idempotency-Key: "8e03978e-40d5-43e8-bc93-6894a57f9324"' -d '{"customer":"c-42","total_cents":4999}'
HTTP/1.1 201 Created
Content-Type: application/json
Etag: "ord_000001-v1"
Location: /orders/ord_000001
Ratelimit: default;a=99;w=60
Ratelimit-Policy: default;q=100;w=60

{"id":"ord_000001","customer":"c-42","status":"pending","total_cents":4999,"note":null,"version":1,...}

$ (same command again)
HTTP/1.1 201 Created
Etag: "ord_000001-v1"
Idempotent-Replayed: true
Location: /orders/ord_000001

$ (same key, "total_cents":1)
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/problem+json
{"type":"https://api.example.com/problems/idempotency-key-reused","title":"Idempotency-Key is already used","status":422,...}

متن وضعیت در Go هنوز "Unprocessable Entity" است؛ RFC 9110 نام 422 را به "Unprocessable Content" تغییر داد. کلاینت باید عدد را بخواند، نه متن را.

۲. GET شرطی و پروتکل جلوگیری از lost update.

text
$ curl -si localhost:8080/orders/ord_000001 -H 'If-None-Match: "ord_000001-v1"'
HTTP/1.1 304 Not Modified
Cache-Control: private, no-cache
Etag: "ord_000001-v1"

$ curl -si -X PATCH localhost:8080/orders/ord_000001 -H 'Content-Type: application/merge-patch+json' -d '{"status":"paid"}'
HTTP/1.1 428 Precondition Required
Accept-Patch: application/merge-patch+json, application/json-patch+json
{"type":"https://api.example.com/problems/precondition-required","title":"If-Match required",...}

$ curl -si -X PATCH ... -H 'If-Match: "ord_000001-v1"' -d '{"status":"paid"}'
HTTP/1.1 200 OK
Etag: "ord_000001-v2"

$ curl -si -X PATCH ... -H 'If-Match: "ord_000001-v1"' -d '{"customer":"bob"}'
HTTP/1.1 412 Precondition Failed
{"type":"https://api.example.com/problems/stale-etag","title":"Precondition failed","status":412,
 "detail":"The order changed since you read it. GET it again, reapply your change, retry with the new ETag.",...}

۳. خطای 405 با mux نسخهٔ Go 1.22 رایگان است.

text
$ curl -si -X PUT localhost:8080/orders/ord_000001 -d '{}'
HTTP/1.1 405 Method Not Allowed
Allow: DELETE, GET, HEAD, PATCH
Content-Type: text/plain; charset=utf-8

۴. صفحه‌های cursor با sparse fieldsets (پس از ساختن پنج سفارش).

text
$ curl -si 'localhost:8080/orders?limit=2&fields=id,status'
HTTP/1.1 200 OK
Link: </orders?cursor=eyJhIjoib3JkXzAwMDAwMiJ9&fields=id%2Cstatus&limit=2>; rel="next"
{"data":[{"id":"ord_000001","status":"pending"},{"id":"ord_000002","status":"pending"}],"next_cursor":"eyJhIjoib3JkXzAwMDAwMiJ9"}

$ curl -si 'localhost:8080/orders?limit=2&fields=id,status&cursor=eyJhIjoib3JkXzAwMDAwMiJ9'
{"data":[{"id":"ord_000003","status":"pending"},{"id":"ord_000004","status":"pending"}],"next_cursor":"eyJhIjoib3JkXzAwMDAwNCJ9"}

cursor را decode کنید (echo eyJhIjoib3JkXzAwMDAwMiJ9 | base64 -d خروجی {"a":"ord_000002"} می‌دهد): همان آخرین id است و به همین دلیل پایدار است. APIهای واقعی آن را امضا یا رمز می‌کنند تا کلاینت با آن مثل رشته‌ای مات رفتار کند.

۵. خروجی طولانی: 202، سپس 200 تا وقتی اجرا می‌شود، سپس 303.

text
$ curl -si -X POST 'localhost:8080/exports?format=csv' -H 'Idempotency-Key: "e1"'
HTTP/1.1 202 Accepted
Location: /operations/op_1
Retry-After: 1
{"id":"op_1","status":"running"}

$ curl -si localhost:8080/operations/op_1
HTTP/1.1 200 OK
Retry-After: 1
{"id":"op_1","status":"running"}

$ curl -si localhost:8080/operations/op_1     # 300 ms later
HTTP/1.1 303 See Other
Location: /exports/exp_1

۶. دو بار حذف، و قرارداد خطا.

text
$ curl -si -X DELETE localhost:8080/orders/ord_000005     ->  HTTP/1.1 204 No Content
$ curl -si -X DELETE localhost:8080/orders/ord_000005     ->  HTTP/1.1 410 Gone (application/problem+json)
$ curl -si -X POST localhost:8080/orders -H 'Content-Type: application/json' -d '{}'
HTTP/1.1 400 Bad Request
{"type":"https://api.example.com/problems/idempotency-key-missing","title":"Idempotency-Key is missing",...}
$ curl -si -X POST localhost:8080/orders -H 'Content-Type: application/json' -H 'Idempotency-Key: "v1"' \
    -d '{"customer":"","total_cents":0}'
HTTP/1.1 422 Unprocessable Entity
{"type":".../validation","title":"Validation failed","status":422,"instance":"/orders",
 "errors":[{"pointer":"#/customer","detail":"is required"},{"pointer":"#/total_cents","detail":"must be greater than 0"}]}

۷. Laravel («خروجی موردانتظار؛ اجرا نشده»). در یک برنامهٔ Laravel 13 با Sanctum، پس از کپی کردن snippetها و اجرای php artisan migrate:

text
$ php artisan route:list --path=api
  GET|HEAD   api/orders ................. orders.index   › OrderController@index
  POST       api/orders ................. orders.store   › OrderController@store
  GET|HEAD   api/orders/{order} ......... orders.show    › OrderController@show
  PUT|PATCH  api/orders/{order} ......... orders.update  › OrderController@update
  DELETE     api/orders/{order} ......... orders.destroy › OrderController@destroy
  POST       api/orders/{order}/cancellation  orders.cancel
  POST       api/exports ................ exports.store
  GET|HEAD   api/operations/{operation} . operations.show
$ php artisan test --filter=OrderApiTest
  PASS  Tests\Feature\OrderApiTest   (4 tests)

توجه کنید که apiResource برای update هم PUT و هم PATCH را ثبت می‌کند؛ این controller با هر دو مثل merge patch رفتار می‌کند. اگر می‌خواهید PUT به معنای جایگزینی کامل باشد، update را فقط برای PATCH ثبت کنید و یک action جدا به نام replace اضافه کنید.

بدفهمی‌های رایج ​

باورواقعیت
REST یعنی JSON و URL زیباREST شش قید است؛ بیشتر APIهای JSON در سطح ۲ مدل Richardson هستند
Stateless یعنی بدون پایگاه دادهحالت نشست سمت سرور بین درخواست‌ها را ممنوع می‌کند، نه حالت منبع را
PUT یعنی update، POST یعنی createPUT در URIای که کلاینت می‌داند ذخیره می‌کند (و می‌تواند بسازد)؛ POST تصمیم را به سرور می‌سپارد
Idempotent یعنی پاسخ یکسانیعنی اثر موردنظر یکسان؛ DELETE دوم ممکن است 404/410 بگیرد
PATCH با شیء JSON جزئی استاندارد استقالب‌های استاندارد application/merge-patch+json و application/json-patch+json هستند
401 و 403 قابل جایگزینی‌اند401 یعنی «کیستی» (با WWW-Authenticate)؛ 403 یعنی شناخته‌شده ولی بی‌اجازه
409 کد ETag کهنه استIf-Match کهنه 412 است؛ 409 تعارض وضعیت است
no-cache کش را ممنوع می‌کندیعنی پیش از استفاده دوباره اعتبارسنجی کن؛ no-store ذخیره را ممنوع می‌کند
202 یعنی موفقیتیعنی پذیرفته شد؛ نتیجه در منبع وضعیت است
unique constraint، POST را idempotent می‌کندجلوی تکراری را می‌گیرد اما پاسخ اصلی را بازپخش نمی‌کند و اثرهای جانبی را نمی‌پوشاند
صفحه‌بندی cursor فقط یک شمارهٔ صفحهٔ دیگر استنشانکی از کلید مرتب‌سازی است؛ زیر نوشتن پایدار و در عمق ارزان
بدون ابررسانهٔ سطح ۳ API بی‌فایده استسطح ۲ کش، retry و ابزار می‌دهد؛ جایی پیوند بگذارید که کلاینت بر اساس وضعیت تصمیم می‌گیرد
X-RateLimit-* استاندارد استفقط قرارداد است؛ پیش‌نویس IETF فیلدهای RateLimit-Policy و RateLimit را تعریف می‌کند

چکیده (Cheat sheet) ​

موضوعبه خاطر بسپارید
قیدهاClient-server، stateless، cacheable، uniform interface (۴ بخش)، layered، code on demand (اختیاری)
متدهای safeGET، HEAD، OPTIONS، TRACE
متدهای idempotentمتدهای safe + PUT + DELETE؛ POST و PATCH نیستند
ساختنPOST به مجموعه، 201 + Location + ETag؛ PUT وقتی کلاینت شناسه را انتخاب می‌کند
تغییر جزئیPATCH با application/merge-patch+json (null حذف می‌کند) یا JSON Patch (test برای پیش‌شرط)
هم‌روندیETag هنگام خواندن، If-Match هنگام نوشتن، 412 برای کهنه، 428 برای غایب
POST قابل retryIdempotency-Key: "uuid"؛ 400 غایب، 409 در حال اجرا، 422 تکراری، در غیر این صورت بازپخش
اعتبارسنجی در برابر نحو422 در برابر 400؛ 415 برای media type نادرست
خطاهاapplication/problem+json با type، title، status، detail، instance
صفحه‌بندیcursor مات از (کلید مرتب‌سازی، id)، Link: rel="next"، سقف برای limit
طراحی queryفیلتر و مرتب‌سازی مجاز، fields= برای sparse fieldsets، index برای هر ترکیب
کار طولانی202 + Location به منبع وضعیت، Retry-After، 303 به نتیجه
rate limit429 + Retry-After؛ RateLimit-Policy و RateLimit (پیش‌نویس)
کشprivate, no-cache + ETag برای دادهٔ کاربر؛ public, s-maxage برای دادهٔ مشترک؛ no-store برای خطا
قرارداداول OpenAPI 3.1، lint با Spectral، مقایسه در CI، تولید کلاینت
راهنمای سبکGoogle AIP، Microsoft یا Zalando را بپذیرید؛ استثناها را بنویسید

خودآزمایی: پرسش و پاسخ ​

نمایش:
  • حیاتی تقریباً در هر مصاحبه پرسیده می‌شود
  • مهم پرتکرار؛ در سطح senior انتظار می‌رود
  • تکمیلی عمق بیشتر؛ تمایز ایجاد می‌کند

۱ — شش قید Fielding را نام ببرید و بگویید کدام اختیاری است. حیاتی ​

پاسخ

پاسخ: Client-server، stateless، cacheable، uniform interface، layered system، code on demand؛ code on demand اختیاری است. ببینید قیدها.

۲ — سروری نتیجهٔ جست‌وجوی کاربر را در حافظهٔ پروسه نگه می‌دارد و ?page=2 را از آن برمی‌گرداند. کدام قید شکسته شده و چه نشانهٔ عملیاتی خواهید دید؟ حیاتی ​

پاسخ

پاسخ: Stateless: درخواست دوم به contextی وابسته است که روی سرور پاسخ‌دهندهٔ درخواست اول مانده. نشانه‌ها: نیاز به sticky session، صفحه‌های اشتباه یا گم‌شده پس از deploy یا failover، بار نامتوازن. به‌جایش موقعیت را در cursor بگذارید.

۳ — اگر فراخوانی دوم DELETE /orders/7 به‌جای 204، 410 برگرداند، آیا هنوز idempotent است؟ چرا؟ حیاتی ​

پاسخ

پاسخ: بله. idempotency دربارهٔ اثر موردنظر روی سرور است (سفارش حذف شده)، نه پاسخ یکسان. ببینید متدها.

۴ — کلاینت PATCH {"note": null} می‌فرستد. این در JSON Merge Patch چه معنایی دارد، و «status را فقط اگر هنوز pending است عوض کن» را چطور بیان می‌کنید؟ مهم ​

پاسخ

پاسخ: در Merge Patch یعنی note را حذف کن. تغییر شرطی به JSON Patch نیاز دارد: [{"op":"test","path":"/status","value":"pending"},{"op":"replace","path":"/status","value":"paid"}]، به‌علاوهٔ If-Match برای کل منبع. ببینید قالب‌های PATCH.

۵ — کد وضعیت را انتخاب کنید: (الف) JSON سالم اما total_cents منفی؛ (ب) بدنه text/plain است؛ (ج) If-Match کهنه است؛ (د) If-Match نیامده اما سرور آن را الزامی می‌داند؛ (ه) سفارش ارسال‌شده به pending برگردانده می‌شود. حیاتی ​

پاسخ

پاسخ: (الف) 422، (ب) 415، (ج) 412، (د) 428، (ه) 409. ببینید کدهای وضعیت.

۶ — چرا صفحه‌بندی offset زیر درج هم‌زمان تکراری نشان می‌دهد، و cursor از نوع keyset چه چیزی در خود دارد؟ حیاتی ​

پاسخ

پاسخ: ردیف‌های تازه همهٔ offsetهای بعدی را جابه‌جا می‌کنند، پس صفحهٔ بعد یک ردیف زودتر شروع می‌شود و یکی را تکرار می‌کند. cursor از نوع keyset کلید مرتب‌سازی و id یکتای آخرین ردیف (به‌علاوهٔ فیلترها) را نگه می‌دارد و query بعدی WHERE (created_at, id) < (...) است. ببینید صفحه‌بندی.

۷ — درخواست POST /payments شما timeout شد. کلاینت در حالی که درخواست اول هنوز اجرا می‌شود با همان Idempotency-Key دوباره تلاش می‌کند. چه باید بگیرد، و پس از پایان درخواست اول چه؟ حیاتی ​

پاسخ

پاسخ: 409 (درخواست در جریان)، ترجیحاً با Retry-After؛ پس از پایان، بازپخش پاسخ اصلی (مثلاً همان بدنهٔ 201). اگر بدنه فرق کند، 422. ببینید کلید idempotency.

۸ — چرا بیشتر APIهای عمومی در سطح ۲ Richardson می‌مانند، و یک قدم ارزان به سمت سطح ۳ چیست؟ تکمیلی ​

پاسخ

پاسخ: کلاینت‌ها از OpenAPI تولید می‌شوند و URIها را hard-code می‌کنند، JSON استاندارد پیوند واحدی ندارد و سودش به کلاینت‌هایی نیاز دارد که دنبال پیوند بروند. قدم ارزان: Link: rel="next"، Location و پیوندهای عمل وابسته به وضعیت مثل cancel. ببینید ابررسانه.

۹ — تفاوت Cache-Control: no-cache و no-store چیست، و برای GET /me کدام را به کار می‌برید؟ حیاتی ​

پاسخ

پاسخ: no-cache ذخیره را مجاز می‌داند اما اعتبارسنجی دوباره می‌خواهد؛ no-store ذخیره را ممنوع می‌کند. برای GET /me: private, no-cache با ETag (یا no-store اگر راز دارد). ببینید کش.

۱۰ — یک خروجی ۴ دقیقه طول می‌کشد. تبادل HTTP را طراحی کنید. حیاتی ​

پاسخ

پاسخ: POST /exports با Idempotency-Key → 202 Accepted، Location: /operations/{id}، Retry-After؛ poll کردن GET /operations/{id} → 200 با running → 303 See Other به نتیجه (یا succeeded با پیوند)؛ در صورت تمایل webhook. ببینید عملیات طولانی.

۱۱ — سه چیز را نام ببرید که گردش کار contract-first با OpenAPI می‌گیرد و code-first نمی‌گیرد. مهم ​

پاسخ

پاسخ: تغییر شکنندهٔ تصادفی (مقایسه در CI)، نقض راهنمای سبک پیش از وجود کد (lint)، و پاسخ‌های خطا یا هدرهای جاافتاده در بازبینی؛ همچنین کار frontend می‌تواند روی mock شروع شود. ببینید OpenAPI.

۱۲ — کاربر ۴۲ منبع /orders/ord_8 را می‌خواهد که مال کاربر ۷ است. 403 یا 404، و Laravel چطور بیانش می‌کند؟ حیاتی ​

پاسخ

پاسخ: معمولاً 404، تا وجود شناسه‌ها قابل کاوش نباشد؛ در Laravel یک policy مقدار Response::denyAsNotFound() برمی‌گرداند. ببینید مبانی امنیت.

واژه‌نامه ​

واژهمعنا
RESTRepresentational State Transfer، سبک معماری Fielding: شش قید
قیدهای Fielding (Fielding constraints)Client-server، stateless، cacheable، uniform interface، layered system، code on demand
بی‌حالت (Stateless)هر درخواست همهٔ اطلاعات لازم را دارد؛ context نشست سمت سرور نیست
قابل کش (Cacheable)پاسخ‌ها خودشان را قابل استفادهٔ دوباره یا غیرقابل برچسب می‌زنند
رابط یکنواخت (Uniform interface)همان متدها، کدها و media typeها برای همهٔ منبع‌ها: شناسایی، بازنمایی، پیام خودتوصیف، HATEOAS
سیستم لایه‌ای (Layered system)هر جزء فقط لایهٔ کناری را می‌بیند؛ proxy، CDN و gateway ممکن می‌شوند
Code on demandقید اختیاری: سرور کد اجرایی می‌فرستد
HATEOASHypermedia as the engine of application state: کلاینت دنبال پیوندها می‌رود
مدل بلوغ Richardson (Richardson maturity model)سطح 0 (تونل)، 1 (منبع)، 2 (فعل و کد)، 3 (ابررسانه)
منبع (Resource)هر چیزی که می‌شود نامش گذاشت و URI دارد
مجموعه (Collection)منبعی که اعضا را فهرست می‌کند و می‌سازد، مثل /orders
زیرمنبع (Sub-resource)منبعی که فقط از راه والد در دسترس است، مثل /orders/7/items
طراحی URI (URI design)قواعد نام‌گذاری: اسم جمع، بدون فعل، شناسهٔ مات، تودرتویی کم‌عمق
بازنمایی (Representation)حالت منبع در یک media type
Media typeبرچسب type/subtype مثل application/json، application/problem+json
Content negotiationسرور بازنمایی را با Accept و هم‌خانواده‌هایش انتخاب می‌کند؛ Vary آن را ثبت می‌کند
متد امن (Safe method)معنای فقط‌خواندنی: GET، HEAD، OPTIONS، TRACE
متد idempotentتکرار همان اثر موردنظر را دارد: متدهای safe، PUT، DELETE
GET / HEAD / OPTIONSخواندن؛ فقط خواندن هدرها؛ پرسیدن قابلیت‌ها
POST / PUT / PATCH / DELETEپردازش یا ساختن؛ جایگزینی در URI؛ تغییر جزئی؛ حذف
JSON Patchفهرست عملیات RFC 6902 (test، add، remove، replace، move، copy)
JSON Merge Patchسند جزئی RFC 7396؛ null عضو را حذف می‌کند
هدر Location (Location header)URI منبع ساخته‌شده یا ناظر وضعیت
Problem Detailsقالب خطای RFC 9457: type، title، status، detail، instance
RFC 9457RFC سال 2023 برای Problem Details که جای RFC 7807 را می‌گیرد
صفحه‌بندی offset (Offset pagination)N ردیف را رد کن؛ ساده، زیر نوشتن ناپایدار، در عمق کند
صفحه‌بندی keyset (Keyset pagination)پس از آخرین کلید مرتب‌سازی و id ادامه بده؛ پایدار و سریع
Cursortoken مات که موقعیت keyset و فیلترها را رمز می‌کند
فیلتر / مرتب‌سازی (Filtering / sorting)پارامترهای query مجاز که مجموعه را باریک و مرتب می‌کنند
Sparse fieldsetsکلاینت فیلدهای برگشتی را انتخاب می‌کند (fields=id,status)
ETagاعتبارسنج مات یک بازنمایی؛ قوی یا ضعیف
If-Matchفقط اگر ETag فعلی جور است بنویس؛ وگرنه 412
If-None-Matchدر GET: اگر جور است 304؛ در PUT با *: فقط اگر وجود ندارد بساز
هم‌روندی خوش‌بینانه (Optimistic concurrency)کشف تعارض هنگام نوشتن با version، به‌جای قفل هنگام خواندن
کلید idempotency (Idempotency key / Idempotency-Key)کلید یکتای کلاینت که به سرور اجازه می‌دهد نتیجهٔ اول یک POST را بازپخش کند
اثر انگشت idempotency (Idempotency fingerprint)hash درخواست برای کشف کلیدی که با بدنهٔ دیگر به کار رفته
Retry-Afterثانیه (یا تاریخ) صبر پیش از retry (429، 503، poll کردن 202)
هدرهای RateLimit (RateLimit headers)فیلدهای پیش‌نویس IETF: RateLimit-Policy (سهمیه) و RateLimit (در دسترس)
endpoint bulk (Bulk endpoint)یک درخواست با چندین قلم؛ اتمی یا با نتیجهٔ جدا برای هر قلم
عملیات طولانی (Long-running operation)کاری که با 202 پذیرفته و با یک منبع وضعیت پیگیری می‌شود
OpenAPIتوصیف ماشین‌خوان API روی HTTP؛ نسخهٔ 3.1 با JSON Schema 2020-12 هم‌راستاست
Contract-firstنوشتن و بازبینی قرارداد API پیش از پیاده‌سازی
Codegenتولید کلاینت، stub و mock از روی قرارداد
راهنمای سبک API (API style guide)قواعد هنجاری سازمانی برای APIها، مثل Google AIP
Google AIPAPI Improvement Proposals گوگل (google.aip.dev)
apiResourceثبت مسیرهای index، store، show، update، destroy در Laravel
API Resourceکلاس JsonResource در Laravel که مدل را به بازنمایی تبدیل می‌کند
Form Requestکلاس درخواست Laravel با authorize() (403) و rules() (422)
Route model bindingتبدیل {order} به مدل در Laravel، 404 اگر نباشد
Policyکلاس Laravel که قواعد مجوزدهی هر مدل را نگه می‌دارد

منابع ​

ساخته‌شده توسط Morteza Negahi