Majid Al-RaimiReference sheetالورقة المرجعية

COE 558Lecture 03المحاضرة 03Referenceالمرجع

Reference sheetالورقة المرجعية

Application Programming Interfaces (APIs) compressed onto one page: the definitions, formulas and numbers to have in your head before a quiz or exam.محاضرة «واجهات برمجة التطبيقات (APIs)» مضغوطة في صفحة واحدة: التعريفات والمعادلات والأرقام التي يجب أن تكون حاضرة في ذهنك قبل الاختبار القصير أو الامتحان.

API, protocol, connection, endpoint, routeAPI والبروتوكول والاتصال وendpoint وroute

Six words to keep apart. Part 01: APIs, endpoints and routes

ست كلمات يجب أن تفصل بينها. الجزء 01: الـAPIs ونقاط النهاية والمسارات

API=what you can callProtocol=how you call itConnection=how the data physically travels\begin{aligned}\textbf{API} &= \text{what you can call}\\ \textbf{Protocol} &= \text{how you call it}\\ \textbf{Connection} &= \text{how the data physically travels}\end{aligned}
Slide 3, word for wordالشريحة 3، حرفيًا
Route=HTTP method+URL\text{Route} = \text{HTTP method} + \text{URL}
Slide 6الشريحة 6
TermالمصطلحMeaningالمعنىLamp exampleمثال المصباح
APIAPIWhat you can call; the interface between componentsما يمكنك استدعاؤه، أي الواجهة بين المكوّناتread energy at /lamp/energyقراءة الطاقة عبر /lamp/energy
Protocolالبروتوكول (Protocol)How you call it; HTTP for a Web APIكيف تستدعيه، وهو HTTP في حالة Web APIGET and PUT with status codesGET وPUT مع رموز الحالة
Connectionالاتصال (Connection)How the data physically travels; TCP/IP under HTTPكيف تنتقل البيانات فعليًا، وهو TCP/IP تحت HTTPTCP between two sockets, over Wi-FiTCP بين مقبسين (sockets) عبر Wi-Fi
Resourceالمورد (Resource)The entity the server managesالكيان الذي يديره الخادمLamp 7 itselfالمصباح 7 نفسه
Endpointنقطة النهاية (Endpoint)The API on the server; an abstraction of a resource with the CRUD logicالـAPI على الخادم، أي تجريد لمورد مع منطق CRUD/lamps/7
Routeالمسار (Route)HTTP method + URL; selects one CRUD operationطريقة HTTP زائد URL، ويختار عملية CRUD واحدةPUT /lamps/7
The vocabulary with the lampالمصطلحات بمثال المصباح
  • API layer jobs: fetch from the backend for display on the frontend, take from the frontend to insert into the backend.مهام طبقة الـAPI: تجلب البيانات من الواجهة الخلفية (backend) لعرضها في الواجهة الأمامية (frontend)، وتأخذ البيانات من الواجهة الأمامية لإدخالها في الواجهة الخلفية.
  • An endpoint is an abstraction of a resource, supports CRUD and provides the logic to run it.نقطة النهاية (endpoint) تجريد لمورد، تدعم عمليات CRUD وتوفّر المنطق الذي ينفّذها.
  • For the client, the HTTP server is a set of APIs.بالنسبة للعميل، خادم HTTP هو مجموعة من الـAPIs.

HTTP methods and CRUDطرق HTTP وعمليات CRUD

Slide 8 lists GET first, slide 9 lists CRUD order; the mapping is the same. Part 02: HTTP methods and message anatomy

الشريحة 8 تبدأ بـGET، والشريحة 9 تتبع ترتيب CRUD، لكن الربط واحد. الجزء 02: طرق HTTP وتشريح الرسالة

