Débutant20 min de lecture

HTTP Protocol Basics

Understand HTTP requests, responses, status codes, headers, and the JSON data format.

HTTP Requests

HTTP (HyperText Transfer Protocol) is the language that clients and servers use to communicate. Every time your browser loads a page, submits a form, or fetches data, it sends an HTTP request to a server.

An HTTP request has four main parts:

1. Method — The action to perform (GET, POST, PUT, DELETE). This tells the server what you want to do.

2. URL — The address of the resource you want. For example, https://api.example.com/users/42 targets user 42 on the example API.

3. Headers — Metadata about the request. Headers are key-value pairs that provide additional context. Common headers include:

  • Content-Type: application/json — tells the server you are sending JSON data
  • Authorization: Bearer abc123 — sends an authentication token
  • Accept: application/json — tells the server you want JSON back
  • User-Agent: Mozilla/5.0... — identifies your browser

4. Body — The actual data being sent (only for POST, PUT, PATCH). When you create a new user, the body contains the user's name, email, and password as JSON data.

Conceptually, a raw HTTP request looks like this:

html
POST /users HTTP/1.1
Host: api.example.com
Content-Type: application/json
Authorization: Bearer abc123

{"name": "Alice", "email": "alice@example.com"}

The first line specifies the method, the path, and the HTTP version. The following lines are headers. After a blank line comes the body. Your browser constructs these requests automatically, but understanding their structure is essential for building and debugging APIs.

HTTP Responses

When a server receives a request, it processes it and sends back an HTTP response. A response also has a specific structure:

1. Status Code — A three-digit number that tells you what happened. This is the first thing you check. 200 means success, 404 means not found, 500 means the server broke. Status codes are grouped by their first digit:

  • 2xx (Success) — The request was received, understood, and accepted. Everything worked.
  • 3xx (Redirection) — The resource has moved. The client needs to go to a different URL.
  • 4xx (Client Error) — Something is wrong with the request. The client made a mistake (bad URL, missing data, wrong credentials).
  • 5xx (Server Error) — Something went wrong on the server. The request was valid, but the server failed to process it.

2. Headers — Response metadata. The server sends back headers like:

  • Content-Type: application/json — the response body is JSON
  • Content-Length: 256 — the body is 256 bytes
  • Set-Cookie: session=abc123 — sets a cookie in the browser
  • Cache-Control: max-age=3600 — the client can cache this for 1 hour

3. Body — The actual data. For an API, this is usually JSON. For a web page, it is HTML. For an image, it is binary data.

A raw HTTP response looks like this:

html
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 45

{"id": 42, "name": "Alice", "role": "admin"}

The first line has the HTTP version, status code, and a human-readable status text. Then headers, a blank line, and the body.

Common Status Codes

Memorizing the most common status codes will make you a more effective developer. Here are the ones you will encounter daily:

Success (2xx):

  • 200 OK — The request succeeded. The server is returning the requested data. Example: successfully loading a user's profile.
  • 201 Created — A new resource was created successfully. Example: a new blog post was saved to the database.
  • 204 No Content — The request succeeded but there is nothing to return. Example: successfully deleting a record.

Redirection (3xx):

  • 301 Moved Permanently — The resource has a new permanent URL. Example: a website changed its domain from old-site.com to new-site.com.
  • 304 Not Modified — The resource has not changed since the last request. Example: the browser can use its cached version.

Client Errors (4xx):

  • 400 Bad Request — The request data is invalid or malformed. Example: submitting a form with a missing required field.
  • 401 Unauthorized — Authentication is required but was not provided or is invalid. Example: trying to access your dashboard without logging in.
  • 403 Forbidden — You are authenticated but do not have permission. Example: a regular user trying to access an admin panel.
  • 404 Not Found — The requested resource does not exist. Example: navigating to a URL that does not match any page.
  • 429 Too Many Requests — You are sending too many requests too quickly (rate limiting). Example: making 1000 API calls per minute.

Server Errors (5xx):

  • 500 Internal Server Error — Something unexpected went wrong on the server. Example: a bug in the server code caused it to crash.
  • 503 Service Unavailable — The server is temporarily down (maintenance, overload). Example: a website during a traffic spike.

JSON — The Language of APIs

JSON (JavaScript Object Notation) is the standard data format for APIs. When a client and server exchange data, they almost always use JSON. It is a way to represent structured data as plain text.

JSON looks very similar to JavaScript objects, but there are strict rules:

  • Keys must be strings in double quotes: "name", not name or 'name'
  • Strings must use double quotes: "hello", not 'hello'
  • Values can be: strings, numbers, booleans (true/false), null, arrays, or objects
  • No trailing commas: the last item in an array or object cannot have a comma after it
  • No comments: JSON does not support // or /* */ comments
  • No functions: JSON is data only, not code

Here is an example of JSON representing a user:

json
{
  "id": 42,
  "name": "Alice Johnson",
  "email": "alice@example.com",
  "isAdmin": false,
  "age": 28,
  "address": {
    "city": "San Francisco",
    "country": "US"
  },
  "hobbies": ["coding", "hiking", "reading"]
}

JavaScript has two built-in methods for working with JSON:

  • JSON.stringify(object) — converts a JavaScript object into a JSON string. This is what happens when your server sends data to a client.
  • JSON.parse(jsonString) — converts a JSON string back into a JavaScript object. This is what happens when your client receives data from a server.

JSON won the data format wars because it is human-readable (you can look at it and understand it), lightweight (less overhead than alternatives like XML), and universal (every programming language has built-in JSON support).

Working with JSON in JavaScript

html
<div id="output" style="font-family:monospace; padding:16px;"></div>

<script>
  // A JavaScript object (what your server works with)
  const user = {
    id: 42,
    name: "Alice Johnson",
    email: "alice@example.com",
    isAdmin: false,
    hobbies: ["coding", "hiking"]
  };

  // Convert object to JSON string (server sending data)
  const jsonString = JSON.stringify(user, null, 2);

  // Convert JSON string back to object (client receiving data)
  const parsed = JSON.parse(jsonString);

  const output = document.getElementById("output");
  output.innerHTML = "<strong>Original object type:</strong> " + typeof user
    + "<br><br><strong>JSON string:</strong><pre>" + jsonString + "</pre>"
    + "<strong>Parsed back — name:</strong> " + parsed.name
    + "<br><strong>Parsed back — hobbies:</strong> " + parsed.hobbies.join(", ");
</script>

What status code means 'resource not found'?

Prêt à pratiquer ?

Crée ton compte gratuit pour accéder à l'éditeur de code interactif, lancer les défis et suivre ta progression.