WordPress

WordPress4.4コアのWP REST APIを叩いてみる(oEmbed編)

ドキュメント読むのめんどいから実際にWP REST APIを叩いてみよう企画第二弾。 今回はWordPress4.4のもう1つのコア機能「oEmbed」のために追加されたAPIを叩いてみます。 oEmbedとは? Wor […]

広告ここから
広告ここまで

ドキュメント読むのめんどいから実際にWP REST APIを叩いてみよう企画第二弾。

今回はWordPress4.4のもう1つのコア機能「oEmbed」のために追加されたAPIを叩いてみます。

oEmbedとは?

WordPress4.4以上でWP REST APIが無効化されていないブログの記事URLを貼り付けると、勝手にブログカード的なものが生成される機能です。
https://blog.mayuko.me/wordpress-4-4-oembed-api/

JSで相手のブログのWP REST APIを叩きに行っているからか、HTTPSなWordPressの人はHTTPS非対応ブログ相手には使えないみたいです。

oEmbed用のAPI

https://wp-kyoto.cdn.rabify.me/check-wp-api-route/
この記事で4.4にデフォルトで追加されたAPIエンドポイントをまとめたのですが、その中に
https://wp-kyoto.cdn.rabify.me/wp-json/oembed/1.0/
https://wp-kyoto.cdn.rabify.me/wp-json/oembed/1.0/embed/
というどう考えてもこのために追加されたエンドポイントが2つありました。

というわけでこの2つをcurl + jqでよんでみましょう。

確認の仕方

なんか自分のブログのAPIを叩くのは面白くないので、適当に知り合いのブログを実験台にします。

「https://blog.hinaloe.net/wp-json/」のようにルートのエンドポイントを以下のコマンドで叩くと、そのエンドポイントで使えるメソッドやクエリを確認できます。

 curl -X GET https://blog.mayuko.me/wp-json/ | jq '.routes."/"' 
[
  {
    "methods": [
      "GET"
    ],
    "args": {
      "context": {
        "required": false,
        "default": "view"
      }
    }
  }
]

この場合、「https://blog.mayuko.me/wp-json/」というエンドポイントにはGETでのリクエストが可能で、[context=]というクエリを(必須ではないが)投げることができる。」ということになります。

それでは見てみましょう。

/wp-json/oembed/1.0/を見てみる

$ curl -X GET https://blog.hinaloe.net/wp-json/ | jq '.routes."/oembed/1.0".endpoints'
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  1025    0  1025    0     0   2489      0 --:--:-- --:--:-- --:--:--  2493
[
  {
    "methods": [
      "GET"
    ],
    "args": {
      "namespace": {
        "required": false,
        "default": "oembed/1.0"
      },
      "context": {
        "required": false,
        "default": "view"
      }
    }
  }
]

namespaceとcontextをGETで投げれるみたいですね。

/wp-json/oembed/1.0/embedを見てみる

$ curl -X GET https://blog.hinaloe.net/wp-json/ | jq '.routes."/oembed/1.0/embed".endpoints'
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  1025    0  1025    0     0    336      0 --:--:--  0:00:03 --:--:--   336
[
  {
    "methods": [
      "GET"
    ],
    "args": {
      "url": {
        "required": true
      },
      "format": {
        "required": false,
        "default": "json"
      },
      "maxwidth": {
        "required": false,
        "default": 600
      }
    }
  }
]

こちらはurlとformat,maxwidthを投げれるみたいです。

直接叩いてみる

なんとなく何を投げればいいかなどは見えたので、実際に叩いてみましょう。

まずは/wp-json/oembed/1.0/から

$ curl -X GET https://blog.hinaloe.net/wp-json/oembed/1.0 | jq '.'
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   681    0   681    0     0    867      0 --:--:-- --:--:-- --:--:--   866
{
  "namespace": "oembed/1.0",
  "routes": {
    "/oembed/1.0": {
      "namespace": "oembed/1.0",
      "methods": [
        "GET"
      ],
      "endpoints": [
        {
          "methods": [
            "GET"
          ],
          "args": {
            "namespace": {
              "required": false,
              "default": "oembed/1.0"
            },
            "context": {
              "required": false,
              "default": "view"
            }
          }
        }
      ],
      "_links": {
        "self": "https://blog.hinaloe.net/wp-json/oembed/1.0"
      }
    },
    "/oembed/1.0/embed": {
      "namespace": "oembed/1.0",
      "methods": [
        "GET"
      ],
      "endpoints": [
        {
          "methods": [
            "GET"
          ],
          "args": {
            "url": {
              "required": true
            },
            "format": {
              "required": false,
              "default": "json"
            },
            "maxwidth": {
              "required": false,
              "default": 600
            }
          }
        }
      ],
      "_links": {
        "self": "https://blog.hinaloe.net/wp-json/oembed/1.0/embed"
      }
    }
  },
  "_links": {
    "up": [
      {
        "href": "https://blog.hinaloe.net/wp-json/"
      }
    ]
  }
}