MethodالطريقةCRUDCRUDActionالإجراءSafeآمنةIdempotentمتساوية الأثر
POSTCreateإنشاء (Create)Create a new resourceإنشاء مورد جديدNoلاNoلا
GETReadقراءة (Read)Return a resourceإرجاع موردYesنعمYesنعم
PUTUpdate or Replaceتحديث أو استبدال (Update or Replace)Replace the resource with the state you sendاستبدال المورد بالحالة التي ترسلهاNoلاYesنعم
DELETEDeleteحذف (Delete)Remove the resourceإزالة الموردNoلاYesنعم
PATCHUpdate (partial)تحديث جزئي (Update (partial))Change only the fields you send (slide 19)تغيير الحقول التي ترسلها فقط (الشريحة 19)NoلاNot guaranteedغير مضمون
Methods, CRUD and two RFC 9110 propertiesالطرق وعمليات CRUD وخاصيتان من RFC 9110

Request and response anatomyتشريح الطلب والاستجابة

Both share one shape: start line, header fields, empty line, optional body. Part 02: HTTP methods and message anatomy

كلاهما بالشكل نفسه: سطر البداية (start line)، ثم حقول الترويسة (header fields)، ثم سطر فارغ، ثم جسم اختياري (body). الجزء 02: طرق HTTP وتشريح الرسالة

Request (slide 11)الطلب (الشريحة 11)

Request lineسطر الطلب
GET /index.html HTTP/1.1: method, request target, version, single spacesGET /index.html HTTP/1.1: الطريقة، ثم هدف الطلب (request target)، ثم الإصدار، تفصل بينها مسافات مفردة
Route and resourceالمسار والمورد
Lecturer's split: route / (root), resource index.htmlتقسيم المحاضر: المسار / (الجذر)، والمورد index.html
Host: localhost
Mandatory in HTTP/1.1; a server must answer 400 without itإلزامي في HTTP/1.1، ويجب أن يرد الخادم بـ400 إذا غاب
Accept: text/html
Media type the client wants back; a JSON client sends application/jsonنوع الوسائط (media type) الذي يريده العميل في الرد، والعميل الذي يريد JSON يرسل application/json
Empty lineسطر فارغ
A lone CRLF ends the header sectionسطر CRLF وحده ينهي قسم الترويسات
Bodyالجسم
Optional; a GET has none, a POST or PUT carries the new stateاختياري، فطلب GET لا جسم له، وطلب POST أو PUT يحمل الحالة الجديدة

Response (slide 12)الاستجابة (الشريحة 12)

HTTP/1.1
Protocol versionإصدار البروتوكول
200
Status code, a three-digit outcome for programsرمز الحالة، نتيجة من ثلاثة أرقام موجهة للبرامج
OK
Status message (reason phrase) for humansرسالة الحالة (reason phrase) موجهة للبشر
Content-Type: text/html
Media type of the bodyنوع الوسائط (media type) للجسم
Content-Length: 500
Size of the body only, in bytes: 500 bytesحجم الجسم وحده بالبايت: 500 bytes
Empty line, then bodyسطر فارغ، ثم الجسم
The HTML page itself, <html> ... </html>صفحة HTML نفسها، <html> ... </html>
ClassالفئةMeaningالمعنىIn wordsبالكلماتExamplesأمثلة
1xxInformationalمعلوماتية (Informational)Received, still processingاستُلم الطلب وما زالت المعالجة جارية100 Continue
2xxSuccessنجاح (Success)Received, understood and acceptedاستُلم الطلب وفُهم وقُبل200 OK, 201 Created
3xxRedirectionإعادة توجيه (Redirection)Client must take another stepعلى العميل أن يتخذ خطوة أخرى301 Moved Permanently
4xxClient errorخطأ من العميل (Client error)Request is wrong or cannot be fulfilledالطلب خاطئ أو لا يمكن تلبيته400, 404, 406
5xxServer errorخطأ من الخادم (Server error)Valid request, the server failedالطلب صحيح لكن الخادم فشل500, 503
Status code classesفئات رموز الحالة

Collections, items and URLsالمجموعات والعناصر وعناوين URL

The method says what to do; the URL says to what. Part 03: Designing endpoints

الطريقة (method) تقول ماذا نفعل، والـURL يقول بماذا. الجزء 03: تصميم نقاط النهاية

