“A WordPress REST API client for JavaScript”で任意のAPIエンドポイントからGETする
タグ:
ドキュメントのどこかにあるはずなんですが、ソース見た方が早かったので一応覚書。 基本的なAPIに対するリクエストについては、ライブラリがほぼ網羅してくれています。 Requesting Different Resourc […]
広告ここから
広告ここまで
目次
ドキュメントのどこかにあるはずなんですが、ソース見た方が早かったので一応覚書。
基本的なAPIに対するリクエストについては、ライブラリがほぼ網羅してくれています。
Requesting Different Resources
ただ、そこにないAPIをコールしたい場合もまれにありまして、そんな時はwp.url()関数を使うと良いみたいです。
var wp = new WPAPI({ endpoint: 'https://www.yoursite.com/wp-json' })
wp.url( 'https://your.website.com/wp-json/some/custom/path' ).get().then(function( data ) {
// do something with the returned posts
}).catch(function( err ) {
// handle error
})
From:https://github.com/WP-API/node-wpapi/blob/master/wpapi.js#L220-L239
例:サイトタイトルと概要を取得しつつ、新着記事を取得する
https://www.yoursite.com/wp-jsonへGETリクエストを投げると、サイトタイトルと説明文 + APIルート情報が返ってきます。
とりあえずこの情報を取得しつつ記事一覧についても取るというサンプルを作ってみました。
const WPAPI = require('wpapi')
const api = 'https://www.yoursite.com/wp-json'
const wp = new WPAPI({'endpoint': api})
let result = {
wp.url(api).get().then(data => {
result.root = {
title: data.name,
description: data.description
}
return wp.posts()
}).then(data => {
result.posts = data
console.log(result)
}).catch(err => {
console.log(err)
})
補足:細かなリクエストを出したい場合はregisterRouteを使う様子
wp.url()でGETリクエストを出すことはできますが、クエリをつけたりしたい場合はwp.registerRoute()で登録する方が良いみたいです。
Custom Routes
var site = new WPAPI({ endpoint: 'https://www.yoursite.com/wp-json' });
site.myCustomResource = site.registerRoute( 'myplugin/v1', '/author/(?P\\d+)' );
site.myCustomResource().id( 7 ); // => myplugin/v1/author/7
site.myCustomResource().id( 'foo' ); // => Error: Invalid path component: foo does not match (?P\d+)