API data loading
Retrieve JSON from an HTTP endpoint and parse it with Response.json().
JavaScript · Function
fetch() starts an asynchronous resource request and returns a promise for a Response. The promise can fulfill for HTTP error statuses, so inspect the response status before treating the request as successful.
Call fetch with a URL or Request and optionally an initialization object. It returns a promise that fulfills with a Response once response headers arrive; inspect the response status before consuming its body with a method such as json().
fetch(input, init)| Name | Type | Description |
|---|---|---|
input | RequestInfo | The resource to fetch, such as a URL string or Request object. |
init | RequestInit | Optional settings for configuring the request, including method, headers, and body. |
A Promise that fulfills with a Response object representing the request's response.
const response = await fetch("https://example.org/data.json");
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
console.log(data);Fetch a resource, explicitly reject unsuccessful HTTP statuses, then parse the response body as JSON.
Retrieve JSON from an HTTP endpoint and parse it with Response.json().
Send configured requests with methods, headers, or a body.
Download text or other resources in browser windows or workers.
fetch() returns a Promise that fulfills with a Response when the response is available, specifically after the server responds with headers. The Response represents the request result and its body can then be consumed with methods such as json().
Follow-up: How should an HTTP 404 be handled? Check response.ok or status after fulfillment, because HTTP error statuses do not by themselves reject the fetch promise.
The first argument identifies the resource and may be a URL-like input or a Request. An optional initialization object configures request details such as method, headers, and body.
Follow-up: What happens when options overlap with those in a Request? Values supplied directly to fetch() take precedence.
fetch() is available as a global method in Window and worker contexts. Its promise rejects for network failures, but an HTTP error response normally still fulfills the promise, so application code must inspect the Response.
Follow-up: How can the response payload be decoded? Call the appropriate Response body method, such as json() or text(), after checking the status.
RequestResponseRequestInitHeadersAbortControllerWindow.fetchWorkerGlobalScope.fetch