Methodالطريقة/lamps (collection)/lamps (المجموعة)/lamps/123 (item)/lamps/123 (العنصر)
GETList all lampsعرض قائمة بكل المصابيحGet information about lamp 123جلب معلومات المصباح 123
DELETEDisable all lampsتعطيل كل المصابيحDisable lamp 123تعطيل المصباح 123
PUTTurn all on or off, change brightness of allتشغيل الكل أو إطفاؤه، وتغيير سطوع الكلTurn lamp 123 on or off, change its brightnessتشغيل المصباح 123 أو إطفاؤه، وتغيير سطوعه
POSTCreate virtual resources, with IDs, for new lampsإنشاء موارد افتراضية بمعرّفات (IDs) للمصابيح الجديدةNot applicable (slides 14 and 23)لا ينطبق (الشريحتان 14 و23)
Lamp API scope (slide 13, corrected)نطاق API المصباح (الشريحة 13، بعد التصحيح)
MethodالطريقةPathالمسارPurposeالغرض
GET/visitsList all visitsعرض قائمة بكل الزيارات
GET/visits/newShow the form for a new visitعرض نموذج زيارة جديدة
POST/visitsCreate a new visitإنشاء زيارة جديدة
GET/visits/:idShow one visitعرض زيارة واحدة
PUT/visits/:idUpdate one visitتحديث زيارة واحدة
DELETE/visits/:idDelete one visitحذف زيارة واحدة
POST/visits/:idError: do not do thisخطأ: لا تفعل هذا
Resourceful routes for visits (slide 14)المسارات المبنية على الموارد للزيارات (الشريحة 14)

URL anatomy (slides 15 and 16)تشريح الـ URL (الشريحتان 15 و16)

http://
Scheme: the protocolالمخطط (scheme): البروتوكول
www.myhome.com
Server: which machine receives the requestالخادم (server): أي جهاز يستقبل الطلب
/lamps
Route: where on the server to deliver the requestالمسار (route): إلى أين يُسلَّم الطلب داخل الخادم
/123
Resource: what the method operates onالمورد (resource): ما تعمل عليه الطريقة
?brightness=6&color=green
Inputs: ? starts the query, & separates pairs, = splits key and valueالمدخلات (inputs): ? يبدأ الاستعلام، و& يفصل بين الأزواج، و= يفصل المفتاح عن القيمة

REST and its six constraintsREST وقيوده الستة

REpresentational State Transfer, Roy Thomas Fielding, doctoral dissertation, UC Irvine, 2000. An architectural style (a set of constraints), not a protocol. Mnemonic: Can Students Cache Useful Lamp Code? Part 04: REST and its six constraints

REpresentational State Transfer، من أطروحة الدكتوراه لـRoy Thomas Fielding في UC Irvine عام 2000. هو أسلوب معماري (مجموعة من القيود) وليس بروتوكولًا. جملة للحفظ: Can Students Cache Useful Lamp Code? الجزء 04: REST وقيوده الستة

