{module 6}
HTTP: requests, responses and status codes
How programs talk to each other20 min read
What you will be able to do
- Read a request and its response in the browser's Network panel: the method, the address, the status code and the headers.
- Say from the first digit of a status code where a problem is: in the address, in the server, or somewhere else.
- Build a page that explains status codes from a list of data.
Why it matters
Lima Ceviche Bar is a restaurant in Lima, Peru. Each table has a card with the address of the menu page. One Saturday, customers said the address showed an error. Rosa Quispe, the owner, spent the morning on the phone with her internet company, who said her connection was fine.
Her nephew Diego opened the menu address with the developer tools open. One number told him where the fault was: the server answered 404. The connection and the server were working. The server had nothing at that address, because someone had renamed the menu file the day before. He put the old name back, and the cards worked again.
That number is a status code. This lesson shows you how to read it.
The idea
Two messages
In module 1 you met the two programs that take part when a page opens. The client asks, and the server answers. The question is a request and the answer is a response. The rules that both messages follow are called HTTP, short for HyperText Transfer Protocol. A protocol is a set of rules for a conversation.
Every page, stylesheet, script and picture arrives this way, one request and one response each. Later in this module your own JavaScript will send requests.
The request: a method and an address
A request says what the client wants to do, and where. The method is what it wants to do, in one word in capital letters.
GETasks for something. Typing an address and pressing Enter sends aGET.POSTsends something to the server, such as the answers in a form.
There are others, such as PUT and DELETE, to change or remove things. In this course you only send GET.
The address is the one you know from module 1: the rules (https://), the name of the server and the path. Some addresses have one more part, after a question mark. This query carries extra details for the server, as pairs of a name and a value joined by &. Here is an address with a query:
https://api.open-meteo.com/v1/forecast?latitude=-12.05&longitude=-77.04¤t=temperature_2m
The path is /v1/forecast. The query asks for the current temperature at latitude -12.05 and longitude -77.04, which is Lima. You will use this server for the rest of the module.
The response: a status code, headers and content
A response has three parts.
The status code is a three-digit number that says how the request went. The first digit tells you the kind of answer.
| First digit | Kind | Example |
|---|---|---|
| 2 | Success | 200 OK |
| 3 | Look somewhere else | 301 Moved Permanently |
| 4 | A mistake in the request | 404 Not Found |
| 5 | The server failed | 500 Internal Server Error |
Codes that start with 1 exist too, and you will rarely see them. When a 4 comes back, look at what was asked for: the address, its spelling, the query. When a 5 comes back, the server broke while it answered, and only the people who run it can fix that.
The headers are extra facts about the message, one per line, each a name and a value. The most useful one is Content-Type, which says what kind of content follows. text/html is a page, text/css is a stylesheet, and application/json is data for a program, which is the subject of the next lesson. Requests have headers too.
The content is the thing itself: the HTML of the page, the CSS, or the data.
Seeing it in the Network panel
The browser shows every request in the developer tools, which you opened in module 1. These steps are the same in Chrome and Edge, and Firefox differs only in names.
- Open the developer tools. Press F12, or Ctrl+Shift+I on Windows and Linux, or Cmd+Option+I on a Mac.
- Click the tab called Network.
- Reload the page. The panel records only while it is open, so it starts empty.
- Each row is one request. The first row is usually the page itself. The columns show its name, its status code and its type.
- Click a row. A Headers tab opens. In Chrome and Edge it has three parts: General (the address, the method and the status code), Response Headers and Request Headers. Firefox shows the status at the top and the two lists of headers below it.
- Click Response to see the content as it arrived.
Worked example
Rosa asked Diego for a page that tells her staff what each code means. He built it from a list of data, with the loop from module 4.
Make a folder called status-codes and open it in Visual Studio Code. Create index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Status codes, Lima Ceviche Bar</title>
<script src="codes.js" defer></script>
</head>
<body>
<main>
<h1>What the server answered</h1>
<p>Status codes we have seen on our menu page, and what each one means.</p>
<ul id="codes"></ul>
</main>
</body>
</html>Create codes.js in the same folder:
const statusCodes = [
{ code: 200, name: "OK", meaning: "The menu page arrived." },
{ code: 301, name: "Moved Permanently", meaning: "The menu has a new address." },
{ code: 404, name: "Not Found", meaning: "Nothing is at this address. Check the spelling." },
{ code: 500, name: "Internal Server Error", meaning: "The server broke while it answered." },
];
// The first digit says what kind of answer it is, so test the highest group first.
function kindOf(code) {
if (code >= 500) {
return "the server failed";
} else if (code >= 400) {
return "a mistake in the request";
} else if (code >= 300) {
return "look somewhere else";
} else {
return "success";
}
}
const list = document.querySelector("#codes");
for (const status of statusCodes) {
const item = document.createElement("li");
item.textContent = `${status.code} ${status.name}: ${kindOf(status.code)}. ${status.meaning}`;
list.append(item);
}Save both files and open index.html in your browser. The page shows:
What the server answered
Status codes we have seen on our menu page, and what each one means.
200 OK: success. The menu page arrived.
301 Moved Permanently: look somewhere else. The menu has a new address.
404 Not Found: a mistake in the request. Nothing is at this address. Check the spelling.
500 Internal Server Error: the server failed. The server broke while it answered.Lines 1 to 6 are the data: an array of objects, one object for each code. Lines 9 to 19 are a function that turns a code into its kind. A code of 404 is not 500 or more, so the first test fails, and the second test, 400 or more, is true. Lines 23 to 27 build one list item for each object, as in module 4.
Common mistakes
Testing the smallest group first
Here is the same function with the tests in the opposite order, in wrong-order.js:
if (code >= 200) {
return "success";
} else if (code >= 300) {
return "look somewhere else";
} else if (code >= 400) {
return "a mistake in the request";
} else {
return "the server failed";
}There is no error in the Console. The list shows:
200 OK: success. The menu page arrived.
301 Moved Permanently: success. The menu has a new address.
404 Not Found: success. Nothing is at this address. Check the spelling.
500 Internal Server Error: success. The server broke while it answered.Every code is called a success. Use the debugging loop. Read: the page is wrong for 404. One guess: the first test that is true wins, and the others are never asked. Test the guess by hand: is 404 more than or equal to 200? Yes, so the function returns at once. Put the highest group first, as in codes.js.
An empty Network panel
You open the Network panel on a page that has already loaded and see no rows. Nothing is broken. The panel records only while it is open. Reload the page.
Calling every problem "the internet"
A 404 is an answer, so the connection worked and the address is wrong. With no connection, no answer comes back, and the row in the Network panel has no status code at all. Rosa lost a morning because nobody looked.
Think it through
Yusuf, a learner, wants Diego's page to include 403 Forbidden, the answer a server gives when you are not allowed to see something.
Understand. One new code must appear, in the right group, and the other four lines must not change.
Break down. Add the data. Check that kindOf puts 403 in the right group.
Plan. Add one object between 301 and 404, so the list stays in order. Change nothing else, because the function already tests by range.
Build. He adds { code: 403, name: "Forbidden", meaning: "You are not allowed to see this." }, and saves.
Test. He reloads. The new line says "403 Forbidden: a mistake in the request", as the table predicts. For an odd case, he takes 499 and 500, either side of a border. 499 fails the first test and passes the second, so it is a mistake in the request. 500 is the server. Both are right.
Reflect. Because the codes are data and the rule is a function, a new code costs one line. Typed into the HTML by hand, each line would need its kind typed by hand too, and could be typed wrong.
At work
When you show someone your work, start with what it does for them. How you made it comes second, and only if they ask.
Diego wrote this to Rosa:
The menu cards work again. A customer who types the address now sees today's menu, and I tested it on two phones.
What happened: the menu file was renamed on Friday, so the address on the cards pointed at nothing. I have put the old name back. Before anyone renames a file on the site, please ask me first.
The first sentence answers Rosa's question: can customers see the menu? The second gives her a reason to believe it. The cause follows in words she knows, and the message ends with the one thing she must do. "The server returned a 404" is a sentence for another developer.
Your tasks
Task 1: Read a real request
Open a new tab, open the Network panel, and go to the address from "The idea":
https://api.open-meteo.com/v1/forecast?latitude=-12.05&longitude=-77.04¤t=temperature_2m
The page shows text with curly brackets, made for a program, not a person. Click the row for forecast in the Network panel and read its Headers tab.
You are done when you have written down the method, the status code and the value of Content-Type.
Task 2: Make it fail on purpose
Change forecast in the address to forcast and press Enter. Then put forecast back and change temperature_2m to temprature_2m. Read the status code each time, and the first words of the content.
You are done when you have two different status codes that both start with 4, and can say what was wrong with each request.
Task 3: Build the page and add two codes
Build the worked example. Then add 302 Found (the page is at another address for now) and 503 Service Unavailable (the server is too busy or closed for repair).
You are done when the page lists six codes in order, and each one shows the right kind.
Task 4: The fifth group
Codes from 100 to 199 mean "information". Change kindOf so that a code below 200 returns "information", and add 100 Continue to the data.
You are done when 100 shows "information" and the other six codes show exactly what they showed before.
Recap
- A client sends a request, and a server sends a response. HTTP is the set of rules for both.
- A request has a method, such as
GETorPOST, and an address. The query after?carries extra details. - A response has a status code, headers and content. The first digit of the code says where to look: 2 is success, 4 is the request, 5 is the server.
- The Network panel shows every request, but only while it is open. Reload to fill it.
Go deeper
- MDN: Overview of HTTP describes what a request and a response contain.
- MDN: HTTP response status codes lists every status code and what it means.
- MDN: HTTP request methods explains
GET,POSTand the others. - Chrome DevTools: Inspect network activity is a tutorial for the Network panel in Chrome and Edge.
- Firefox: Network Monitor describes the same panel in Firefox.