انتقل إلى المحتوى
أمين أبوزيد
منشورBEG-052-L02

الدوال: GET وPOST وPUT وPATCH وDELETE

  • الدرس 2 من 7
  • 10 دقيقة قراءة
  • مبتدئ
في هذا الدرس 11 موضوعات

هذا الدرس متاح حاليًا باللغة الإنجليزية فقط، ولم تُنشر نسخته العربية بعد.

Lesson Overview

In the restaurant picture, the method is the verb on the order slip: "bring me the menu", "add a dish to my table", "replace my order", "change one thing", "cancel it". The method is the first word of the request line, and it states what you want done with the resource named in the target.

Choosing the right method is not decoration. Browsers, caches, search crawlers, and retry logic all make decisions based on the method alone. A wrong choice can cause a page crawler to delete your data, or a retry to charge a customer twice.

This lesson covers the five methods you will use most, introduces the two words that separate them (safe and idempotent), and builds a small book-API table you can reuse. It builds on lesson 1 (the request line) and on the idea of a resource from BEG-003.

Learning Objectives

By the end of this lesson you will be able to:

  • Say what GET, POST, PUT, PATCH, and DELETE each mean.
  • Choose the right method for a read, a create, a full replace, a partial change, and a removal.
  • Explain what safe and idempotent mean and classify the five methods.
  • Explain why a GET must never change data.
  • Distinguish PUT (replace the whole resource) from PATCH (change part of it).
  • Write the request lines for a small book API.

Written Explanation

Resources and verbs

A web API is organized around resources: things such as books, members, or orders. Each resource has a URL. A collection is usually named in the plural, /books, and one item adds its id, /books/7. The method is the verb applied to that noun. So the pair DELETE /books/7 reads like a sentence: delete book 7. (REST, the style that builds on this idea, is a topic for BEG-053.)

The five methods

According to MDN's method reference:

MethodMeaningTypical bodyExample
GETRetrieve a representation of a resourceNoGET /books/7
POSTSubmit data to the resource, often creating something or causing a changeYesPOST /books
PUTReplace the target resource with the data sentYesPUT /books/7
PATCHApply a partial changeYesPATCH /books/7
DELETEDelete the resourceUsually noDELETE /books/7

Notes on each:

  • GET only reads. It is what a browser sends when you type a URL or click a link.
  • POST is the general-purpose "do something with this data". The usual use in an API is creating a new item in a collection: you post to /books, and the server decides the new id.
  • PUT sends a complete new version. Whatever fields you leave out are not kept; the resource becomes exactly what you sent.
  • PATCH sends only the changes, such as just the new title.
  • DELETE removes it.

Safe and idempotent

Two words from the HTTP rules sort the methods.

  • A method is safe if it is meant only to read and not change the server's state.
  • A method is idempotent if sending the same request several times has the same effect on the server as sending it once.
MethodSafeIdempotent
GETYesYes
POSTNoNo
PUTNoYes
PATCHNoNo (in general)
DELETENoYes

Why does idempotent matter? Imagine your phone sends a request and the connection drops before you see the answer. Did it arrive? If the method is idempotent, a retry is harmless: setting book 7's title to "Dune" twice leaves it as "Dune". If it is not, a retry might do the work twice: posting the same new book twice usually creates two books.

DELETE is idempotent because after the first call the book is gone and after the tenth it is still gone. The response may differ (the second call may say "not found"), but the server's state is the same. PATCH is not idempotent in general: a patch such as "add 1 to the stock" changes the result each time. A patch such as "set the title to Dune" happens to be harmless to repeat, but nothing in the method guarantees it.

Why a GET must never change data

Because GET is safe, the whole web assumes it can be called freely. Browsers prefetch links, crawlers follow every link they find, and caches may store the answer and reuse it. If a link like GET /deleteBook?id=7 removes a book, then a crawler visiting your page would delete your data without anyone clicking anything. Reading and changing must be separate methods so that those tools stay harmless.

PUT versus PATCH