ConstraintالقيدMeaningالمعنىLamp exampleمثال المصباحStatusالحالة
1. Client-server1. عميل وخادم (Client-server)Separate client and server responsibilitiesفصل مسؤوليات العميل عن مسؤوليات الخادمApp owns the UI, server owns lamp stateالتطبيق يملك واجهة المستخدم، والخادم يملك حالة المصباحMandatoryإلزامي
2. Stateless2. عديم الحالة (Stateless)No client session data on the server; every request carries all it needsلا بيانات جلسة للعميل على الخادم، وكل طلب يحمل كل ما يحتاجهLamp ID and auth token in every requestمعرّف المصباح ورمز المصادقة (auth token) في كل طلبMandatoryإلزامي
3. Cacheable3. قابل للتخزين المؤقت (Cacheable)Responses say whether they may be reusedالاستجابات تذكر هل يجوز إعادة استخدامهاCache-Control: max-age=60Mandatoryإلزامي
4. Uniform interface4. واجهة موحّدة (Uniform interface)Standardized interaction, four sub-constraintsتفاعل موحّد المعايير، وله أربعة قيود فرعيةPATCH /lamps/123Mandatoryإلزامي
5. Layered system5. نظام طبقي (Layered system)Intermediaries allowed; each sees only the next layerالوسطاء مسموح بهم، وكل طبقة لا ترى إلا الطبقة التاليةAPI gateway, load balancerبوابة API (API gateway)، وموازن حمل (load balancer)Mandatoryإلزامي
6. Code on demand6. الشيفرة عند الطلب (Code on demand)Server may send executable code to the clientيجوز للخادم أن يرسل شيفرة قابلة للتنفيذ إلى العميلJavaScript lamp control UIواجهة تحكم بالمصباح مكتوبة بـJavaScriptOptionalاختياري
The six constraints in orderالقيود الستة بالترتيب
  1. Resource identification through URIs: /lamps/123.تعريف المورد عبر الـURIs (resource identification): /lamps/123.
  2. Manipulation through representations: {"brightness": 80}.التعامل مع المورد عبر تمثيلاته (manipulation through representations): {"brightness": 80}.
  3. Self-descriptive messages: method, Content-Type and body describe the update.رسائل تصف نفسها (self-descriptive messages): الطريقة وContent-Type والجسم تصف التحديث.
  4. HATEOAS: the response links to retrieve, update or delete the lamp.HATEOAS: الاستجابة تحتوي روابط لاسترجاع المصباح أو تحديثه أو حذفه.
AspectالجانبStateless (REST)عديم الحالة (REST)Statefulذو حالة (Stateful)
Each request carriesما يحمله كل طلبLamp ID, auth token, the changeمعرّف المصباح، ورمز المصادقة (auth token)، والتغييرOnly the changeالتغيير فقط
Session data livesمكان بيانات الجلسةOn the clientعلى العميلIn server memoryفي ذاكرة الخادم
Scaling outالتوسع الأفقي (scaling out)Add servers; any server answersأضف خوادم، وأي خادم يجيبRequests stick to one serverالطلبات تلتصق بخادم واحد
Failoverالتعافي من الأعطال (failover)Another server takes the next requestخادم آخر يتولى الطلب التاليSession lost when that server crashesتضيع الجلسة عند تعطل ذلك الخادم
CostالتكلفةA little repeated data per requestقليل من البيانات المكررة في كل طلبMemory per client on the serverذاكرة لكل عميل على الخادم
Stateless versus statefulعديم الحالة مقابل ذي الحالة
fresh  ⟺  age<max-age\text{fresh} \iff \text{age} < \text{max-age}
Age counts from generation at the origin serverيُحسب العمر من لحظة التوليد في الخادم الأصلي

Cache worked exampleمثال محلول على التخزين المؤقت

Responseالاستجابة
GET /lamps/123 at t = 0 s, Cache-Control: max-age=60GET /lamps/123 عند t = 0 s، مع Cache-Control: max-age=60
Request at 45 sطلب عند 45 ثانية
45 < 60: fresh, served from cache45 < 60: حديثة (fresh)، فيُخدَم الطلب من ذاكرة التخزين المؤقت
Request at 75 sطلب عند 75 ثانية
75 > 60: stale, goes back to the server75 > 60: قديمة (stale)، فيعود الطلب إلى الخادم
Proxy held it 20 sالوسيط احتفظ بها 20 ثانية
Age: 20 leaves 60 - 20 = 40 s of freshnessAge: 20 يترك 60 - 20 = 40 s من الحداثة

The five design elementsعناصر التصميم الخمسة

Any REST API design answer is these five rows. Part 05: Designing REST APIs

أي إجابة عن تصميم REST API هي هذه الصفوف الخمسة. الجزء 05: تصميم REST APIs

