This library is an isomorphic client for the WordPress REST API, designed to work with WordPress 5.0 or later. If you are using the older WP REST API plugin or WordPress 4.9, some commands will not work.
Index:
node-wpapi is an isomorphic JavaScript client for the WordPress REST API that makes it easy for your JavaScript application to request specific resources from a WordPress website. It uses a query builder-style syntax to let you craft the request being made to REST API endpoints, then returns the API's response to your application as a JSON object. And don't let the name fool you: with Webpack or Browserify, node-wpapi works just as well in the browser as it does on the server!
This library is maintained by K. Adam White at Bocoup, with contributions from a great community of WordPress and JavaScript developers.
To get started, npm install wpapi or download the browser build and check out "Installation" and "Using the Client" below.
node-wpapi works both on the server or in the browser. Node.js version 8.6 or higher (or version 8.2.1 with the --harmony flag) is required, and the latest LTS release is recommended.
In the browser node-wpapi officially supports the latest two versions of all evergreen browsers, and Internet Explorer 11.
To use the library from Node, install it with npm:
npm install --save wpapi
Then, within your application's script files, require the module to gain access to it:
var WPAPI = require( 'wpapi' );
This library is designed to work in the browser as well, via a build system such as Browserify or Webpack; just install the package and require( 'wpapi' ) from your application code.
Alternatively, you may download a ZIP archive of the bundled library code. These files are UMD modules, which may be included directly on a page using a regular <script> tag or required via AMD or CommonJS module systems. In the absence of a module system, the UMD modules will export the browser global variable WPAPI, which can be used in place of require( 'wpapi' ) to access the library from your code.
The module is a constructor, so you can create an instance of the API client bound to the endpoint for your WordPress install:
var WPAPI = require( 'wpapi' );
var wp = new WPAPI({ endpoint: 'http://src.wordpress-develop.dev/wp-json' });
Once an instance is constructed, you can chain off of it to construct a specific request. (Think of it as a query-builder for WordPress!)
We support requesting posts using either a callback-style or promise-style syntax:
// Callbacks
wp.posts().get(function( err, data ) {
if ( err ) {
// handle err
}
// do something with the returned posts
});
// Promises
wp.posts().then(function( data ) {
// do something with the returned posts
}).catch(function( err ) {
// handle error
});
The wp object has endpoint handler methods for every endpoint that ships with the default WordPress REST API plugin.
Once you have used the chaining methods to describe a resource, you may call .create(), .get(), .update() or .delete() to send the API request to create, read, update or delete content within WordPress. These methods are documented in further detail below.
In a case where you would want to connect to a HTTPS WordPress installation that has a self-signed certificate (insecure), you will need to force a connection by placing the following line before you make any wp calls.
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
It is also possible to leverage the capability discovery features of the API to automatically detect and add setter methods for your custom routes, or routes added by plugins.
To utilize the auto-discovery functionality, call WPAPI.discover() with a URL within a WordPress REST API-enabled site:
var apiPromise = WPAPI.discover( 'http://my-site.com' );
If auto-discovery succeeds this method returns a promise that will be resolved with a WPAPI client instance object configured specifically for your site. You can use that promise as the queue that your client instance is ready, then use the client normally within the .then callback.
Custom Routes will be detected by this process, and registered on the client. To prevent name conflicts, only routes in the wp/v2 namespace will be bound to your instance object itself. The rest can be accessed through the .namespace method on the WPAPI instance, as demonstrated below.
apiPromise.then(function( site ) {
// If default routes were detected, they are now available
site.posts().then(function( posts ) {
console.log( posts );
}); // etc
// If custom routes were detected, they can be accessed via .namespace()
site.namespace( 'myplugin/v1' ).authors()
.then(function( authors ) { /* ... */ });
// Namespaces can be saved out to variables:
var myplugin = site.namespace( 'myplugin/v1' );
myplugin.authors()
.id( 7 )
.then(function( author ) { /* ... */ });
});
While using WPAPI.discover( url ) to generate the handler for your site gets you up and running quickly, it does not provide the same level of customization as instantiating your own new WPAPI object. In order to specify authentication configuration when using autodiscovery, chain a .then onto the initial discovery query to call the .auth method on the returned site object with the relevant credentials (username & password, nonce, etc):
var apiPromise = WPAPI.discover( 'http://my-site.com' ).then(function( site ) {
return site.auth({
username: 'admin',
password: 'always use secure passwords'
});
});
apiPromise.then(function( site ) {
// site is now configured to use authentication
})
When attempting auto-discovery against a remote server in a client-side environment, discovery will fail unless the server is configured for Cross-Origin Resource Sharing (CORS). CORS can be enabled by specifying a set of Access-Control- headers in your PHP code to instruct browsers that requests from remote clients are accepted; these headers also let you control what specific methods and links are exposed to those remote clients.
The WP-REST-Allow-All-Cors plugin will permit CORS requests for all API resources. Auto-discovery will still fail when using this plugin, however, because discovery depends on the presence of a Link header on WordPress pages outside of the root REST API endpoint.
To permit your site to be auto-discovered by client-side REST API clients, add a filter to send_headers to explicitly whitelist the Link header for HEAD requests:
add_action( 'send_headers', function() {
if ( ! did_action('rest_api_init') && $_SERVER['REQUEST_METHOD'] == 'HEAD' ) {
header( 'Access-Control-Allow-Origin: *' );
header( 'Access-Control-Expose-Headers: Link' );
header( 'Access-Control-Allow-Methods: HEAD' );
}
} );
Enable CORS at your own discretion. Restricting Access-Control-Allow-Origin to a specific origin domain is often preferable to allowing all origins via *.
If you are building an application designed to interface with a specific site, it is possible to sidestep the additional asynchronous HTTP calls that are needed to bootstrap the client through auto-discovery. You can download the root API response, i.e. the JSON response when you hit the root endpoint such as your-site.com/wp-json, and save that JSON file locally; then, in
your application code, just require in that JSON file and pass the routes property into the WPAPI constructor or the WPAPI.site method.
Note that you must specify the endpoint URL as normal when using this approach.
var apiRootJSON = require( './my-endpoint-response.json' );
var site = new WPAPI({
endpoint: 'http://my-site.com/wp-json',
routes: apiRootJSON.routes
});
// site is now ready to be used with all methods defined in the
// my-endpoint-response.json file, with no need to wait for a Promise.
site.namespace( 'myplugin/v1' ).authors()...
To create a slimmed JSON file dedicated to this particular purpose, see the npm script npm run update-default-routes-json, which will let you download and save an endpoint response to your local project.
In addition to retrieving the specified resource with .get(), you can also .create(), .update() and .delete() resources:
To create posts, use the .create() method on a query to POST (the HTTP verb for "create") a data object to the server:
// You must authenticate to be able to POST (create) a post
var wp = new WPAPI({
endpoint: 'http://your-site.com/wp-json',
// This assumes you are using basic auth, as described further below
username: 'someusername',
password: 'password'
});
wp.posts().create({
// "title" and "content" are the only required properties
title: 'Your Post Title',
content: 'Your post content',
// Post will be created as a draft by default if a specific "status"
// is not specified
status: 'publish'
}).then(function( response ) {
// "response" will hold all properties of your newly-created post,
// including the unique `id` the post was assigned on creation
console.log( response.id );
})
This will work in the same manner for resources other than post: you can see the list of required data parameters for each resource on the REST API Developer Handbook.
To create posts, use the .update() method on a single-item query to PUT (the HTTP verb for "update") a data object to the server:
// You must authenticate to be able to PUT (update) a post
var wp = new WPAPI({
endpoint: 'http://your-site.com/wp-json',
// This assumes you are using basic auth, as described further below
username: 'someusername',
password: 'password'
});
// .id() must be used to specify the post we are updating
wp.posts().id( 2501 ).update({
// Update the title
title: 'A Better Title',
// Set the post live (assuming it was "draft" before)
status: 'publish'
}).then(function( response ) {
console.log( response );
})
This will work in the same manner for resources other than post: you can see the list of required data parameters for each resource in the REST API Developer Handbook.
A WPAPI instance object provides the following basic request methods:
wp.posts()...: Request items from the /posts endpointswp.pages()...: Start a request for the /pages endpointswp.types()...: Get Post Type collections and objects from the /types endpointswp.comments()...: Start a request for the /comments endpointswp.taxonomies()...: Generate a request against the /taxonomies endpointswp.tags()...: Get or create tags with the /tags endpointwp.categories()...: Get or create categories with the /categories endpointwp.statuses()...: Get resources within the /statuses endpointswp.users()...: Get resources within the /users endpointswp.media()...: Get Media collections and objects from the /media endpointswp.settings()...: Read or update site settings from the /settings endpoint (always requires authentication)All of these methods return a customizable request object. The request object can be further refined with chaining methods, and/or sent to the server via .get(), .create(), .update(), .delete(), .headers(), or .then(). (Not all endpoints support all methods; for example, you cannot
$ claude mcp add node-wpapi \
-- python -m otcore.mcp_server <graph>