oEmbed用APIのルート情報が取れる・・・という感じでしょうか?
ちょっと検索しただけではクエリに関する情報が出てこなかったので、また時間を見つけて調べてみます。

/wp-json/oembed/1.0/embedも叩いてみる

$ curl -X GET https://blog.hinaloe.net/wp-json/oembed/1.0/embed | jq '.'
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   143    0   143    0     0     78      0 --:--:--  0:00:01 --:--:--    78
{
  "code": "rest_missing_callback_param",
  "message": "パラメーター不足: url",
  "data": {
    "status": 400,
    "params": [
      "url"
    ]
  }
}

はい、怒られました。
urlのクエリが必須なので、つけないと400エラーを返されます。

で、思いつくままにクエリを適当に投げてみた結果上手いこと行っちゃったので以下その結果です。

$ curl -X GET https://blog.mayuko.me/wp-json/oembed/1.0/embed?url=https://blog.mayuko.me/wordpress-4-4-oembed-api/ | jq .
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  2840    0  2840    0     0   1554      0 --:--:--  0:00:01 --:--:--  1553
{
  "version": "1.0",
  "provider_name": "まよねーずブログ",
  "provider_url": "https://blog.mayuko.me",
  "author_name": "マヨネーズまゆこ",
  "author_url": "https://blog.mayuko.me/author/mayuko/",
  "title": "WordPress 4.4 で記事が埋め込めるようになるっぽい (埋め込めないケースを追記)",
  "type": "rich",
  "width": 600,
  "height": 338,
  "html": "<blockquote class=\"wp-embedded-content\"><a href=\"https://blog.mayuko.me/wordpress-4-4-oembed-api/\">WordPress 4.4 で記事が埋め込めるようになるっぽい (埋め込めないケースを追記)</a></blockquote>\n<script type='text/javascript'>\n<!--//--><![CDATA[//><!--\n\t\t!function(a,b){\"use strict\";function c(){if(!e){e=!0;var a,c,d,f,g=-1!==navigator.appVersion.indexOf(\"MSIE 10\"),h=!!navigator.userAgent.match(/Trident.*rv:11\\./),i=b.querySelectorAll(\"iframe.wp-embedded-content\"),j=b.querySelectorAll(\"blockquote.wp-embedded-content\");for(c=0;c<j.length;c++)j[c].style.display=\"none\";for(c=0;c<i.length;c++)if(d=i[c],d.style.display=\"\",!d.getAttribute(\"data-secret\")){if(f=Math.random().toString(36).substr(2,10),d.src+=\"#?secret=\"+f,d.setAttribute(\"data-secret\",f),g||h)a=d.cloneNode(!0),a.removeAttribute(\"security\"),d.parentNode.replaceChild(a,d)}else;}}var d=!1,e=!1;if(b.querySelector)if(a.addEventListener)d=!0;if(a.wp=a.wp||{},!a.wp.receiveEmbedMessage)if(a.wp.receiveEmbedMessage=function(c){var d=c.data;if(d.secret||d.message||d.value)if(!/[^a-zA-Z0-9]/.test(d.secret)){var e,f,g,h,i,j=b.querySelectorAll('iframe[data-secret=\"'+d.secret+'\"]'),k=b.querySelectorAll('blockquote[data-secret=\"'+d.secret+'\"]');for(e=0;e<k.length;e++)k[e].style.display=\"none\";for(e=0;e<j.length;e++)if(f=j[e],c.source===f.contentWindow){if(f.style.display=\"\",\"height\"===d.message){if(g=parseInt(d.value,10),g>1e3)g=1e3;else if(200>~~g)g=200;f.height=g}if(\"link\"===d.message)if(h=b.createElement(\"a\"),i=b.createElement(\"a\"),h.href=f.getAttribute(\"src\"),i.href=d.value,i.host===h.host)if(b.activeElement===f)a.top.location.href=d.value}else;}},d)a.addEventListener(\"message\",a.wp.receiveEmbedMessage,!1),b.addEventListener(\"DOMContentLoaded\",c,!1),a.addEventListener(\"load\",c,!1)}(window,document);\n//--><!]]>\n</script><iframe sandbox=\"allow-scripts\" security=\"restricted\" src=\"https://blog.mayuko.me/wordpress-4-4-oembed-api/embed/\" width=\"600\" height=\"338\" title=\"埋め込まれた WordPress の投稿\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\" class=\"wp-embedded-content\"></iframe>"
}

