W3schools Fetch Api

Posted on  by admin

API facilitates the communication and exchange of data amongdifferent systems and is written and developed in advance for amodular software development approach. It is an application orsystem that can be used to implement a programming interface thatis written using functions or sub-routines and can be used by othersoftware.

API Testing mostly focuses on the business logic layer (asdefined in the diagram) of software development architecture. API testing does not connect with the look and feel of thesoftware product. As an alternative to using standard input devices(like a keyboard) or output devices (like a monitor), API testinguses software for sending calls to your API that you'll use duringAPI test to fetch output and eventually document the response ofyour product.

Below is an example of an API test where JSON input ismentioned, which is used to call the Login API. Request Body (JSON):.

  • While testing the API, the tester examines theinput and expected output according to the technical document. Sample Response - Error:. JS VersionsJS 2009 (ES5)JS 2015 (ES6)JS 2016JS 2017JS 2018JS IE / EdgeJS History. Object DefinitionsObject PropertiesObject MethodsObject DisplayObject AccessorsObject ConstructorsObject PrototypesObject IterablesObject SetsObject MapsObject Reference.
  • Function DefinitionsFunction ParametersFunction InvocationFunction CallFunction ApplyFunction BindFunction Closures. Class IntroClass InheritanceClass Static. JS CallbacksJS AsynchronousJS PromisesJS Async/Await. DOM IntroDOM MethodsDOM DocumentDOM ElementsDOM HTMLDOM FormsDOM CSSDOM AnimationsDOM EventsDOM Event ListenerDOM NavigationDOM NodesDOM CollectionsDOM Node Lists.

AJAX IntroAJAX XMLHttpAJAX RequestAJAX ResponseAJAX XML FileAJAX PHPAJAX ASPAJAX DatabaseAJAX ApplicationsAJAX Examples.

JSON IntroJSON SyntaxJSON vs XMLJSON Data TypesJSON ParseJSON StringifyJSON ObjectsJSON ArraysJSON ServerJSON PHPJSON HTMLJSON JSONP. jQuery SelectorsjQuery HTMLjQuery CSSjQuery DOM. JS GraphicsJS CanvasJS PlotlyJS Chart.jsJS Google ChartJS D3.js. JS ExamplesJS HTML DOMJS HTML InputJS HTML ObjectsJS HTML EventsJS BrowserJS EditorJS ExercisesJS QuizJS Certificate.

JavaScript ObjectsHTML DOM Objects. javascript by Gleaming Gemsbok on Feb 10 2020 Comment . The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest, but the new API provides a more powerful and flexible feature set. Fetch provides a generic definition of Request and Response objects (and other things involved with network requests).

This will allow them to be used wherever they are needed in the future, whether it's for service workers, Cache API, and other similar things that handle or modify requests and responses, or any kind of use case that might require you to generate your responses programmatically (that is, the use of computer program or personal programming instructions).

It also defines related concepts such as CORS and the HTTP Origin header semantics, supplanting their separate definitions elsewhere. For making a request and fetching a resource, use the fetch() method.


It is implemented in multiple interfaces, specifically Window and WorkerGlobalScope. This makes it available in pretty much any context you might want to fetch resources in.

The fetch() method takes one mandatory argument, the path to the resource you want to fetch.

It returns a Promise that resolves to the Response to that request — as soon as the server responds with headers — even if the server response is an HTTP error status.

  • Accept
  • Accept-Language
  • Content-Language
  • You can also optionally pass in an init options object as the second argument (see Request). Once a Response is retrieved, there are a number of methods available to define what the body content is and how it should be handled.

JS Objects

You can create a request and response directly using the Request() and Response() constructors, but it's uncommon to do this directly. Instead, these are more likely to be created as results of other API actions (for example, FetchEvent.respondWith() from service workers).

The fetch specification differs from jQuery.ajax() in three main ways:. The Promise returned from fetch()won't reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.

won't send cross-origin cookies unless you set the credentialsinit option (to . fetch()won't send cross-origin cookies unless you set the credentialsinit option (to include).

In April 2018, the spec changed the default credentials policy to 'same-origin'. The following browsers shipped an outdated native fetch, and were updated in these versions: Firefox 61.0b13, Safari 12, Chrome 68.If you are targeting older versions of these browsers, be sure to include credentials: 'same-origin'init option on all API requests that may be affected by cookies/user login state.

In April 2018, the spec changed the default credentials policy to 'same-origin'. The following browsers shipped an outdated native fetch, and were updated in these versions: Firefox 61.0b13, Safari 12, Chrome 68.

