Lecture 03 · Application Programming Interfaces

المحاضرة 03 · واجهات برمجة التطبيقات

Designing a REST API: five elements, lamps and calculator

تصميم REST API: العناصر الخمسة، والمصابيح والآلة الحاسبة

Slides 20–26الشرائح 20–26 P1 MUST

Any REST design question is answered by filling the same five rows: URL, method, status codes, headers, JSON. The slides do it twice, for lamps and for a calculator.

أي سؤال تصميم REST تجيب عنه بملء الصفوف الخمسة نفسها: URL، الطريقة، رموز الحالة، الترويسات، JSON. والشرائح تفعل ذلك مرتين: للمصابيح وللآلة الحاسبة.

The five design elements

عناصر التصميم الخمسة

Slides 20 and 24 list what you must decide when designing a REST API. Learn them in order, with the one-line content slide 24 gives each:

تسرد الشريحتان 20 و24 ما يجب أن تقرره عند تصميم واجهة REST. احفظها بالترتيب، مع السطر الذي تعطيه الشريحة 24 لكل عنصر:

#ElementالعنصرSlide 24 contentمحتوى الشريحة 24Travels inأين ينتقل
1URLURLDomain name + pathاسم النطاق + المسارRequest lineسطر الطلب
2HTTP request methodHTTP request method (طريقة الطلب)GET, POST, PUT, DELETERequest lineسطر الطلب
3HTTP response status codeHTTP response status code (رمز حالة الاستجابة)100 to 599من 100 إلى 599Response status lineسطر حالة الاستجابة
4Header fieldsHeader fields (حقول الترويسة)Metadata: cookies, tokens, content type (application/json), ...بيانات وصفية (metadata): الـ cookies، والـ tokens، ونوع المحتوى (application/json)، ...Request and response headersheaders الطلب والاستجابة
5JSON messageJSON message (رسالة JSON)Resource representation: data describing a resource's state or requested changesتمثيل الـ resource: بيانات تصف حالة الـ resource أو التغييرات المطلوبة عليهRequest or response bodyالـ body في الطلب أو الاستجابة

يلخّص الجدول العناصر الخمسة وأين يسافر كل منها داخل رسالة HTTP. لاحظ أن رمز الحالة هو العنصر الوحيد الذي يوجد في الاستجابة فقط، وأن JSON يصف إما حالة المورد (في الاستجابة) وإما التغيير المطلوب (في الطلب).

WHERE THE FIVE ELEMENTS SIT REQUEST PUT http://myHome.com/lamps/123 Authorization: Bearer eyJ... Content-Type: application/json { "id": 123, "Enabled": true, "ON": true, "brightness": 60 } 2 1 4 5 body = requested change RESPONSE HTTP/1.1 200 OK Content-Type: application/json Cache-Control: max-age=60 { "id": 123, "Enabled": true, "ON": true, "brightness": 60 } 3 4 5 body = resource state
1 URL and 2 method open the request. 3 status code opens the response. 4 headers and 5 JSON appear on both sides.
1 الـ URL و2 الـ method يفتتحان الطلب. و3 رمز الحالة يفتتح الاستجابة. و4 الـ headers و5 الـ JSON يظهران في الجهتين.

العنصر 1 (URL) والعنصر 2 (الطريقة) يفتتحان الطلب. والعنصر 3 (رمز الحالة) يفتتح الاستجابة. أما 4 (الترويسات) و5 (JSON) فيظهران في الجهتين.

Memory trickحيلة للحفظ

"Where, What, How did it go, Extra info, Data": URL is where, method is what to do, status code is how it went, headers are extra info, JSON is the data.

أين، ماذا، كيف جرى، معلومات إضافية، بيانات: URL هو أين، والطريقة هي ماذا تفعل، ورمز الحالة هو كيف جرى الأمر، والترويسات معلومات إضافية، وJSON هو البيانات.

The design principles behind the elements

مبادئ التصميم وراء العناصر

Slide 21 states four practical rules that the five elements implement:

