Skip to content

JavaScript (Fetch API)

Browser-native fetch with async/await, bearer-token auth, error handling, and pagination.

This guide is for calling the GoRest API from a browser using plain JavaScript and the built-in fetch function. Everything below runs inside an HTML page.

What you need

  • A web browser. Chrome, Firefox, Safari, or Edge from the last few years all work.
  • A text editor to write a small HTML file.
  • An access token, which you generate after signing in. Sign in with GitHub, Google or Microsoft (no password to remember), then visit /my/tokens to create one. Tokens are tied to your account so the rows you create are yours.

A complete working page

Save the file below as index.html, replace YOUR_TOKEN with your token, and open the file in your browser (double-click it, or drag it onto the browser window). You will see a list of users render on the page. Reads work without a token too, but then you see only the sample data.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>GoRest demo</title>
  </head>
  <body>
    <h1>Users</h1>
    <ul id="users"></ul>

    <script>
      const TOKEN = "YOUR_TOKEN"; // paste yours from /my/tokens; for local tests only, never in a page you publish

      fetch("https://gorest.co.in/public/v3/users", {
        headers: { Authorization: `Bearer ${TOKEN}` }
      })
        .then(async res => {
          if (!res.ok) {
            throw new Error(`HTTP ${res.status}: ${await res.text()}`);
          }
          return res.json();
        })
        .then(({ data: users }) => {
          const list = document.getElementById("users");
          for (const u of users) {
            const li = document.createElement("li");
            li.textContent = `${u.name} (${u.email})`;
            list.appendChild(li);
          }
        })
        .catch(err => {
          document.getElementById("users").innerHTML =
            `<li style="color:red">${err.message}</li>`;
        });
    </script>
  </body>
</html>

That is a full working program. It uses three things:

  • fetch(url, options) is the browser's built-in HTTP client. It returns a Promise.
  • The Authorization header tells the API who you are. The format is Bearer <token> with a single space.
  • DOM manipulation via document.getElementById and createElement to put the result on the page.

The rest of this guide breaks the code into reusable pieces and adds the patterns you will need in real apps.

The base URL and token

Pick a base URL once and reuse it everywhere. Save the token in a constant near the top of your script. (In production apps you should not put the token directly in client-side code; the Tips section at the bottom covers safer patterns.)

const API   = "https://gorest.co.in/public/v3";
const TOKEN = "YOUR_TOKEN"; // from /my/tokens

Send the bearer token on every request

All write operations and any request that needs your per-token rate-limit budget need an Authorization header. Build it once and pass it into every fetch call:

const headers = {
  "Authorization": `Bearer ${TOKEN}`,
  "Accept": "application/json",
  "Content-Type": "application/json"
};

The header Accept: application/json asks for JSON back. The header Content-Type: application/json is needed only when you send a body (POST, PATCH).

Promises and async/await

Every fetch returns a Promise. There are two ways to read the response. Both work, but async/await is easier to follow once you have more than one step.

// The .then() version
fetch(`${API}/users`, { headers })
  .then(res => res.json())
  .then(({ data }) => console.log(data));

// The async/await version: same thing, easier to read
async function listUsers() {
  const res   = await fetch(`${API}/users`, { headers });
  const { data } = await res.json(); // a list is { data, meta }
  console.log(data);
}
listUsers();

Use whichever you find more readable. The rest of the guide uses async/await because it scales better to multi-step flows.

List users with filters

Build the URL with the URL constructor. It URL-encodes the query parameters for you, which avoids small bugs with names that contain spaces or special characters.

async function listUsers({ status = "active", size = 25 } = {}) {
  const url = new URL(`${API}/users`);
  url.searchParams.set("filter[status]", status);
  url.searchParams.set("page[size]", size);

  const res = await fetch(url, { headers });
  if (!res.ok) throw new Error(`Got ${res.status}`);
  return res.json(); // { data: [...], meta: {...} }
}

listUsers({ status: "active" }).then(({ data }) => {
  console.log(data.length, "users on this page");
});

The filters on the users endpoint are filter[status] and filter[email] (an exact, lower case match). For a text search on names and emails, use search=. Every list answers { data, meta }. Ids are UUID strings.

Fetch a single user

Pass the id straight in the path. Handle 404 in your code. The id might not exist, or it might belong to someone else's account (which the API treats the same).

async function getUser(id) {
  const res = await fetch(`${API}/users/${id}`, { headers });
  if (res.status === 404) return null;
  if (!res.ok) throw new Error(`Got ${res.status}`);
  return res.json();
}

Create, update, delete

