WP-API / node-wpapi

An isomorphic JavaScript client for the WordPress REST API
http://wp-api.org/node-wpapi/
MIT License
1.67k stars 192 forks source link

Document usage with wp.com wp/v2 API endpoints #329

Open kadamwhite opened 6 years ago

kadamwhite commented 6 years ago

This issue was raised in Gitter chat:

Out of the box, if I got a Wordpress hosted at the "official" wordpress_com site, is it's API level ok with node-wpapi ?

The built-in WordPress REST API is supported by WordPress.com through their public-api.wordpress.com site; the base URL for endpoints for a given site is e.g.

https://public-api.wordpress.com/wp/v2/sites/your_site

where your_site is a string like "kadamwhite.wordpress.com". Then you can request collections and resources as normal:

https://public-api.wordpress.com/wp/v2/sites/kadamwhite.wordpress.com/posts
https://public-api.wordpress.com/wp/v2/sites/kadamwhite.wordpress.com/tags

Because of the structure of this URL, we have to do a bit of adjustment to get our client to generate the proper URL format. The simplest way is to chain a .namespace() call onto our requests:

import WPAPI from 'wpapi';
const wpcom = WPAPI.site('https://public-api.wordpress.com');
wpcom.posts().namespace('wp/v2/sites/kadamwhite.wordpress.com').get()....

this is a bit verbose, so you could make a helper method to reduce the duplication:

function withSite( site ) {
  return function( request ) {
    return request.namespace( site );
  };
}
const withMySite = withSite( 'kadamwhite.wordpress.com' );

// Now wrap requests in `withMySite` before using .get() or .then():
withMySite( wpcom.posts() ).get()....

Alternatively, you should be able to download the API root for your site and use that to bootstrap a client specific to your own .com site.

Note that authentication with the WordPress.com-hosted version of the WordPress REST API is untested, and probably not feasible at this time, since WordPress.com sites provide no plugins for authentication and arbitrary custom plugins cannot run on WordPress.com.

This issue tracks moving this documentation into the README.

cmawhorter commented 6 years ago

FWIW - first time wpapi user here and google brought me here. It would be helpful to include a working snippet. It's obvious now, but at first I didn't realize what I needed to do.

Example of how to list posts at wordpress.com blog using basic auth:

const WPAPI = require('wpapi');

const wpcom = new WPAPI({
  endpoint: 'https://public-api.wordpress.com', // not your blog domain
  username: 'your-blog-username', // for mywordpresscomblog.wordpress.com
  password: 'your-user-password' // for mywordpresscomblog.wordpress.com
});

wpcom.posts().namespace('wp/v2/sites/mywordpresscomblog.wordpress.com')
  .get()
  .then(console.log)
  .catch(console.error);