WPAPI

WPAPI

new WPAPI(options)

Construct a REST API client instance object to create

Source:
Parameters:
Name Type Description
options Object

An options hash to configure the instance

Name Type Attributes Description
endpoint String

The URI for a WP-API endpoint

username String <optional>

A WP-API Basic Auth username

password String <optional>

A WP-API Basic Auth password

nonce String <optional>

A WP nonce for use with cookie authentication

routes Object <optional>

A dictionary of API routes with which to bootstrap the WPAPI instance: the instance will be initialized with default routes only if this property is omitted

transport String <optional>

An optional dictionary of HTTP transport methods (.get, .post, .put, .delete, .head) to use instead of the defaults, e.g. to use a different HTTP library than superagent

Members

(static) .transport :Object

Default HTTP transport methods object for all WPAPI instances

These methods may be extended or replaced on an instance-by-instance basis

Properties:
Name Type Description
transport
Source:
Type:
  • Object

#setHeaders

Set the default headers to use for all HTTP requests created from this WPAPI site instance. Accepts a header name and its associated value as two strings, or multiple headers as an object of name-value pairs.

Since:
  • 1.1.0
Source:
Examples

Set a single header to be used by all requests to this site

    site.setHeaders( 'Authorization', 'Bearer trustme' )...

Set multiple headers to be used by all requests to this site

    site.setHeaders({
      Authorization: 'Bearer comeonwereoldfriendsright',
      'Accept-Language': 'en-CA'
    })...

Methods

(static) .categories() → {WPRequest}

Start a request against /categories endpoint

Source:
Returns:
Type:
WPRequest

(static) .comments() → {WPRequest}

Start a request against /comments endpoints

Source:
Returns:
Type:
WPRequest

(static) .discover(url) → {Promise}

Take an arbitrary WordPress site, deduce the WP REST API root endpoint, query that endpoint, and parse the response JSON. Use the returned JSON response to instantiate a WPAPI instance bound to the provided site.

Source:
Parameters:
Name Type Description
url string

A URL within a REST API-enabled WordPress website

Returns:
Type:
Promise

A promise that resolves to a configured WPAPI instance bound to the deduced endpoint, or rejected if an endpoint is not found or the library is unable to parse the provided endpoint.

(static) .media() → {WPRequest}

Start a request against /media endpoints

Source:
Returns:
Type:
WPRequest

(static) .pages() → {WPRequest}

Start a request against /pages endpoints

Source:
Returns:
Type:
WPRequest

(static) .posts() → {WPRequest}

Start a request against /posts endpoints

Source:
Returns:
Type:
WPRequest

(static) .settings() → {WPRequest}

Start a request against /settings endpoint

Source:
Returns:
Type:
WPRequest

(static) .site(endpoint, routes) → {WPAPI}

Convenience method for making a new WPAPI instance

Source:
Parameters:
Name Type Description
endpoint String

The URI for a WP-API endpoint

routes Object

The "routes" object from the JSON object returned from the root API endpoint of a WP site, which should be a dictionary of route definition objects keyed by the route's regex pattern

Returns:
Type:
WPAPI

A new WPAPI instance, bound to the provided endpoint

Examples
These are equivalent:

    var wp = new WPAPI({ endpoint: 'http://my.blog.url/wp-json' });
    var wp = WPAPI.site( 'http://my.blog.url/wp-json' );

`WPAPI.site` can take an optional API root response JSON object to use when
bootstrapping the client's endpoint handler methods: if no second parameter
is provided, the client instance is assumed to be using the default API
with no additional plugins and is initialized with handlers for only those
default API routes.
These are equivalent:

    // {...} means the JSON output of http://my.blog.url/wp-json
    var wp = new WPAPI({
      endpoint: 'http://my.blog.url/wp-json',
      json: {...}
    });
    var wp = WPAPI.site( 'http://my.blog.url/wp-json', {...} );

(static) .statuses() → {WPRequest}

Start a request against /statuses endpoints

Source:
Returns:
Type:
WPRequest

(static) .tags() → {WPRequest}

Start a request against /tags endpoint

Source:
Returns:
Type:
WPRequest

(static) .taxonomies() → {WPRequest}

Start a request against /taxonomies endpoints

Source:
Returns:
Type:
WPRequest

(static) .transport(transport) → {WPAPI}

Set custom transport methods to use when making HTTP requests against the API

Pass an object with a function for one or many of "get", "post", "put", "delete" and "head" and that function will be called when making that type of request. The provided transport functions should take a WPRequest handler instance (e.g. the result of a wp.posts()... chain or any other chaining request handler) as their first argument; a data object as their second argument (for POST, PUT and DELETE requests); and an optional callback as their final argument. Transport methods should invoke the callback with the response data (or error, as appropriate), and should also return a Promise.

Source:
Parameters:
Name Type Description
transport Object

A dictionary of HTTP transport methods

Name Type Attributes Description
get function <optional>