どうもhtmlの中に入っているコードがカードとして出力されてそうな気配ですね・・・

せっかくなのでformatとmaxwidthも投げてみます。

maxwidthを300pxにしてみる

$ curl -X GET "https://blog.mayuko.me/wp-json/oembed/1.0/embed?url=https://blog.mayuko.me/wordpress-4-4-oembed-api/&maxwidth=300" | jq .
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  2840    0  2840    0     0   3422      0 --:--:-- --:--:-- --:--:--  3421
{
  "version": "1.0",
  "provider_name": "まよねーずブログ",
  "provider_url": "https://blog.mayuko.me",
  "author_name": "マヨネーズまゆこ",
  "author_url": "https://blog.mayuko.me/author/mayuko/",
  "title": "WordPress 4.4 で記事が埋め込めるようになるっぽい (埋め込めないケースを追記)",
  "type": "rich",
  "width": 300,
  "height": 200,
  "html": "<blockquote class=\"wp-embedded-content\"><a href=\"https://blog.mayuko.me/wordpress-4-4-oembed-api/\">WordPress 4.4 で記事が埋め込めるようになるっぽい (埋め込めないケースを追記)</a></blockquote>\n<script type='text/javascript'>\n<!--//--><![CDATA[//><!--\n\t\t!function(a,b){\"use strict\";function c(){if(!e){e=!0;var a,c,d,f,g=-1!==navigator.appVersion.indexOf(\"MSIE 10\"),h=!!navigator.userAgent.match(/Trident.*rv:11\\./),i=b.querySelectorAll(\"iframe.wp-embedded-content\"),j=b.querySelectorAll(\"blockquote.wp-embedded-content\");for(c=0;c<j.length;c++)j[c].style.display=\"none\";for(c=0;c<i.length;c++)if(d=i[c],d.style.display=\"\",!d.getAttribute(\"data-secret\")){if(f=Math.random().toString(36).substr(2,10),d.src+=\"#?secret=\"+f,d.setAttribute(\"data-secret\",f),g||h)a=d.cloneNode(!0),a.removeAttribute(\"security\"),d.parentNode.replaceChild(a,d)}else;}}var d=!1,e=!1;if(b.querySelector)if(a.addEventListener)d=!0;if(a.wp=a.wp||{},!a.wp.receiveEmbedMessage)if(a.wp.receiveEmbedMessage=function(c){var d=c.data;if(d.secret||d.message||d.value)if(!/[^a-zA-Z0-9]/.test(d.secret)){var e,f,g,h,i,j=b.querySelectorAll('iframe[data-secret=\"'+d.secret+'\"]'),k=b.querySelectorAll('blockquote[data-secret=\"'+d.secret+'\"]');for(e=0;e<k.length;e++)k[e].style.display=\"none\";for(e=0;e<j.length;e++)if(f=j[e],c.source===f.contentWindow){if(f.style.display=\"\",\"height\"===d.message){if(g=parseInt(d.value,10),g>1e3)g=1e3;else if(200>~~g)g=200;f.height=g}if(\"link\"===d.message)if(h=b.createElement(\"a\"),i=b.createElement(\"a\"),h.href=f.getAttribute(\"src\"),i.href=d.value,i.host===h.host)if(b.activeElement===f)a.top.location.href=d.value}else;}},d)a.addEventListener(\"message\",a.wp.receiveEmbedMessage,!1),b.addEventListener(\"DOMContentLoaded\",c,!1),a.addEventListener(\"load\",c,!1)}(window,document);\n//--><!]]>\n</script><iframe sandbox=\"allow-scripts\" security=\"restricted\" src=\"https://blog.mayuko.me/wordpress-4-4-oembed-api/embed/\" width=\"300\" height=\"200\" title=\"埋め込まれた WordPress の投稿\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\" class=\"wp-embedded-content\"></iframe>"
}

600~200の間であれば、縦横比をええ感じに保ちつつサイズ変更できるみたいです。

