WP-API / node-wpapi

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

Update constructor initialization to support WP.com API urls #484

Open tomsoderlund opened 3 years ago

tomsoderlund commented 3 years ago

I'm trying to figure out how to use WPAPI with a Wordpress.com-hosted blog.

const wp = new WPAPI({
  endpoint: 'https://MYSITE.wordpress.com/wp-json'
})
const posts = await wp.posts().get()
console.log(`posts:`, posts)

But I'm getting “Not Found” errors (if I set the Wordpress privacy to "Private" I get no error!).

I'm used to interacting with Wordpress REST API at https://public-api.wordpress.com/rest/v1.1/sites/MYSITE.wordpress.com/posts but the /wp-json route doesn't seem to be available.

What to do?

tomsoderlund commented 3 years ago

Update

Seems that the v2 API endpoint is https://public-api.wordpress.com/wp/v2/sites/MYSITE.wordpress.com but now I get this error:

{ code: 'rest_no_route',
  message: 'No route was found matching the URL and request method.' }
kadamwhite commented 3 years ago

This is a bug, because the code currently assumes that the wp/v2 namespace will always come at the end of the URI, which is inverted in the WP.com multisite environment. The best way to work around it right now would be,

const wp = new WPAPI({
  endpoint: 'https://MYSITE.wordpress.com/wp-json'
})
const posts = await wp.root( 'posts' ).get()
console.log(`posts:`, posts)

You would pass the relative API path via .root() instead of being able to use the .posts() method, etc. This is not ideal, and at that point you aren't much better off than using fetch or some such directly, but it's the best we can support right now without adding a patch to special-case wp.com.