تذكر الشريحة 21 أربع قواعد عملية تطبّقها العناصر الخمسة:

  1. Every entity is a resource (a file, a user, a virtual machine, an IoT device), and each resource is uniquely identified by a URI such as /lamps/123.

    كل كيان مورد (resource): ملف، مستخدم، آلة افتراضية، جهاز IoT. وكل مورد له URI فريد مثل /lamps/123.

  2. A resource is represented in JSON, using key-value pairs, and representations are exchanged through HTTP request and response bodies.

    يُمثَّل المورد بـ JSON باستخدام أزواج مفتاح وقيمة (key-value pairs)، وتُتبادل التمثيلات عبر أجسام طلبات واستجابات HTTP.

  3. Extra information goes in HTTP headers: authentication tokens, content types, and accepted response formats.

    المعلومات الإضافية توضع في ترويسات HTTP: رموز المصادقة (tokens)، ونوع المحتوى، وصيغ الاستجابة المقبولة.

  4. Communication is stateless: each request contains what the server needs to process it independently.

    الاتصال عديم الحالة: كل طلب يحمل ما يحتاجه الخادم لمعالجته بشكل مستقل.

Design example 1: lamps in a home

مثال التصميم 1: المصابيح في منزل

Slide 22 sets the scene: a browser page at .../lamp/123 with ON, OFF and an intensity slider sends an HTTP request to a small server (a Raspberry Pi in the picture), which sends a signal to the device with ID 123. Slide 23 is the solution table. Two URLs: the collection http://myHome.com/lamps and the item http://myHome.com/lamps/123.

الشريحة 22 ترسم المشهد: صفحة متصفح على .../lamp/123 فيها أزرار ON وOFF ومنزلق للشدة، ترسل طلب HTTP إلى خادم صغير (Raspberry Pi في الصورة)، والخادم يرسل إشارة إلى الجهاز رقم 123. والشريحة 23 هي جدول الحل. هناك عنوانان: المجموعة (collection) http://myHome.com/lamps والعنصر (item) http://myHome.com/lamps/123.

Methodالـ Method/lamps/lamps/123JSON objectكائن JSON
GETList all lamps in the houseعرض قائمة بكل المصابيح في المنزلGet information about a specific lampجلب معلومات مصباح معيّنReturned in response: {"id":123, "Enabled":true, "ON":true, "brightness":35}يُرجَع في الاستجابة: {"id":123, "Enabled":true, "ON":true, "brightness":35}
DELETEDisable all lampsتعطيل كل المصابيحDisable a specific lampتعطيل مصباح معيّنSent in response: {"id":123, "Enabled":false}يُرسَل في الاستجابة: {"id":123, "Enabled":false}
PUTChange brightness of / turn on or off / enable all lampsتغيير السطوع / التشغيل أو الإطفاء / التفعيل لكل المصابيحSame, for one specific lampالشيء نفسه، لمصباح واحد معيّنSent in request: {"id":123, "Enabled":true, "ON":true, "brightness":60}يُرسَل في الطلب: {"id":123, "Enabled":true, "ON":true, "brightness":60}
POSTSearch for a newly installed lamp, assign it a unique ID, create a virtual resource for itالبحث عن مصباح رُكِّب حديثاً، وإعطاؤه معرّفاً فريداً، وإنشاء resource افتراضي لهNot applicableلا ينطبقReturned in response: {"id":123, "Enabled":true, "ON":false, "brightness":0}يُرجَع في الاستجابة: {"id":123, "Enabled":true, "ON":false, "brightness":0}

هذا جدول الحل في الشريحة 23. ما يجب ملاحظته: GET وDELETE وPOST يعود فيها JSON داخل الاستجابة، أما PUT فهو الوحيد الذي يُرسَل فيه JSON داخل الطلب. وDELETE هنا يعني تعطيل المصباح ("Enabled": false) لا إزالته. وPOST على العنصر /lamps/123 غير منطبق، لأن الإنشاء يتم على المجموعة. والترويسات لكل الصفوف هي Cookie وAuthentication Token وAuthorization Token.

Header fields for every row: Cookie, Authentication Token, Authorization Token. Notice the new lamp found by POST starts life enabled but off at brightness 0.

الترويسات في كل الصفوف: Cookie، Authentication Token، Authorization Token. ولاحظ أن المصباح الجديد الذي يكتشفه POST يبدأ مُفعَّلاً (Enabled) لكنه مطفأ وسطوعه 0.

Design example 2: the calculator

مثال التصميم 2: الآلة الحاسبة

Slide 25 asks: design a REST API for the addition operation, which must happen on the server. Slide 26 fills the five elements:

تطلب الشريحة 25: صمّم واجهة REST لعملية الجمع بحيث تتم على الخادم. والشريحة 26 تملأ العناصر الخمسة:

