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 ونقاط النهاية والمسارات
| Termالمصطلح | Meaningالمعنى | Lamp exampleمثال المصباح |
|---|---|---|
| APIAPI | What 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 API | GET and PUT with status codesGET وPUT مع رموز الحالة |
| Connectionالاتصال (Connection) | How the data physically travels; TCP/IP under HTTPكيف تنتقل البيانات فعليًا، وهو TCP/IP تحت HTTP | TCP 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 |
- 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الطريقة | CRUDCRUD | Actionالإجراء | Safeآمنة | Idempotentمتساوية الأثر |
|---|---|---|---|---|
| POST | Createإنشاء (Create) | Create a new resourceإنشاء مورد جديد | Noلا | Noلا |
| GET | Readقراءة (Read) | Return a resourceإرجاع مورد | Yesنعم | Yesنعم |
| PUT | Update or Replaceتحديث أو استبدال (Update or Replace) | Replace the resource with the state you sendاستبدال المورد بالحالة التي ترسلها | Noلا | Yesنعم |
| DELETE | Deleteحذف (Delete) | Remove the resourceإزالة المورد | Noلا | Yesنعم |
| PATCH | Update (partial)تحديث جزئي (Update (partial)) | Change only the fields you send (slide 19)تغيير الحقول التي ترسلها فقط (الشريحة 19) | Noلا | Not guaranteedغير مضمون |
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أمثلة |
|---|---|---|---|
| 1xx | Informationalمعلوماتية (Informational) | Received, still processingاستُلم الطلب وما زالت المعالجة جارية | 100 Continue |
| 2xx | Successنجاح (Success) | Received, understood and acceptedاستُلم الطلب وفُهم وقُبل | 200 OK, 201 Created |
| 3xx | Redirectionإعادة توجيه (Redirection) | Client must take another stepعلى العميل أن يتخذ خطوة أخرى | 301 Moved Permanently |
| 4xx | Client errorخطأ من العميل (Client error) | Request is wrong or cannot be fulfilledالطلب خاطئ أو لا يمكن تلبيته | 400, 404, 406 |
| 5xx | Server errorخطأ من الخادم (Server error) | Valid request, the server failedالطلب صحيح لكن الخادم فشل | 500, 503 |
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 (العنصر) |
|---|---|---|
| GET | List all lampsعرض قائمة بكل المصابيح | Get information about lamp 123جلب معلومات المصباح 123 |
| DELETE | Disable all lampsتعطيل كل المصابيح | Disable lamp 123تعطيل المصباح 123 |
| PUT | Turn all on or off, change brightness of allتشغيل الكل أو إطفاؤه، وتغيير سطوع الكل | Turn lamp 123 on or off, change its brightnessتشغيل المصباح 123 أو إطفاؤه، وتغيير سطوعه |
| POST | Create virtual resources, with IDs, for new lampsإنشاء موارد افتراضية بمعرّفات (IDs) للمصابيح الجديدة | Not applicable (slides 14 and 23)لا ينطبق (الشريحتان 14 و23) |
| Methodالطريقة | Pathالمسار | Purposeالغرض |
|---|---|---|
| GET | /visits | List all visitsعرض قائمة بكل الزيارات |
| GET | /visits/new | Show the form for a new visitعرض نموذج زيارة جديدة |
| POST | /visits | Create a new visitإنشاء زيارة جديدة |
| GET | /visits/:id | Show one visitعرض زيارة واحدة |
| PUT | /visits/:id | Update one visitتحديث زيارة واحدة |
| DELETE | /visits/:id | Delete one visitحذف زيارة واحدة |
| POST | /visits/:id | Error: do not do thisخطأ: لا تفعل هذا |
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=60 | Mandatoryإلزامي |
| 4. Uniform interface4. واجهة موحّدة (Uniform interface) | Standardized interaction, four sub-constraintsتفاعل موحّد المعايير، وله أربعة قيود فرعية | PATCH /lamps/123 | Mandatoryإلزامي |
| 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واجهة تحكم بالمصباح مكتوبة بـJavaScript | Optionalاختياري |
- Resource identification through URIs: /lamps/123.تعريف المورد عبر الـURIs (resource identification): /lamps/123.
- Manipulation through representations: {"brightness": 80}.التعامل مع المورد عبر تمثيلاته (manipulation through representations): {"brightness": 80}.
- Self-descriptive messages: method, Content-Type and body describe the update.رسائل تصف نفسها (self-descriptive messages): الطريقة وContent-Type والجسم تصف التحديث.
- 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ذاكرة لكل عميل على الخادم |
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. عنوان URL | Domain name + pathاسم النطاق زائد المسار | http://myHome.com/lamps/123 | Which resource?أي مورد؟ |
| 2. HTTP request method2. طريقة طلب HTTP | GET, POST, PUT, DELETEGET، POST، PUT، DELETE | PUT | What to do with it?ماذا نفعل به؟ |
| 3. HTTP response status code3. رمز حالة استجابة HTTP | 100 to 599من 100 إلى 599 | 200 OK | Did it work, whose fault?هل نجح، وعلى من الخطأ؟ |
| 4. Header fields4. حقول الترويسة (header fields) | Metadata: cookies, tokens, Content-Typeبيانات وصفية: cookies، والرموز (tokens)، وContent-Type | Content-Type: application/json | What surrounds the message?ما الذي يحيط بالرسالة؟ |
| 5. JSON message5. رسالة JSON | Representation of state or requested changeتمثيل للحالة أو للتغيير المطلوب | {"id": 123, "Enabled": true, "ON": true, "brightness": 60} | What is the data?ما البيانات؟ |
| Methodالطريقة | /lamps/lamps | /lamps/123/lamps/123 | JSON objectكائن JSON |
|---|---|---|---|
| GET | List all lamps in the houseعرض قائمة بكل المصابيح في المنزل | Get information about lamp 123جلب معلومات المصباح 123 | Response: {"id": 123, "Enabled": true, "ON": true, "brightness": 35}الاستجابة: {"id": 123, "Enabled": true, "ON": true, "brightness": 35} |
| DELETE | Disable all lampsتعطيل كل المصابيح | Disable lamp 123تعطيل المصباح 123 | Response: {"id": 123, "Enabled": false}الاستجابة: {"id": 123, "Enabled": false} |
| PUT | Change brightness, turn on or off, or enable allتغيير السطوع، أو التشغيل والإطفاء، أو تفعيل الكل | Same for lamp 123الشيء نفسه للمصباح 123 | Request: {"id": 123, "Enabled": true, "ON": true, "brightness": 60}الطلب: {"id": 123, "Enabled": true, "ON": true, "brightness": 60} |
| POST | Find 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} |
- 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 OK | Succeededنجح الطلب | X = 1, Y = 2, result 3X = 1، Y = 2، والنتيجة 3 | Nobodyلا أحد |
| 400 Bad Request | Client error in the requestخطأ من العميل في الطلب | X missing or "abc"; division by Y = 0X مفقود أو قيمته "abc"، أو قسمة على Y = 0 | Clientالعميل |
| 406 Not Acceptable | No representation matches Acceptلا يوجد تمثيل يطابق Accept | Accept: application/xml | Clientالعميل |
| 500 Internal Server Error | Unexpected server conditionحالة غير متوقعة في الخادم | Exception in the addition codeاستثناء (exception) في شيفرة الجمع | Serverالخادم |
| 503 Service Unavailable | Overload or maintenance; may send Retry-Afterحمل زائد أو صيانة، وقد يرسل Retry-After | Too many requests, or an upgradeطلبات كثيرة جدًا، أو ترقية | Serverالخادم |
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.