XML形式でとってみる

$ curl -X GET "https://blog.mayuko.me/wp-json/oembed/1.0/embed?url=https://blog.mayuko.me/wordpress-4-4-oembed-api/&format=xml"
<?xml version="1.0"?>
<oembed><version>1.0</version><provider_name>まよねーずブログ</provider_name><provider_url>https://blog.mayuko.me</provider_url><author_name>マヨネーズまゆこ</author_name><author_url>https://blog.mayuko.me/author/mayuko/</author_url><title>WordPress 4.4 で記事が埋め込めるようになるっぽい (埋め込めないケースを追記)</title><type>rich</type><width>200</width><height>200</height><html><blockquote class="wp-embedded-content"><a href="https://blog.mayuko.me/wordpress-4-4-oembed-api/">WordPress 4.4 で記事が埋め込めるようになるっぽい (埋め込めないケースを追記)</a></blockquote>
<script type='text/javascript'>
<!--//--><![CDATA[//><!--
        !function(a,b){"use strict";function c(){if(!e){e=!0;var a,c,d,f,g=-1!==navigator.appVersion.indexOf("MSIE 10"),h=!!navigator.userAgent.match(/Trident.*rv:11\./),i=b.querySelectorAll("iframe.wp-embedded-content"),j=b.querySelectorAll("blockquote.wp-embedded-content");for(c=0;c<j.length;c++)j[c].style.display="none";for(c=0;c<i.length;c++)if(d=i[c],d.style.display="",!d.getAttribute("data-secret")){if(f=Math.random().toString(36).substr(2,10),d.src+="#?secret="+f,d.setAttribute("data-secret",f),g||h)a=d.cloneNode(!0),a.removeAttribute("security"),d.parentNode.replaceChild(a,d)}else;}}var d=!1,e=!1;if(b.querySelector)if(a.addEventListener)d=!0;if(a.wp=a.wp||{},!a.wp.receiveEmbedMessage)if(a.wp.receiveEmbedMessage=function(c){var d=c.data;if(d.secret||d.message||d.value)if(!/[^a-zA-Z0-9]/.test(d.secret)){var e,f,g,h,i,j=b.querySelectorAll('iframe[data-secret="'+d.secret+'"]'),k=b.querySelectorAll('blockquote[data-secret="'+d.secret+'"]');for(e=0;e<k.length;e++)k[e].style.display="none";for(e=0;e<j.length;e++)if(f=j[e],c.source===f.contentWindow){if(f.style.display="","height"===d.message){if(g=parseInt(d.value,10),g>1e3)g=1e3;else if(200>~~g)g=200;f.height=g}if("link"===d.message)if(h=b.createElement("a"),i=b.createElement("a"),h.href=f.getAttribute("src"),i.href=d.value,i.host===h.host)if(b.activeElement===f)a.top.location.href=d.value}else;}},d)a.addEventListener("message",a.wp.receiveEmbedMessage,!1),b.addEventListener("DOMContentLoaded",c,!1),a.addEventListener("load",c,!1)}(window,document);
//--><!]]>
</script><iframe sandbox="allow-scripts" security="restricted" src="https://blog.mayuko.me/wordpress-4-4-oembed-api/embed/" width="200" height="200" title="埋め込まれた WordPress の投稿" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" class="wp-embedded-content"></iframe></html></oembed>

使いたいとは思わないけどXMLにも対応してました。

ちなみに

$ curl -X GET "https://wp-kyoto.cdn.rabify.me/wp-json/oembed/1.0/embed?url=https://blog.mayuko.me/wordpress-4-4-oembed-api/" | jq .
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    73    0    73    0     0    499      0 --:--:-- --:--:-- --:--:--   500
{
  "code": "oembed_invalid_url",
  "message": "Not Found",
  "data": {
    "status": 404
  }
}

urlクエリとGETリクエストを送るエンドポイントは同じサイトじゃないとだめです。

当たり前といえば当たり前なんだけど一応ね。

ブックマークや限定記事(予定)など

WP Kyotoサポーター募集中

WordPressやフロントエンドアプリのホスティング、Algolia・AWSなどのサービス利用料を支援する「WP Kyotoサポーター」を募集しています。
月額または年額の有料プランを契約すると、ブックマーク機能などのサポーター限定機能がご利用いただけます。

14日間のトライアルも用意しておりますので、「このサイトよく見るな」という方はぜひご検討ください。

広告ここから
広告ここまで

Related Category posts