REST elementعنصر RESTValue (slide 26)القيمة (الشريحة 26)
URLhttp://calculator.com/add
HTTP request methodHTTP request method (طريقة الطلب)GET
HTTP response status codeHTTP response status code (رمز حالة الاستجابة)200 (successful), 400 (bad request), 406 (not acceptable), 500 (internal server error), 503 (service unavailable), ...200 (نجاح)، 400 (طلب غير صالح)، 406 (غير مقبول)، 500 (خطأ داخلي في الخادم)، 503 (الخدمة غير متاحة)، ...
Header fieldsHeader fields (حقول الترويسة)Authorization
JSON messageJSON message (رسالة JSON){"X": 1, "Y": 2}

هذا جدول الشريحة 26 كما هو. احفظه حرفياً: URL هو http://calculator.com/add، والطريقة GET، والترويسة Authorization، والرسالة {"X": 1, "Y": 2}. رموز الحالة خمسة: 200 و400 و406 و500 و503.

Worked exampleمثال محلول

The server builds an environment from the request and executes the operation (slide 26: "environment constructed on the server to execute the operation requested by the client"):

الخادم يبني بيئة من الطلب وينفّذ العملية (الشريحة 26: بيئة تُبنى على الخادم لتنفيذ العملية التي طلبها العميل):

request   GET http://calculator.com/add
          Authorization: Bearer eyJ...
          { "X": 1, "Y": 2 }

server    X  = 1
          Y  = 2
          op = Addition        (chosen by the path /add)
          Resp.send(X op Y)  =  Resp.send(1 + 2)  =  3

response  200 OK   with the result 3

Now map failures to the slide's codes:

الآن اربط حالات الفشل برموز الشريحة:

body is { "X": 1 }  (Y missing)            -> 400 bad request
client sends Accept: application/xml,
  server can only produce JSON            -> 406 not acceptable
server code throws an exception           -> 500 internal server error
server overloaded or down for maintenance -> 503 service unavailable
Slide quirk: GET with a JSON bodyغرابة في الشريحة: GET مع body بصيغة JSON

The slide pairs GET with a JSON body. HTTP gives a GET body no defined meaning, so many real APIs would instead use GET /add?x=1&y=2 (query parameters) or POST /add with the JSON body. In the exam, answer per the slide: GET. If a short-answer question lets you justify, you may add that GET is safe and idempotent, which fits a pure calculation.

الشريحة تجمع GET مع جسم JSON. بروتوكول HTTP لا يعطي جسم GET معنى محدداً، لذلك كثير من الواجهات الحقيقية تستخدم GET /add?x=1&y=2 (معاملات استعلام) أو POST /add مع جسم JSON. في الاختبار أجب حسب الشريحة: GET. وإذا سمح سؤال الإجابة القصيرة بالتبرير، فاذكر أن GET آمن (safe) وidempotent، وهذا يناسب عملية حسابية بحتة.

Status code classes

فئات رموز الحالة

Slide 24 says status codes run from 100 to 599. The first digit tells you the class, which is all you need for a matching question:

تقول الشريحة 24 إن رموز الحالة من 100 إلى 599. الرقم الأول يحدد الفئة، وهذا كل ما تحتاجه لسؤال matching:

ClassالفئةMeaningالمعنىWhose sideعلى من تقعExamplesأمثلة
1xxInformationalمعلوماتية (Informational)In progressقيد التنفيذ100 Continue
2xxSuccessنجاح (Success)All goodكل شيء سليم200 OK, 201 Created, 204 No Content
3xxRedirectionإعادة توجيه (Redirection)Look elsewhereابحث في مكان آخر301 Moved Permanently, 304 Not Modified
4xxClient errorخطأ من العميل (Client error)Client's faultخطأ العميل400 Bad Request, 406 Not Acceptable, also 401, 403, 404400 Bad Request، و406 Not Acceptable، وأيضاً 401 و403 و404
5xxServer errorخطأ من الخادم (Server error)Server's faultخطأ الخادم500 Internal Server Error, 503 Service Unavailable

الفئات الخمس تتحدد بالرقم الأول: 1xx معلوماتية، 2xx نجاح، 3xx إعادة توجيه، 4xx خطأ من العميل، 5xx خطأ من الخادم. الخلايا المظللة تحتوي رموز الشريحة 26. أما 201 و204 و301 و304 و401 و403 و404 فهي إضافات شائعة من خارج الشريحة.

