Velamuvi AIAcademy

Lesson 3 of 12 · How the Web Talks

Methods: GET, POST, PUT, DELETE

Learn the HTTP methods GET, POST, PUT, PATCH and DELETE with simple definitions, the CRUD idea, resources and safe retries, plus runnable Python examples and real API calls.

  • 7 min read
  • Beginner
  • Reviewed
In this lesson you will learn
  • What an HTTP method is
  • When to use GET, POST, PUT, PATCH and DELETE
  • What CRUD and resources mean
  • Which requests are safe to repeat

The verb of a request

Every HTTP request starts with a word that says what kind of action you want. In the last lesson, the weather request started with GET.

The URL says which resource. The method says what to do with it.

The five methods you will use

CRUD: the four basic jobs

Each CRUD job has a matching method:

JobMethodExample requestMeaning
CreatePOSTPOST /notesadd a new note
ReadGETGET /notes or GET /notes/1list all notes, or get note 1
UpdatePUT or PATCHPATCH /notes/1change note 1
DeleteDELETEDELETE /notes/1remove note 1

Notice that one URL, /notes/1, can be read, changed or deleted. Only the method changes.

A pretend notes server

To see how a server reacts to each method, here is a tiny pretend API written as a Python function. It keeps notes in a dictionary and answers with a status code and some data.

Try it yourselfPython
notes = {1: "Buy milk"}
next_id = 2


def handle(method, path, body=None):
    global next_id
    if path == "/notes" and method == "GET":
        return 200, notes
    if path == "/notes" and method == "POST":
        notes[next_id] = body
        next_id += 1
        return 201, {"created": next_id - 1}
    note_id = int(path.split("/")[2])          # "/notes/1" -> 1
    if note_id not in notes:
        return 404, {"error": "No such note"}
    if method == "GET":
        return 200, notes[note_id]
    if method == "PUT":
        notes[note_id] = body
        return 200, notes[note_id]
    if method == "DELETE":
        del notes[note_id]
        return 204, None
    return 405, {"error": "Method not allowed"}


print(handle("GET", "/notes"))
print(handle("POST", "/notes", "Learn about APIs"))
print(handle("PUT", "/notes/1", "Buy oat milk"))
print(handle("GET", "/notes/1"))
print(handle("DELETE", "/notes/1"))
print(handle("GET", "/notes"))
print(handle("GET", "/notes/1"))

Read the output line by line. The same path gives different results depending on the method, and asking for a deleted note gives 404, which means "not found". Status codes are the next lesson.

Methods with a real API

JSONPlaceholder is a free practice API with fake blog posts. It accepts every method, so it is perfect for trying them out. (It only pretends to save your changes, so nothing really changes on the server.)

Try it yourselfPython
import requests

base = "https://jsonplaceholder.typicode.com"

response = requests.get(f"{base}/posts/1", timeout=10)
print("GET   ", response.status_code, response.json()["title"][:40])

new_post = {"title": "My first post", "body": "Hello, API!", "userId": 1}
response = requests.post(f"{base}/posts", json=new_post, timeout=10)
print("POST  ", response.status_code, response.json())

response = requests.patch(f"{base}/posts/1", json={"title": "A better title"}, timeout=10)
print("PATCH ", response.status_code, response.json()["title"])

response = requests.delete(f"{base}/posts/1", timeout=10)
print("DELETE", response.status_code)

The requests library has one function per method: get, post, put, patch and delete. The json= argument puts your data in the request body. You will learn more about bodies later in the course.

Which requests are safe to repeat?

Why care? Networks fail. Sometimes you send a request and never hear back, so you do not know whether it worked. Sending it again is:

  • fine for GET: you just read the data twice.
  • fine for PUT and DELETE: replacing note 1 with the same text twice, or deleting it twice, ends in the same state.
  • risky for POST: you might create two orders, or charge a customer twice.

You will use this rule in the Rate Limits and Retries lesson.

Common mistakes

Practice exercise

Finish a pretend to-do server so it can also change and delete tasks.

Your solutionPython
tasks = {1: "Write lesson", 2: "Test code"}


def handle(method, task_id=None, body=None):
    if method == "GET":
        return 200, tasks
    if method == "POST":
        new_id = max(tasks) + 1
        tasks[new_id] = body
        return 201, new_id
    # Add two more methods here:
    # DELETE: if task_id is in tasks, delete it and return 204, None.
    #         Otherwise return 404, "Not found".
    # PATCH:  if task_id is in tasks, set its text to body and return 200, tasks[task_id].
    #         Otherwise return 404, "Not found".
    return 405, "Method not allowed"


print(handle("POST", body="Publish course"))
print(handle("PATCH", 2, "Test every example"))
print(handle("DELETE", 1))
print(handle("DELETE", 1))
print(handle("GET"))

# Output must be exactly:
# (201, 3)
# (200, 'Test every example')
# (204, None)
# (404, 'Not found')
# (200, {2: 'Test every example', 3: 'Publish course'})
Knowledge check

Which method should you use to create a new item, such as a new order?

Summary

  • The HTTP method says what to do. The URL says which resource to do it to.
  • GET reads, POST creates, PUT replaces, PATCH changes part and DELETE removes.
  • Together these cover CRUD: create, read, update and delete.
  • GET is safe. GET, PUT and DELETE are idempotent, so they are safe to retry. POST is not.

Next: the numbers that tell you whether a request worked.

Finished reading? Tick it off to track your progress.