ElementالعنصرWhat it holdsما يحتويهLamp exampleمثال المصباحQuestionالسؤال
1. URL1. عنوان URLDomain name + pathاسم النطاق زائد المسارhttp://myHome.com/lamps/123Which resource?أي مورد؟
2. HTTP request method2. طريقة طلب HTTPGET, POST, PUT, DELETEGET، POST، PUT، DELETEPUTWhat to do with it?ماذا نفعل به؟
3. HTTP response status code3. رمز حالة استجابة HTTP100 to 599من 100 إلى 599200 OKDid it work, whose fault?هل نجح، وعلى من الخطأ؟
4. Header fields4. حقول الترويسة (header fields)Metadata: cookies, tokens, Content-Typeبيانات وصفية: cookies، والرموز (tokens)، وContent-TypeContent-Type: application/jsonWhat surrounds the message?ما الذي يحيط بالرسالة؟
5. JSON message5. رسالة JSONRepresentation of state or requested changeتمثيل للحالة أو للتغيير المطلوب{"id": 123, "Enabled": true, "ON": true, "brightness": 60}What is the data?ما البيانات؟
Design elements, PUT on lamp 123عناصر التصميم، طلب PUT على المصباح 123
Methodالطريقة/lamps/lamps/lamps/123/lamps/123JSON objectكائن JSON
GETList all lamps in the houseعرض قائمة بكل المصابيح في المنزلGet information about lamp 123جلب معلومات المصباح 123Response: {"id": 123, "Enabled": true, "ON": true, "brightness": 35}الاستجابة: {"id": 123, "Enabled": true, "ON": true, "brightness": 35}
DELETEDisable all lampsتعطيل كل المصابيحDisable lamp 123تعطيل المصباح 123Response: {"id": 123, "Enabled": false}الاستجابة: {"id": 123, "Enabled": false}
PUTChange brightness, turn on or off, or enable allتغيير السطوع، أو التشغيل والإطفاء، أو تفعيل الكلSame for lamp 123الشيء نفسه للمصباح 123Request: {"id": 123, "Enabled": true, "ON": true, "brightness": 60}الطلب: {"id": 123, "Enabled": true, "ON": true, "brightness": 60}
POSTFind a new lamp, assign a unique ID, create its virtual resourceاكتشاف مصباح جديد، وتعيين معرّف (ID) فريد له، وإنشاء مورده الافتراضيNot applicableلا ينطبقResponse: {"id": 123, "Enabled": true, "ON": false, "brightness": 0}الاستجابة: {"id": 123, "Enabled": true, "ON": false, "brightness": 0}
Lamp API (slide 23). Header fields for every row: Cookie, authentication token, authorization token.API المصباح (الشريحة 23). حقول الترويسة لكل صف: Cookie، ورمز المصادقة (authentication token)، ورمز التفويض (authorization token).
  • DELETE disables the lamp ("Enabled": false), a soft delete.DELETE يعطّل المصباح ("Enabled": false)، أي حذف ناعم (soft delete).
  • PUT sends the full new state; PATCH sends only the changed fields.PUT يرسل الحالة الجديدة كاملة، وPATCH يرسل الحقول المتغيرة فقط.

Calculator APIAPI الآلة الحاسبة

Other operations change only the path and numbers; division adds Y = 0 as a 400. Part 05: Designing REST APIs

العمليات الأخرى لا تغيّر إلا المسار والأرقام، والقسمة تضيف Y = 0 كحالة 400. الجزء 05: تصميم REST APIs

Addition, as on slide 26الجمع، كما في الشريحة 26

URL
http://calculator.com/addhttp://calculator.com/add
HTTP request methodطريقة طلب HTTP
GET
HTTP response status codeرمز حالة استجابة HTTP
200, 400, 406, 500, 503
Header fieldsحقول الترويسة
Authorization
JSON messageرسالة JSON
{"X": 1, "Y": 2}, result 3{"X": 1, "Y": 2}، والنتيجة 3
CodeالرمزMeaningالمعنىCalculator triggerالمسبب في الآلة الحاسبةFaultعلى من الخطأ
200 OKSucceededنجح الطلبX = 1, Y = 2, result 3X = 1، Y = 2، والنتيجة 3Nobodyلا أحد
400 Bad RequestClient error in the requestخطأ من العميل في الطلبX missing or "abc"; division by Y = 0X مفقود أو قيمته "abc"، أو قسمة على Y = 0Clientالعميل
406 Not AcceptableNo representation matches Acceptلا يوجد تمثيل يطابق AcceptAccept: application/xmlClientالعميل
500 Internal Server ErrorUnexpected server conditionحالة غير متوقعة في الخادمException in the addition codeاستثناء (exception) في شيفرة الجمعServerالخادم
503 Service UnavailableOverload or maintenance; may send Retry-Afterحمل زائد أو صيانة، وقد يرسل Retry-AfterToo many requests, or an upgradeطلبات كثيرة جدًا، أو ترقيةServerالخادم
Status codes and their triggersرموز الحالة ومسبباتها

