What is an API call?

An API call is a request your code sends to another program's interface (usually a web server over HTTP) to read or change data, followed by a response, typically in JSON.

Anatomy of an HTTP API call

  • URL / endpoint: https://api.example.com/users/42
  • Method: GET (read), POST (create), PUT/PATCH (update), DELETE (remove).
  • Headers: metadata such as Content-Type, Authorization, Accept.
  • Body: data sent with POST/PUT/PATCH, usually JSON.
  • Response: a status code (200 OK, 201 Created, 400 Bad Request, 401 Unauthorized, 404 Not Found, 500 Server Error), headers, and a body.

Making a call in JavaScript

With fetch (built in) or a library like Axios. The call is asynchronous, so you use await or .then.

What a robust API call handles

  • Loading state while waiting.
  • Errors: network failures and HTTP error statuses (remember fetch does not reject on 4xx/5xx).
  • Timeouts and cancellation with AbortController.
  • Validation of the response shape before using it.
  • Retries with backoff for temporary failures (and only for idempotent requests).
  • Security: never put secret API keys in browser code; call your own backend, which holds the secrets.

Types of APIs

REST (resource URLs), GraphQL (one endpoint, query language), RPC-style (including Next.js Server Actions), WebSockets for real-time, and browser APIs (Geolocation, Clipboard) that are "APIs" in the broader sense.

Code example

js
1// A complete, realistic API call: loading state, timeout, errors, validation
2async function getUser(id) {
3 const state = { loading: true, error: null, user: null };
4 try {
5 // offline demo: a data: URL standing in for https://api.example.com/users/:id
6 const body = JSON.stringify({ id, name: "Ada Lovelace", email: "ada@example.com" });
7 const res = await fetch(`data:application/json,${encodeURIComponent(body)}`, {
8 headers: { Accept: "application/json" },
9 signal: AbortSignal.timeout(5000),
10 });
11 if (!res.ok) throw new Error(`Request failed with status ${res.status}`);
12
13 const data = await res.json();
14 if (typeof data?.name !== "string") throw new Error("Unexpected response shape");
15 state.user = data;
16 } catch (err) {
17 state.error = err.name === "TimeoutError" ? "The server took too long" : err.message;
18 } finally {
19 state.loading = false;
20 }
21 return state;
22}
23
24const result = await getUser(42);
25console.log(result); // { loading: false, error: null, user: { id: 42, name: "Ada Lovelace", ... } }

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app