Skip to content
KALANBLON
Show contents

Chapter 1 of 7 · 20 min

HTTP requests and responses

By the end of this chapter, you'll be able to

  • Describe the parts of an HTTP request: method, path, headers, body
  • Describe the parts of an HTTP response: status code, headers, body
  • Choose the right method and the right status code
  • Represent data in JSON with JSON.stringify and JSON.parse

A conversation in two messages

On the web, the client (browser, mobile app) always speaks first: it sends a request. The server sends back a response. Here is a real request, as it travels:

POST /api/registrations HTTP/1.1
Host: kalanblon.example
Content-Type: application/json
Content-Length: 48

{"name":"Awa Traoré","course":"python-beginner"}
  • the request line: the method (POST), the path (/api/registrations) and the protocol version;
  • the headers: Name: value pairs describing the request (the target site, the content type…);
  • an empty line, then the body: the data sent, here in JSON.

And the response:

HTTP/1.1 201 Created
Content-Type: application/json

{"id":17,"name":"Awa Traoré","course":"python-beginner"}

The first line holds the status code (201) and its label. Then come the headers and the body.

The server replies: 201 means “created”, and the body contains the registration with its identifier.

Step 4 of 4
Text description of the animation
  1. The app sends a request with a JSON body: the name and the chosen course.
  2. The server takes the request apart: which action, on which resource, with which data.
  3. The API's code checks the data and saves it.
  4. The server replies: 201 means “created”, and the body contains the registration with its identifier.

Methods

The method says what the client wants to do:

MethodMeaningExample
GETreadGET /api/courses: the list of courses
POSTcreatePOST /api/registrations: a new registration
PUTreplacePUT /api/courses/3: replace course 3
PATCHpartly modifyPATCH /api/courses/3: change only the title
DELETEdeleteDELETE /api/registrations/17

A GET request must never modify data: browsers, robots and caches may repeat it freely.

Status codes

The status code has three digits, and the first one gives the family:

2xx  success        200 OK · 201 Created · 204 No Content
3xx  redirection    301 Moved Permanently · 304 Not Modified
4xx  client error   400 Bad Request · 401 Unauthorized · 403 Forbidden
                    404 Not Found · 409 Conflict · 422 Unprocessable Content
5xx  server error   500 Internal Server Error · 503 Service Unavailable

The rule: 4xx if the client made a mistake (invalid data, unknown resource), 5xx if the server has a problem.

JSON: the data format

APIs almost always exchange JSON (JavaScript Object Notation): text that looks like JavaScript objects. You go from an object to text with JSON.stringify, and from text to an object with JSON.parse:

const registration = { id: 17, name: "Awa Traoré", course: "python-beginner", paid: false };
const text = JSON.stringify(registration);
console.log(text);
console.log(typeof text);

const parsed = JSON.parse('{"id":18,"name":"Kofi Mensah","course":"sql-beginner"}');
console.log(parsed.name, parsed.id + 1);
{"id":17,"name":"Awa Traoré","course":"python-beginner","paid":false}
string
Kofi Mensah 19

JSON is stricter than JavaScript: property names are in double quotes, and there are no functions, no undefined and no trailing comma.

Mini-lab: building an HTTP responseJavaScript

Output

Click “Run” to execute your code.

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: the right method, the right status

For each situation, give the request's method and the response's status code:

1. The app displays the list of courses.
2. A student registers for a course; the registration is created.
3. We ask for course no. 999, which does not exist.
4. A student sends a registration without their name.
5. We delete registration no. 17; there is nothing to send back.
6. The server's database is down.
Hint 1
Read = GET, create = POST, delete = DELETE.
Hint 2
Who made the mistake: the client (4xx) or the server (5xx)?
Show the solution and common mistakes
1. GET    → 200 OK
2. POST   → 201 Created
3. GET    → 404 Not Found
4. POST   → 400 Bad Request (or 422 if the syntax is right but a field is missing)
5. DELETE → 204 No Content
6. any method → 500 Internal Server Error (or 503 if the outage is temporary)

Common mistakes:

  • Replying 200 to a creation: it works, but 201 says precisely that a resource was created.
  • Replying 500 when the client's data is invalid: the client must fix its request, so a 4xx code.

Summary

  1. 1An HTTP request contains a method, a path, headers and possibly a body.
  2. 2A response contains a status code, headers and a body.
  3. 3GET reads, POST creates, PUT and PATCH modify, DELETE deletes; GET never changes anything.
  4. 42xx codes signal success, 4xx a client error, 5xx a server error.
  5. 5APIs exchange JSON, converted with JSON.stringify and JSON.parse.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.