Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 39 ยท Web APIs and AJAX Basics

Web APIs and REST in Practice

Understand web APIs and REST conventions: endpoints, resources, query strings, pagination, versioning and how to read API documentation.

An API (application programming interface) is a set of agreed ways to ask a program for something. A web API is one you reach over HTTP: your JavaScript sends a request to a URL, and the server answers with data. You don't need to know how the server stores anything. You only need to know what to ask for and what comes back.

Most web APIs follow the same loose set of habits called REST (Representational State Transfer). REST is not a standard you can pass or fail; it's a style that leans on what HTTP already gives you: URLs name things, methods say what to do with them, and status codes report what happened. Once you know the conventions, a new API feels familiar within minutes.

Every example here is read-only text or a small simulation, because the sandbox cannot reach real servers. The URLs use the reserved example domain api.example.com, which you can safely copy into your own experiments.

Endpoints and resources

An endpoint is a URL (plus a method) that the API answers. REST thinks in resources: the nouns of your application, such as users, books or orders. Each resource has a collection URL and an item URL.

Request Meaning
GET /books List books
POST /books Create a new book
GET /books/17 Read book 17
PUT /books/17 Replace book 17
PATCH /books/17 Change some fields of book 17
DELETE /books/17 Delete book 17
GET /books/17/reviews List reviews that belong to book 17
flowchart LR
    C["Collection<br/>/books"] -->|"GET: list<br/>POST: create"| L["List of books"]
    I["Item<br/>/books/17"] -->|"GET: read<br/>PUT/PATCH: update<br/>DELETE: remove"| B["One book"]
    I --> N["Nested collection<br/>/books/17/reviews"]

Collections hold items; the method decides the action. Nested paths express ownership.

Good habits when you design or read endpoint names:

  • Use plural nouns (/books, not /getBooks). The verb is the HTTP method.
  • Put the identity in the path (/books/17) and the options in the query string.
  • Keep nesting shallow. /books/17/reviews is fine; five levels deep is a sign of trouble.
  • Use lowercase and hyphens, such as /order-items.

Not every API is perfectly RESTful. Some have action endpoints like POST /orders/17/cancel because "cancel" doesn't fit a clean create/replace/delete. That's normal. What matters is that you read the documentation instead of guessing.

Query strings: filtering, sorting and searching

The part after ? in a URL is the query string: name and value pairs joined with &. APIs use it to narrow or shape a result without changing which resource you are talking to.

TEXT
GET /books?author=le-guin&sort=-year&fields=id,title&limit=10

Parameter names differ from API to API; there is no universal standard. Common ones are q or search for text, sort or order for ordering, fields for limiting what comes back, and limit or per_page for page sizes. Always build query strings with URLSearchParams so special characters are encoded:

JS Building query strings safely

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that & inside the value became %26 and the space became +. Building the string by hand with "?q=" + text would have broken the request.

Pagination: never return everything

A collection may hold millions of items, so APIs return them in pages. There are three common designs.

Style Request looks like Good for Watch out for
Page number ?page=3&per_page=20 Simple page controls Items shift when data changes while you browse
Offset and limit ?offset=40&limit=20 Flexible slicing Slow on very large offsets
Cursor ?after=eyJpZCI6NDB9&limit=20 Feeds, infinite scroll, changing data You can't jump to page 7 directly

A cursor is an opaque token the server hands you; you pass it back unchanged to get the next batch. Responses usually carry the paging information next to the data, or in a Link header.

The next demo shows a mock paged API as a function. It reports the total, hands out one page at a time and returns a next marker until the data runs out. A loop collects every page.

JS Walking through a paged API

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real APIs also set limits. Always stop when the server says there is no next page, and never assume a response contains everything.

Versioning

An API is a contract: other people's code depends on it. When the shape must change in a way that would break them, providers publish a new version instead of changing the old one silently. The most common spellings are:

  • In the path: https://api.example.com/v2/books
  • In a header: Accept: application/vnd.example.v2+json
  • In a query parameter: ?version=2 (less common)

Path versioning is the easiest to see in logs and to test in a browser. Pin the version your code was written for, and read the changelog before moving to a newer one.

Reading API documentation

You will spend more time reading API docs than writing clever code. A good reference page lists, for each endpoint:

  1. Method and path, with path parameters like /books/{id}.
  2. Parameters: which are required, their types and allowed values.
  3. Request body shape for POST, PUT and PATCH, plus the Content-Type.
  4. Authentication: none, an API key header, or a bearer token.
  5. Response shape for success, with a sample JSON body.
  6. Error responses: the statuses and the error body format.
  7. Limits: rate limits, maximum page size, payload size.

Turn what you read into a small function the rest of your app can call. For example, from docs that say "GET /books/{id} returns { id, title, author } or 404":

JavaScript
async function getBook(id) {
  const response = await fetch(`https://api.example.com/v1/books/${encodeURIComponent(id)}`, {
    headers: { Accept: "application/json" },
  });
  if (response.status === 404) return null;
  if (!response.ok) throw new Error(`Request failed: ${response.status}`);
  return response.json();
}

encodeURIComponent protects the path if an id ever contains characters like / or ?.

Plain REST versus JSON:API and friends

"REST with JSON" is a style, not a format, so two APIs can look very different. Some teams adopt a stricter specification to remove debate about shapes. JSON:API is one of those: it fixes how to name the data, relationships, errors and paging.

JSON
{
  "data": {
    "type": "books",
    "id": "17",
    "attributes": { "title": "The Dispossessed", "year": 1974 },
    "relationships": {
      "author": { "data": { "type": "people", "id": "3" } }
    }
  }
}

The same book in a plain REST API is often just:

JSON
{ "id": 17, "title": "The Dispossessed", "year": 1974, "author_id": 3 }

JSON:API gives you consistency and lots of existing tooling, at the price of more nesting. Plain REST is shorter and easier to read by hand. Whichever you meet, your job is the same: read the docs, write one small function per endpoint, and keep shape-handling code in one place.

There are other styles too. GraphQL exposes a single endpoint where the client describes exactly which fields it wants, and RPC-style APIs name actions directly (POST /sendInvoice). The fetch techniques in this tutorial work for all of them, because they are all HTTP.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which request in a REST API lists every book?

    REST uses plural resource nouns and lets the HTTP method describe the action. GET on the collection lists its items.
  2. 2. Why should you use URLSearchParams to build a query string?

    Characters like & and = have meaning in query strings. URLSearchParams escapes them so values arrive intact.
  3. 3. A feed changes constantly while users scroll. Which pagination style handles it best?

    A cursor points at a position in the data, so new items don't shift the next page. Page numbers and offsets can skip or repeat items.
  4. 4. Why do API providers add a version such as /v2/ instead of editing /v1/ in place?

    An API is a contract. Versioning lets existing clients keep working while new clients use the changed shape.

Summary

  • A web API answers HTTP requests with data; REST is a set of conventions on top of HTTP.
  • Resources are nouns in plural form: a collection (/books) and an item (/books/17); methods express the action.
  • Query strings filter, sort and shape results; build them with URLSearchParams.
  • Large collections are paginated by page, offset or cursor; stop when the server says there is no next page.
  • Versions (/v1/, /v2/) protect existing clients from breaking changes.
  • Read the docs for method, parameters, body, auth, response and errors, then wrap each endpoint in one small function.
  • Plain REST and JSON:API differ in data shape, not in how you call them.

Next: JSON Syntax and Data Types โ€” the format almost every API speaks.