Skip to main content

Lesson 2 of 4 18 min read

HTTP, REST APIs, requests and responses

Understand the structure of HTTP messages, the main methods and status codes, and how REST APIs exchange JSON.

In this lesson you will

  • Identify the parts of an HTTP request and response
  • Match HTTP methods to create, read, update and delete operations
  • Read a REST API design and call it from JavaScript with fetch

HTTP: the language of the web

The frontend and backend communicate using HTTP (HyperText Transfer Protocol). Every exchange is a request from the client followed by a response from the server.

A request contains:

  • a method describing the action, such as GET or POST;
  • a URL identifying the resource;
  • headers with extra information, such as the content type or a session cookie;
  • an optional body with data, usually JSON.
HTTP
POST /api/students HTTP/1.1
Host: api.example.com
Content-Type: application/json

{"name": "Ravi Kumar", "email": "ravi@example.com"}

A response contains a status code, headers and usually a body:

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

{"id": 42, "name": "Ravi Kumar", "email": "ravi@example.com"}

Methods and CRUD

Most applications Create, Read, Update and Delete data (CRUD). HTTP methods map onto these actions:

MethodActionExample
GETReadGET /api/courses lists courses
POSTCreatePOST /api/courses adds a course
PUTReplace / updatePUT /api/courses/7 updates course 7
PATCHPartial updatePATCH /api/courses/7 changes one field
DELETEDeleteDELETE /api/courses/7 removes course 7

GET requests must not change data, which lets browsers and caches repeat them safely.

Status codes

RangeMeaningCommon codes
2xxSuccess200 OK, 201 Created, 204 No Content
3xxRedirection301 Moved Permanently, 304 Not Modified
4xxClient error400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found
5xxServer error500 Internal Server Error, 503 Service Unavailable

A 4xx code means the request needs fixing; a 5xx code means the server failed.

REST APIs and JSON

An API (Application Programming Interface) is a defined way for programs to talk to each other. A REST API organises data as resources identified by URLs and manipulated with the standard HTTP methods:

  1. /api/courses (collection)
  2. /api/courses/7 (one course)
  3. /api/courses/7/lessons (its lessons)
3-step diagram

Data is exchanged as JSON (JavaScript Object Notation):

JSON
{
  "id": 7,
  "title": "Web Development Basics",
  "level": "Beginner",
  "lessons": 5,
  "free": true
}

JSON supports objects {}, arrays [], strings, numbers, booleans and null.

One REST call from start to finish

Browser sends to API: GET /api/courses/7. API sends to Database: find course 7. Database replies to API: the course row. API replies to Browser: 200 OK + JSON

Calling an API from the frontend

Browsers provide fetch for HTTP requests:

JavaScript
async function loadCourses() {
  const response = await fetch("/api/courses");
  if (!response.ok) {
    throw new Error(`Request failed with status ${response.status}`);
  }
  const courses = await response.json();
  console.log(courses.map((c) => c.title));
}

async function addStudent(name, email) {
  const response = await fetch("/api/students", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ name, email }),
  });
  return response.json();
}

await pauses the function until the network response arrives without freezing the page. Always check response.ok (true for 2xx statuses) before using the data.

Hands-on exercise

Design a REST API for a library. List the method and URL you would use to list all books, view one book, add a book, change a book's title and remove a book. Then write the JSON body you would send to add a book with a title, author and year. Finally, open https://api.github.com/users/octocat in your browser and identify three fields in the JSON response.

Knowledge check

3 questions • 70% to pass • Practice only, no certificate

  1. 1.Which method should you use to remove the course at /api/courses/9?
  2. 2.A user requests a page they are not allowed to see while logged in. Which status fits best?
  3. 3.What does response.json() do in the fetch example?
0 of 3 answered

Key concepts

  • An HTTP request has a method, URL, headers and an optional body; a response has a status code, headers and a body.
  • GET reads, POST creates, PUT and PATCH update, DELETE removes.
  • 2xx means success, 4xx means a client error and 5xx means a server error.
  • REST APIs expose resources at URLs and usually exchange JSON; fetch calls them from the browser.