The function to use for GET requests

post function <optional>

The function to use for POST requests

put function <optional>

The function to use for PUT requests

delete function <optional>

The function to use for DELETE requests

head function <optional>

The function to use for HEAD requests

Returns:
Type:
WPAPI

The WPAPI instance, for chaining

Example

showing how a cache hit (keyed by URI) could short-circuit a get request

    var site = new WPAPI({
      endpoint: 'http://my-site.com/wp-json'
    });

    // Overwrite the GET behavior to inject a caching layer
    site.transport({
      get: function( wpreq, cb ) {
        var result = cache[ wpreq ];
        // If a cache hit is found, return it via the same callback/promise
        // signature as the default transport method
        if ( result ) {
          if ( cb && typeof cb === 'function' ) {
            cb( null, result );
          }
          return Promise.resolve( result );
        }

        // Delegate to default transport if no cached data was found
        return WPAPI.transport.get( wpreq, cb ).then(function( result ) {
          cache[ wpreq ] = result;
          return result;
        });
      }
    });

This is advanced behavior; you will only need to utilize this functionality
if your application has very specific HTTP handling or caching requirements.
Refer to the "http-transport" module within this application for the code
implementing the built-in transport methods.

(static) .types() → {WPRequest}

Start a request against /types endpoints

Source:
Returns:
Type:
WPRequest

(static) .users() → {WPRequest}

Start a request against /users endpoints

Source:
Returns:
Type:
WPRequest

#auth(credentials) → {WPAPI}

Set the authentication to use for a WPAPI site handler instance. Accepts basic HTTP authentication credentials (string username & password) or a Nonce (for cookie authentication) by default; may be overloaded to accept OAuth credentials in the future.

Source:
Parameters:
Name Type Description
credentials Object

An authentication credentials object

Name Type Attributes Description
username String <optional>

A WP-API Basic HTTP Authentication username

password String <optional>

A WP-API Basic HTTP Authentication password

nonce String <optional>

A WP nonce for use with cookie authentication

Returns:
Type:
WPAPI

The WPAPI site handler instance, for chaining

Examples

Basic Authentication

    site.auth({
      username: 'admin',
      password: 'securepass55'
    })...

Cookie/Nonce Authentication

    site.auth({
      nonce: 'somenonce'
    })...

#bootstrap(routes) → {WPAPI}

Deduce request methods from a provided API root JSON response object's routes dictionary, and assign those methods to the current instance. If no routes dictionary is provided then the instance will be bootstrapped with route handlers for the default API endpoints only.

This method is called automatically during WPAPI instance creation.

Source:
Parameters:
Name Type Description
routes Object

The "routes" object from the JSON object returned from the root API endpoint of a WP site, which should be a dictionary of route definition objects keyed by the route's regex pattern

Returns:
Type:
WPAPI

The bootstrapped WPAPI client instance (for chaining or assignment)

#namespace(namespace) → {Object}

Access API endpoint handlers from a particular API namespace object

Source:
Parameters:
Name Type Description
namespace string

A namespace string

Returns:
Type:
Object

An object of route endpoint handler methods for the routes within the specified namespace

Example
wp.namespace( 'myplugin/v1' ).author()...

    // Default WP endpoint handlers are assigned to the wp instance itself.
    // These are equivalent:
    wp.namespace( 'wp/v2' ).posts()...
    wp.posts()...

registerRoute(namespace, restBase, optionsopt) → {function}

Create and return a handler for an arbitrary WP REST API endpoint.

The first two parameters mirror register_rest_route in the REST API codebase:

Source:
Parameters:
Name Type Attributes Description
namespace string

A namespace string, e.g. 'myplugin/v1'

restBase string

A REST route string, e.g. '/author/(?P\d+)'

options object <optional>

An (optional) options object

Name Type Attributes Description
mixins object <optional>

A hash of functions to apply as mixins

methods Array.<string> <optional>

An array of methods to whitelist (on the leaf node only)

Returns:
Type:
function

An endpoint handler factory function for the specified route

#root(relativePathopt) → {WPRequest}

Generate a query against an arbitrary path on the current endpoint. This is useful for requesting resources at custom WP-API endpoints, such as WooCommerce's /products.

Source:
Parameters:
Name Type Attributes Description
relativePath String <optional>

An endpoint-relative path to which to bind the request

Returns:
Type:
WPRequest

A request object

#url(url) → {WPRequest}

Generate a request against a completely arbitrary endpoint, with no assumptions about or mutation of path, filtering, or query parameters. This request is not restricted to the endpoint specified during WPAPI object instantiation.

Source:
Parameters:
Name Type Description
url String

The URL to request

Returns:
Type:
WPRequest

A WPRequest object bound to the provided URL

Example
Generate a request to the explicit URL "http://your.website.com/wp-json/some/custom/path"

    wp.url( 'http://your.website.com/wp-json/some/custom/path' ).get()...