Slide errataأخطاء الشرائح

Answer with the lecture's expected answer, then name the correction. Part 01, Part 02, Part 03, Part 04, Part 05

أجب بالإجابة التي تتوقعها المحاضرة، ثم اذكر التصحيح. الجزء 01، الجزء 02، الجزء 03، الجزء 04، الجزء 05

What the slides get wrongما أخطأت فيه الشرائح

Slide 3الشريحة 3
The line labelled both HTTP and Connection is two facts: HTTP is spoken over it, TCP/IP is the connection.الخط الموسوم بـHTTP وConnection معًا يجمع حقيقتين: HTTP هو ما يُتحدَّث عبره، وTCP/IP هو الاتصال.
Slides 4, 6الشريحتان 4 و6
"Endpoint" is used loosely. Answer in slide 6 wording: a URL leads to an endpoint that defines routes.كلمة "Endpoint" تُستخدم بتساهل. أجب بصياغة الشريحة 6: الـURL يقود إلى نقطة نهاية (endpoint) تعرّف المسارات (routes).
Slide 11الشريحة 11
Route / plus resource index.html is the lecturer's split; the standard calls /index.html the request target.المسار / زائد المورد index.html هو تقسيم المحاضر، أما المعيار فيسمّي /index.html هدف الطلب (request target).
Slides 10, 11الشريحتان 10 و11
Index.html versus index.html: paths are case-sensitive, the lowercase request is intended.Index.html مقابل index.html: المسارات حساسة لحالة الأحرف، والمقصود هو الطلب بالأحرف الصغيرة.
Slide 12الشريحة 12
Omits the empty line (CRLF) between headers and body.تُسقط السطر الفارغ (CRLF) بين الترويسات والجسم.
Slide 13الشريحة 13
POST on /lamps/123 contradicts slides 14 and 23. Use POST /lamps to create, PUT /lamps/123 to update.POST على /lamps/123 يناقض الشريحتين 14 و23. استخدم POST /lamps للإنشاء، وPUT /lamps/123 للتحديث.
Slide 14الشريحة 14
Lamp heading over a visits table; "a new visits" should be "a new visit".عنوان عن المصباح فوق جدول للزيارات، و"a new visits" صوابها "a new visit".
Slide 15الشريحة 15
"resrouce" should be "resource". A state change through a GET query breaks GET's safety."resrouce" صوابها "resource". وتغيير الحالة عبر استعلام GET يكسر خاصية الأمان (safety) في GET.
Slide 19الشريحة 19
HATEOAS is Hypermedia As The Engine Of Application State, not "hypermedia-driven application state".HATEOAS اختصار لـHypermedia As The Engine Of Application State، وليس "hypermedia-driven application state".
Slide 22الشريحة 22
/lamp/123 (singular) should be /lamps/123./lamp/123 (بصيغة المفرد) صوابها /lamps/123.
Slide 23الشريحة 23
Mixed JSON key casing (Enabled, ON, id); GET on /lamps returns a list; one Authorization token usually does both token jobs.حالة أحرف مختلطة في مفاتيح JSON (Enabled، ON، id)، وGET على /lamps يعيد قائمة، ورمز Authorization واحد يؤدي عادة مهمتي الرمزين كلتيهما.
Slide 26الشريحة 26
GET with a JSON body has no defined meaning. Use GET /add?x=1&y=2 or POST /add. The verb path /add is closer to RPC than REST.GET بجسم JSON ليس له معنى محدد. استخدم GET /add?x=1&y=2 أو POST /add. والمسار الذي هو فعل مثل /add أقرب إلى RPC منه إلى REST.