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
GETorPOST; - 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.
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/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:
| Method | Action | Example |
|---|---|---|
GET | Read | GET /api/courses lists courses |
POST | Create | POST /api/courses adds a course |
PUT | Replace / update | PUT /api/courses/7 updates course 7 |
PATCH | Partial update | PATCH /api/courses/7 changes one field |
DELETE | Delete | DELETE /api/courses/7 removes course 7 |
GET requests must not change data, which lets browsers and caches repeat them safely.
Status codes
| Range | Meaning | Common codes |
|---|---|---|
| 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 |
| 5xx | Server error | 500 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:
- /api/courses (collection)
- /api/courses/7 (one course)
- /api/courses/7/lessons (its lessons)
Data is exchanged as JSON (JavaScript Object Notation):
{
"id": 7,
"title": "Web Development Basics",
"level": "Beginner",
"lessons": 5,
"free": true
}JSON supports objects {}, arrays [], strings, numbers, booleans and null.
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:
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
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.