Writes use JSON request bodies, and the token needs the users:write scope. A user has name, email and status ("active" or "inactive"). name and email are required, and status is "active" unless you set it.

  • POST returns 201 with the new resource (including its server-assigned id).
  • PATCH returns 200 with the updated row. It changes only the fields you send. There is no PUT in v3.
  • DELETE returns 204 with no body.
// Create
async function createUser() {
  const res = await fetch(`${API}/users`, {
    method: "POST",
    headers,
    body: JSON.stringify({
      name: "Avani Iyer",
      email: `avani-${Date.now()}@example.com`
    })
  });
  return res.json();
}

// Update (partial)
async function deactivate(id) {
  await fetch(`${API}/users/${id}`, {
    method: "PATCH",
    headers,
    body: JSON.stringify({ status: "inactive" })
  });
}

// Delete
async function removeUser(id) {
  await fetch(`${API}/users/${id}`, { method: "DELETE", headers });
}

Validation errors

When the body fails validation the API returns 422 with a Problem Details body, and its errors array lists the wrong fields. Show those next to the form fields rather than as a generic "something went wrong":

async function tryCreate() {
  const res = await fetch(`${API}/users`, {
    method: "POST",
    headers,
    body: JSON.stringify({ name: "x" }) // missing email
  });

  if (res.status === 422) {
    const problem = await res.json();
    // problem.errors: [{ pointer: "/email", code: "required", detail: "..." }, ...]
    for (const e of problem.errors) console.warn(`${e.pointer}: ${e.detail}`);
    return;
  }

  console.log("created:", await res.json());
}

Pagination

A list carries its paging state in meta, not in headers:

  • meta.has_more is true when another page exists.
  • meta.next_cursor is the value to send as page[after] to get the next page.
  • page[size] sets the page size, from 1 to 100 (the default is 25).

The cleanest way to walk every page in JavaScript is an async generator. The caller treats it like a regular loop; the generator handles the paging behind the scenes.

async function* pageUsers(query = {}) {
  let after = null;
  while (true) {
    const url = new URL(`${API}/users`);
    for (const [k, v] of Object.entries(query)) url.searchParams.set(k, v);
    url.searchParams.set("page[size]", 100);
    if (after) url.searchParams.set("page[after]", after);

    const res = await fetch(url, { headers });
    if (!res.ok) throw new Error(`Got ${res.status}`);

    const { data, meta } = await res.json();
    for (const u of data) yield u;

    if (!meta.has_more) return;
    after = meta.next_cursor;
  }
}

// Use it like a regular for loop
(async () => {
  for await (const user of pageUsers({ "filter[status]": "active" })) {
    console.log(user.email);
  }
})();

Handle rate limits

The default per-token budget is 300 requests per minute. When you hit the limit, the API returns 429 with a Retry-After header (in seconds). The RateLimit header on every response also shows how many calls are left. Wait that long and try again. Do not retry immediately, or you will spend the next request on another 429.

async function fetchWithRetry(url, opts = {}, attempts = 3) {
  for (let i = 0; i < attempts; i++) {
    const res = await fetch(url, opts);
    if (res.status !== 429) return res;

    const wait = (+res.headers.get("retry-after") || 1) * 1000;
    await new Promise(r => setTimeout(r, wait));
  }
  throw new Error("Rate limited; gave up");
}

Cancel in-flight requests

When the user types in a search box, you fire a new request on every keystroke. Without cancellation, responses can arrive out of order and the wrong result wins. AbortController is the standard fix: call .abort() on the previous request before starting the next.

let active;
document.getElementById("search").addEventListener("input", async (e) => {
  // Cancel the previous in-flight request
  active?.abort();
  active = new AbortController();

  try {
    const res = await fetch(
      `${API}/users?search=${encodeURIComponent(e.target.value)}`,
      { headers, signal: active.signal }
    );
    const { data: matches } = await res.json();
    render(matches);
  } catch (err) {
    if (err.name !== "AbortError") throw err;
  }
});

The AbortError caught in the try/catch is the expected result of cancellation, not a real error, so we ignore it.

Tips

  • Open DevTools while you work. Press F12 (or Cmd+Option+I on Mac), switch to the Console tab. You can paste any of the snippets in this guide directly into the console and run them on a page that already has TOKEN defined.
  • Use the Network tab. Every fetch call shows up there. Click a request to see the headers it sent, the response, and the timing. This is the fastest way to debug "why did the API say 401?"
  • Tokens in client code. Putting the token directly in index.html is fine for a personal demo or a tutorial, but the file is visible to anyone who opens DevTools. For production apps, the safer pattern is to keep the token on your own backend and have the browser call your backend, which forwards the request to GoRest.
  • Test slow responses and errors. Call /public/v3/http/delay/1500 to simulate latency, or /public/v3/http/status/429 to test your error path.
Related guides

Keep going