Exam trapsفخاخ الامتحان

4xx is the client's fault, 5xx is the server's fault. A missing Y is 400 (client). A crash computing 1 + 2 is 500 (server). 503 means the server is temporarily unable to serve, not that the request was wrong.

4xx خطأ العميل، و5xx خطأ الخادم. غياب Y هو 400 (العميل). وانهيار الخادم أثناء حساب 1 + 2 هو 500 (الخادم). و503 يعني أن الخادم غير قادر مؤقتاً على الخدمة، لا أن الطلب خاطئ.

406 is about the Accept header. It means the server cannot produce a response in any format the client said it accepts. It is not "unauthorized" (that is 401).

406 مرتبط بترويسة Accept. معناه أن الخادم لا يستطيع إنتاج استجابة بأي صيغة قال العميل إنه يقبلها. وليس معناه "غير مصرّح" (ذلك 401).

In the lamp table, DELETE disables ("Enabled": false) rather than removing the lamp, and POST on /lamps/123 is not applicable.

في جدول المصابيح، DELETE يعطّل المصباح ("Enabled": false) ولا يزيله، وPOST على /lamps/123 غير منطبق.

The URL element is domain name + path, for example calculator.com + /add. The method is a separate element, never part of the URL.

عنصر URL هو اسم النطاق مع المسار، مثل calculator.com مع /add. والطريقة عنصر مستقل، وليست جزءاً من URL.

Check yourself

اختبر نفسك

Which list gives the five REST design elements from slide 24?

أي قائمة تعطي عناصر تصميم REST الخمسة من الشريحة 24؟

B. A mixes up the design elements with the architectural constraints from slides 18 and 19. D lists methods, which are only element 2.

B. الخيار A يخلط عناصر التصميم بالقيود المعمارية من الشريحتين 18 و19. والخيار D يسرد طرقاً (methods)، وهي العنصر 2 فقط.

In slide 26's calculator design, which values are given for the method, header and JSON message?

في تصميم الآلة الحاسبة بالشريحة 26، ما القيم المعطاة للطريقة والترويسة ورسالة JSON؟

D. The slide's table: URL http://calculator.com/add, method GET, header Authorization, JSON {"X": 1, "Y": 2}. A describes a common real-world alternative and a response, not what the slide gives.

D. جدول الشريحة: الـ URL هو http://calculator.com/add، والـ method هو GET، والـ header هو Authorization، والـ JSON هو {"X": 1, "Y": 2}. والخيار A يصف بديلاً شائعاً في الواقع مع استجابة، لا ما تعطيه الشريحة.

A client sends Accept: application/xml to an API that can only return JSON. The most fitting status code is:

عميل يرسل Accept: application/xml إلى واجهة لا تُرجع إلا JSON. ما رمز الحالة الأنسب؟

C. 406 means no representation matches what the client's Accept header allows. It is a 4xx because the client asked for something the server does not offer. B and D are server-side failures.

C. الرمز 406 يعني أنه لا يوجد تمثيل يطابق ما يسمح به الـ Accept header عند العميل. وهو من فئة 4xx لأن العميل طلب شيئاً لا يقدّمه الخادم. والخياران B وD أعطال من جهة الخادم.

In the lamp solution table (slide 23), what does DELETE http://myHome.com/lamps/123 do?

في جدول حل المصابيح (الشريحة 23)، ماذا يفعل DELETE http://myHome.com/lamps/123؟

A. The slide defines DELETE as "disable a specific lamp", with the JSON sent in the response. C confuses disabling with switching off, which is done with PUT. D is the entry for POST on the item URL, not DELETE.

A. الشريحة تعرّف DELETE بأنه "تعطيل مصباح معيّن"، مع إرسال الـ JSON في الاستجابة. والخيار C يخلط بين التعطيل والإطفاء، والإطفاء يتم بـ PUT. والخيار D هو خانة POST على URL العنصر، لا DELETE.

Which status code class indicates the server failed to fulfil a valid request?

أي فئة من رموز الحالة تعني أن الخادم فشل في تلبية طلب صحيح؟

B. 5xx is server error, for example 500 and 503. 4xx means the request itself was faulty, 3xx is redirection and 1xx is informational.

B. الفئة 5xx هي خطأ من الخادم، مثل 500 و503. والفئة 4xx تعني أن الطلب نفسه كان معيباً، و3xx إعادة توجيه، و1xx معلوماتية.