Suppose book 7 is {"id":7,"title":"Dune","year":1965}.

  • PUT /books/7 with {"id":7,"title":"Dune Messiah","year":1969} replaces the whole thing. If the body had only the title, then in a strict replace the year would be gone (how a particular server treats the missing field is the server's design choice, but replace semantics are what PUT promises).
  • PATCH /books/7 with {"title":"Dune Messiah"} changes the title and leaves the rest alone.

Use PUT when the client has the complete new version, PATCH when it only wants to change a few fields.

Examples

Example 1: Matching verbs to jobs (simple)

JobRequest line
Read the list of booksGET /books
Read book 7GET /books/7
Add a new bookPOST /books
Replace book 7 completelyPUT /books/7
Fix only the title of book 7PATCH /books/7
Remove book 7DELETE /books/7

Notice how the path names the noun and the method carries the verb. There is no /addBook or /deleteBook anywhere.

Example 2: A full create-and-fix conversation (practical)

  1. Create:
text
POST /books HTTP/1.1
Host: api.example.com
Content-Type: application/json

{"title":"Dun","year":1965}

The server answers 201 Created and the body shows the new book with "id":8.

  1. The title has a typo. Only one field is wrong, so PATCH:
text
PATCH /books/8 HTTP/1.1
Host: api.example.com
Content-Type: application/json

{"title":"Dune"}
  1. Check the result: GET /books/8 returns {"id":8,"title":"Dune","year":1965}.

Three requests, three methods, each with a clear purpose. Step 3 is safe: asking again changes nothing.

Example 3: Retrying after a lost answer (realistic)

A mobile app sends POST /orders. The network drops, so the app never sees the reply. Should it send again?

  • If the first request did arrive, a second POST creates a second order, because POST is not idempotent. The customer is charged twice.
  • If the request had been PUT /orders/55 with the full order, retrying is harmless: the order ends up in the same state.

This is why real payment systems often add an extra identifier to POST requests so the server can recognize a repeat. The technique goes beyond this lesson; the point here is that the method's guarantees decide how safe retrying is.

Backend Insight

When you write a backend, you will connect each method and path to a piece of code. Your choice of method is a promise to every client: "calling this with GET will not change anything", "calling this with PUT repeatedly is fine". Clients, caches, and gateways rely on those promises, so breaking them (a GET that deletes, a POST used for reading everything) causes bugs that are hard to trace.

Also remember that a method is a convention enforced by your code. HTTP does not stop a server from deleting data on a GET. The protocol describes what clients may assume; you are responsible for living up to it.

A practical habit: before writing an endpoint, write its request line and ask two questions. Does it change data? Is it safe to repeat? The answers pick the method.

Common Mistakes

Mistake 1: A GET with side effects

  • Incorrect: GET /deleteBook?id=7 or GET /approveOrder?id=3.
  • Correct: DELETE /books/7, and POST or PATCH for the order change.

Crawlers, prefetching, and caches may call a GET at any time.

Mistake 2: Putting the verb in the path

  • Incorrect: POST /createBook and POST /deleteBook/7.
  • Correct: POST /books and DELETE /books/7.

The method already carries the verb.

Mistake 3: Using PUT for a one-field change

  • Incorrect: sending PUT /books/7 with only {"title":"New"} and expecting the other fields to survive.
  • Correct: use PATCH for partial changes, or send the whole book with PUT.

Mistake 4: Assuming every method is safe to retry

  • Incorrect: "The network failed, so I will just resend the POST."
  • Correct: resending a POST may do the work twice; resending GET, PUT, or DELETE is designed to be safe.

Exercises

Level A: Foundation

A1. Choose a method for each: list all members; add a member; replace member 4; change only member 4's phone number; remove member 4.

أظهر الحل A1

A1. GET /members; POST /members; PUT /members/4; PATCH /members/4; DELETE /members/4.

A2. Which of the five methods are safe? Which are idempotent?

أظهر الحل A2

A2. Only GET is safe. GET, PUT, and DELETE are idempotent; POST and (in general) PATCH are not.

A3. In one sentence, what is the difference between PUT and PATCH?

أظهر الحل A3

A3. PUT replaces the whole resource with the data sent; PATCH changes only the parts described.

Level B: Application

B1. Write the request line for each task in a movie API: show movie 12; create a movie; delete movie 12; replace movie 12; rename movie 12.

أظهر الحل B1

B1. GET /movies/12; POST /movies; DELETE /movies/12; PUT /movies/12; PATCH /movies/12.

B2. A coworker wrote the link <a href="/archiveBook?id=9">Archive</a> that archives a book when clicked. Explain what could go wrong, and propose a better request.

أظهر الحل B2

B2. A link makes the browser send GET. Crawlers, prefetching, or anyone opening the link could archive the book without a deliberate action, and caches may repeat it. Better: PATCH /books/9 with {"archived":true}, sent from a button or script, or POST if the server treats it as an action.

B3. A request PATCH /stock/5 with body {"add":1} is retried three times after timeouts. What may happen, and why does it differ from PUT /stock/5 with {"count":10}?

أظهر الحل B3

B3. The first request adds 1, so after four sends the stock may be 4 higher than intended (this PATCH is not idempotent). PUT with count:10 sets the same final state every time.

Level C: Challenge

C1. Design the request lines for a small to-do API: list tasks, add a task, mark task 3 as done (only one field changes), rewrite task 3 completely, and delete task 3. For each, state if it is safe and if it is idempotent.

أظهر الحل C1

C1. GET /tasks (safe, idempotent); POST /tasks (neither); PATCH /tasks/3 with {"done":true} (not safe; not guaranteed idempotent as a method, though this particular body is harmless to repeat); PUT /tasks/3 (not safe, idempotent); DELETE /tasks/3 (not safe, idempotent).

C2. A client calls DELETE /books/7 twice. The first answer is 204, the second is 404. A teammate says "DELETE is not idempotent because the answers differ." Reply to them using the definition.

أظهر الحل C2

C2. Idempotent is about the effect on the server, not the response. After the first call book 7 is gone; after the second it is still gone, so the state is the same. The 404 just reports that there was nothing left to delete.

Mini Challenge

Pick a topic you know (a school, a gym, a recipe site) and choose one resource. Write a table of six request lines: list, read one, create, replace, partially change, delete. For each, add two columns: safe (yes/no) and idempotent (yes/no). Then write one sentence on what could go wrong if the "read one" request were implemented with side effects.

Check your work: nouns in paths, verbs only in methods, plural collection and id for one item, and a table that matches the safe and idempotent table in this lesson.

Summary & Next Lesson

Key takeaways

  • The method states what to do with the resource: GET read, POST create/submit, PUT replace, PATCH partial change, DELETE remove.
  • GET is safe: it must not change data, because browsers, crawlers, and caches may call it freely.
  • Idempotent means repeating the request leaves the server in the same state: GET, PUT, DELETE are; POST and generally PATCH are not.
  • Put nouns in the path and verbs in the method.

Next lesson

The next lesson, "Status codes", covers the number in the response: how to tell success from client error from server error.

Self-check

  1. Which method reads data without changing it?
  2. Which method is normally used to create a new item in a collection?
  3. What is the difference between PUT and PATCH?
  4. What does idempotent mean?
  5. Why is GET /deleteBook?id=7 a bad design?
أظهر الإجابات
  1. GET.
  2. POST, for example POST /books.
  3. PUT replaces the whole resource; PATCH changes part of it.
  4. Sending the same request several times has the same effect as sending it once.
  5. A GET must be safe; crawlers, prefetching, and caches may call it, so it could delete data without a deliberate request. Use DELETE /books/7.

References

  • MDN: HTTP request methods. Supports the meaning of GET, POST, PUT, PATCH, and DELETE, the definitions of safe and idempotent, the classification table, and the examples of why POST and counter-incrementing PATCH are not idempotent.
  • MDN: An overview of HTTP. Supports the client/server request-response model referred to in the overview.

I did not verify the claim that real payment systems add a request identifier to POST requests; it is stated here as a general practice, not a source-backed fact.

التطبيق

طبّق هذا الدرس بمختبر الوحدة وتمارينها واختبارها.

المختبر والتمارين الاختبار

تعليم الدرس كمكتمل اختياري ويمكنك التراجع عنه في أي وقت. يبقى تقدمك محفوظًا في هذا المتصفح.

اكتب للبحث في المستويات والمراحل والوحدات والدروس.