JavaScript API Call with fetch(): GET and JSON POST Requests

Browser code for an API call in JavaScript using fetch

Use fetch() to make a JavaScript API call with the browser’s built-in, promise-based request function. This guide shows how to call an API in JavaScript with async/await for GET and JSON POST requests.

An API call from JavaScript returns a promise, so await keeps the control flow readable while the browser waits for a response.

Build a JavaScript API call with fetch()

fetch() starts a request and returns a promise that resolves to a Response object. The complete async GET function below adds URL parameters, checks response.ok before parsing, and rethrows failures so calling code can handle them.

GET example: async function getUsers(limit, role) { try { const params = new URLSearchParams({ limit: String(limit), role }); const url = “https://api.example.com/users?” + params.toString(); const response = await fetch(url); if (!response.ok) { throw new Error(“GET failed: ” + response.status); } return await response.json(); } catch (error) { console.error(“Could not load users:”, error); throw error; } }

GET is the default HTTP method, so this request does not need an options object. await fetch(url) waits for the response promise, while await response.json() waits for the separate promise that parses the response body.

How to call an API in JavaScript with GET parameters

Place query parameters after a question mark in the URL. URLSearchParams creates that query string and encodes spaces and special characters safely. In the example, limit and role become parameters such as ?limit=10&role=admin.

Call the function with getUsers(10, “admin”). To set the method explicitly, pass a second argument to fetch(): fetch(url, { method: “GET” }). The server’s status is available through response.status, while response.ok is true only for successful 2xx responses.

Send JSON with POST requests and headers

Use POST when the request sends data to the server. Set the method to “POST”, identify the body as JSON with a Content-Type header, and convert the JavaScript object with JSON.stringify() before sending it.

JSON POST example: async function createUser(user) { try { const response = await fetch(“https://api.example.com/users”, { method: “POST”, headers: { “Content-Type”: “application/json”, “Accept”: “application/json” }, body: JSON.stringify(user) }); if (!response.ok) { throw new Error(“POST failed: ” + response.status); } return await response.json(); } catch (error) { console.error(“Could not create user:”, error); throw error; } }

For example, pass an object with createUser({ name: “Ada”, email: “[email protected]” }). The request headers tell the server how to interpret the body and what response format the client prefers.

Handle network, HTTP, and parsing errors

Handle these failures separately:

  • Network errors: fetch() rejects when the request cannot be completed, such as when the network is unavailable or the request is blocked. The surrounding try…catch handles that rejection.
  • HTTP errors: A 404 or 500 response does not automatically reject the fetch promise. The promise resolves normally, so check response.ok and throw an error when it is false.
  • Parsing errors: response.json() returns a promise and rejects when the body is not valid JSON. Using return await response.json() inside the try block sends that failure to catch.

If an endpoint returns an empty or non-JSON body, use await response.text() instead of response.json().