API Fetch
The@wordpress/api-fetch package is a utility wrapper around window.fetch designed specifically for making WordPress REST API requests. It simplifies API calls by automatically handling REST API root URLs, nonces, and request parsing.
Installation
You can install the package using npm:This package assumes your code will run in an ES2015+ environment. If you’re targeting environments with limited support for modern JavaScript features, include the polyfill from
@wordpress/babel-preset-default.Basic Usage
Making GET Requests
You can make GET requests by passing apath option to apiFetch:
GET with Query Parameters
CombineapiFetch with addQueryArgs from @wordpress/url to add query parameters:
Making POST Requests
You can use themethod and data options to send POST requests:
API Reference
apiFetch( options )
The main function that makes API requests. It accepts all standardfetch options plus additional WordPress-specific options.
Options
Shorthand to be used in place of
url, appended to the REST API root URL for the current site.Absolute URL to the endpoint from which to fetch.
Unlike
fetch, the Promise return value of apiFetch will resolve to the parsed JSON result. Disable this behavior by passing parse as false.Sent on
POST or PUT requests only. Shorthand to be used in place of body, accepts an object value to be stringified to JSON.HTTP method for the request (e.g., ‘GET’, ‘POST’, ‘PUT’, ‘DELETE’).
Aborting Requests
You can abort requests using theAbortController API:
For legacy browsers that don’t support
AbortController, you can provide your own polyfill or ignore the aborting functionality as a progressive enhancement.Middleware
Theapi-fetch package supports middleware functions that wrap apiFetch calls to perform pre/post processing.
Using Middleware
You can add custom middleware using theuse() method:
apiFetch.use( middleware )
Registers a middleware function.A function that receives
options and next, and returns a Promise. The middleware should call next(options) to continue the chain.Built-in Middleware
Nonce Middleware
The nonce middleware automatically adds authentication to your requests:apiFetch.createNonceMiddleware( nonce )
Creates middleware that adds a nonce to requests for authentication.The nonce value for authentication.
The middleware function with a
nonce property that you can update with a fresh nonce value.Root URL Middleware
The root URL middleware sets the base URL for API requests:apiFetch.createRootURLMiddleware( rootURL )
Creates middleware that prepends the root URL to the path.The REST API root URL.
Custom Fetch Handler
You can replace the defaultwindow.fetch with a custom handler using setFetchHandler():
apiFetch.setFetchHandler( handler )
Sets a custom fetch handler for making requests.A function that receives the request options and returns a Promise.