URLs & Endpoints — API

An endpoint is a method paired with a path, such as GET /books/1. The host (the server's name) is the same for every endpoint of one API. A URL is made of…

Search an online bookshop for "this earth of mankind" and the address bar (the box at the top of the browser) changes to something like /search?q=this+earth+of+mankind. Click one book and the address becomes /books/1. Each part of these addresses has its own job, and the addresses of an API follow the same rules.

In an API, an endpoint is a method paired with an address, such as GET /books/1. The address is written as a URL (a full web address, like the one in the address bar). You read a URL like the address on a parcel label. The building name (in a URL: the host) takes the parcel to the right office. The shelf number (in a URL: the path) says which item. The note on the label (in a URL: the query string) states your preferences, such as "only the ones in stock".

The parts of a URL

This is one full URL to the Bookshop API:

https://api.bookshop.test/books/1?fields=title,price
Part What it holds Read with new URL()
protocol https: url.protocol
host api.bookshop.test url.host
path /books/1 url.pathname
query string ?fields=title,price url.search

The browser already has a built-in URL reader, new URL(). This code uses it to read the path and the query string:

const url = new URL("https://api.bookshop.test/books/1?fields=title,price");

console.log(url.pathname);                  // "/books/1"
console.log(url.searchParams.get("fields")); // "title,price"

url.searchParams.get("fields") gets the value of fields from the query string.

The host is the same for every endpoint of one API. What makes one endpoint different from another is its method and path. So an endpoint is the specific URL that receives requests for one resource, with a certain method.

Endpoints in the Bookshop API

Endpoint Meaning
GET /books every book
GET /books/{id} one book
POST /books add a book
GET /authors/{id}/books the books of one author

{id} is a blank that gets filled with a number, such as 1 in /books/1. Documentation (the written guide to an API) usually writes it {id}, while Express code writes it :id. The pattern is always the resource's name, then the id: student number 5 is at /api/students/5. The /api prefix is common when the API and the website share one host.

Path parameter: pointing at one thing

In /books/1, the 1 says which book. This part of the path, whose value can change, is called a path parameter. In Express the endpoint is written app.get("/books/:id", ...), and its value is read from req.params.id. Before you read on, guess: for the request GET /books/1, is req.params.id the number 1 or the text "1"?

Its value is always text: "1", not 1. A URL is text, so everything read from a URL is text too. As a result "1" === 1 is false, because === compares the value and its type. So turn it into a number first with parseInt(req.params.id) or Number(req.params.id).

In the exercise, the endpoint is GET /users/:id. Here is how it runs:

Request req.params.id parseInt(...) Answer
GET /users/1 "1" 1 200 + {"id": 1, "name": "Budi"}
GET /users/99 "99" 99 404 + {"error": "User not found"}

A user that doesn't exist is answered with 404 Not Found, not 200 with an empty body.

Query string: options for a list

The query string comes after the ?. It holds name=value pairs, and several pairs are joined with &. A query string doesn't point at one thing. Its job is usually to shape a list: filtering, sorting, or cutting it into pages.

These two requests ask for the list of books by author number 2. The second one also sorts them by price:

GET /books?author_id=2
GET /books?author_id=2&sort=price

How to choose the place for a part: imagine that part removed from the URL. If the request then points at a different thing, put that part in the path. If the part is only an option for a list, put it in the query. So GET /api/getStudentById?id=5 isn't RESTful (it doesn't follow the REST style): 5 points at one student, so it goes in the path: GET /api/students/5.

Naming rules

GET /api/Student_Data/getAll breaks almost all of these rules: it has capitals, an underscore, and the verb getAll. The tidy version is GET /api/students.

Exercise: one user through a path parameter

The exercise code has the same shape as this Bookshop endpoint:

app.get("/books/:id", (req, res) => {
  const id = parseInt(req.params.id);
  if (id === 1) {
    res.json({ id: 1, title: "The Rainbow Troops" });
  } else {
    res.status(404).json({ error: "Book not found" });
  }
});

In the exercise the resource is users. User 1 is answered with {"id": 1, "name": "Budi"}, and any other user with 404 and {"error": "User not found"}.

⚠️ Badly written addresses, and numbers that turn out to be text

const id = Number(req.params.id);
if (!Number.isInteger(id)) {
  return res.status(400).json({ error: "id must be a whole number" });
}

With this check, "1" is accepted as 1, while "1abc", "abc" and "1.5" are answered with 400.

TL;DR: An endpoint is a method paired with a path, such as GET /books/1. The host (the server's name) is the same for every endpoint of one API. A URL is made of protocol (https:), host, path and query string (the part after ?), and new URL() can read those parts. A path parameter (/books/:id) is the part of the path that points at one thing. Its value in req.params.id is always text, so turn it into a number with parseInt before comparing it with a number. The query string (?author_id=2) shapes a list. An empty list is still answered with 200 and [], while a thing that doesn't exist is answered with 404. Path names: lowercase, plural nouns, no verbs, such as /api/students/5.

⚡ Endpoint = method + path

Meaning: One endpoint is a method paired with a path (the address of the data), such as GET /books/1. The host (the server's name, such as api.bookshop.test) is the same for every endpoint of one API, so what makes one endpoint different is its method and path.

⚡ A path parameter is text

Write:

app.get("/books/:id", (req, res) => {
  const id = parseInt(req.params.id);
  if (id === 1) {
    res.json({ id: 1, title: "The Rainbow Troops" });
  } else {
    res.status(404).json({ error: "Book not found" });
  }
});
Guess first: for GET /books/1, is req.params.id the number 1 or the text "1"?

The text "1". A URL is text, so everything read from a URL is text too. "1" === 1 is false, so turn it into a number first with parseInt.

Meaning: :id is a path parameter: the part of the path that points at one book. "/books/:id" catches /books/1, /books/99 and so on, and its value is read from req.params.id. A book that doesn't exist is answered with 404, not 200 with an empty body.

⚡ The path points, the query shapes a list

Guess first: GET /api/getStudentById?id=5 can be used to get student number 5. The part after ? is called the query. What's wrong with it?

It isn't RESTful (it doesn't follow the REST style). There's a verb in the URL, and one student is pointed at through the query. Write GET /api/students/5.

Meaning: To choose the place for a part of a URL, imagine that part removed. If the request then points at a different thing, put that part in the path. If the part is only an option for a list, such as ?author_id=2 (only the books by author number 2), put it in the query.

What you will learn