JS Graphics

If you are targeting older versions of these browsers, be sure to include credentials: 'same-origin'init option on all API requests that may be affected by cookies/user login state.

Concepts and usage

Note: Find out more about using the Fetch API features in Using Fetch, and study concepts in Fetch basic concepts. Browsers have started to add experimental support for the AbortController and AbortSignal interfaces (aka The Abort API), which allow operations like Fetch and XHR to be aborted if they have not already completed.


See the interface pages for more details. The fetch() method used to fetch a resource. Represents response/request headers, allowing you to query them and take different actions depending on the results.


Represents a resource request. Represents the response to a request.

JS vs jQuery

BCD tables only load in the browser.

JS Examples

Instead of passing a path to the resource you want to request into the fetch() call, you can create a request object using the Request() constructor, and pass that in as a fetch() method argument:

Request() accepts exactly the same parameters as the fetch() method. You can even pass in an existing request object to create a copy of it:

This is pretty useful, as request and response bodies can only be used once. Making a copy like this allows you to effectively use the request/response again while varying the init options if desired. The copy must be made before the body is read.

Note: There is also a clone() method that creates a copy. Both methods of creating a copy will fail if the body of the original request or response has already been read, but reading the body of a cloned response or request will not cause it to be marked as read in the original.

JS Browser BOM

The Headers interface allows you to create your own headers object via the Headers() constructor. A headers object is a simple multi-map of names to values:

The same can be achieved by passing an array of arrays or an object literal to the constructor:

The contents can be queried and retrieved:

Some of these operations are only useful in ServiceWorkers, but they provide a much nicer API for manipulating headers.

All of the Headers methods throw a TypeError if a header name is used that is not a valid HTTP Header name. The mutation operations will throw a TypeError if there is an immutable guard (see below). Otherwise, they fail silently. For example:

A good use case for headers is checking whether the content type is correct before you process it further. For example:

Browser compatibility

Since headers can be sent in requests and received in responses, and have various limitations about what information can and should be mutable, headers' objects have a guard property. This is not exposed to the Web, but it affects which mutation operations are allowed on the headers object.

Possible guard values are:

  • none: default.
  • request: guard for a headers object obtained from a request (Request.headers).
  • request-no-cors: guard for a headers object obtained from a request created with Request.modeno-cors.
  • response: guard for a headers object obtained from a response (Response.headers).
  • immutable: guard that renders a headers object read-only; mostly used for ServiceWorkers.

Note: You may not append or set the Content-Length header on a guarded headers object for a response. Similarly, inserting Set-Cookie into a response header is not allowed: ServiceWorkers are not allowed to set cookies via synthesized responses.

JS Classes

As you have seen above, Response instances are returned when fetch() promises are resolved.

The most common response properties you'll use are:

  • Response.status — An integer (default value 200) containing the response status code.
  • Response.statusText — A string (default value ""), which corresponds to the HTTP status code message. Note that HTTP/2 does not support status messages.
  • Response.ok — seen in use above, this is a shorthand for checking that status is in the range 200-299 inclusive. This returns a boolean value.

They can also be created programmatically via JavaScript, but this is only really useful in ServiceWorkers, when you are providing a custom response to a received request using a respondWith() method:

The Response() constructor takes two optional arguments — a body for the response, and an init object (similar to the one that Request() accepts.)

Note: The static method error() returns an error response. Similarly, redirect() returns a response resulting in a redirect to a specified URL. These are also only relevant to Service Workers.

Fetch Interfaces

Both requests and responses may contain body data. A body is an instance of any of the following types:

  • ArrayBufferView (Uint8Array and friends)
  • Blob/File
  • string

The Request and Response interfaces share the following methods to extract a body. These all return a promise that is eventually resolved with the actual content.

  • Request.arrayBuffer() / Response.arrayBuffer()
  • Request.blob() / Response.blob()
  • Request.formData() / Response.formData()
  • Request.json() / Response.json()
  • Request.text() / Response.text()

This makes usage of non-textual data much easier than it was with XHR.

Request bodies can be set by passing body parameters:

Both request and response (and by extension the fetch() function), will try to intelligently determine the content type. A request will also automatically set a Content-Type header if none is set in the dictionary.

JS Functions

Fetch API support can be detected by checking for the existence of Headers, Request, Response or fetch() on the Window or Worker scope. For example:

JS References

Fetch Standard
# fetch-method


BCD tables only load in the browser

Browse Javascript Answers by Framework