Category Archives: WP REST API

WP- REST-API(v2) Setup

WP4.4 からの WordPress の oEmbed ブログカード埋め込み処理でも一部使われていましたが、wp4.7 からWordPressで REST API が広く有効化されたらしく、試してみる。

まず、プラグインで導入する必要ない、デフォルトで有効になっています。

エンドポイント

試しに、サイトのURLにwp-json/を足して、v1のエンドポイントへアクセスしてみると、たくさんの文字が出力される。

http://xie.mki.biz/wordpress/wp-json/

ここで、Chromeの拡張機能のPostmanを導入して、データを見る

postman

v1より大分長くなり、なんだろう。v2から、エンドポイント変わったね!

先人のブログを参照し、Postsだけ見るにと、出力だいぶ減り

http://xie.mki.biz/wordpress/wp-json/wp/v2/posts

Postmanからデータを見る

image

この画面はなぜかGetのした、Authorizationの表示が出って。認証すると、もっと機能が増える?

認証に関して

認証に関して、v1と変わらないみたい

このAPIにおいては、認証にはいくつかの選択肢があり、基本的に以下のように選びましょう。

  • そのサイトで有効化されたテーマやプラグインから利用するのであれば クッキー認証
  • デスクトップアプリ、ウェブアプリ、モバイルアプリなどのサイトの外からアクセスするクライアントから API を利用するのであれば OAuth 認証, アプリケーションパスワード または ベーシック認証

 

OAuth 認証は複雑なので、しかもv1.0 (OAuth 1.0a specification) の難しい方だ。まず開発段階ではベーシック認証が便利でしょう。

ベーシック認証とアプリケーションパスワードは、HTTP Basic Authentication (published as RFC2617) を利用しており、Basic Auth plugin または Application Passwords plugin のどちらかを有効化する必要があります。

ベーシック認証を使用するには、ユーザー名とパスワードをリクエストごとにAuthenticationヘッダーで送信するだけです。この値は認証のたびにBase64エンドコードでエンコードされるべきです。

WP- REST-API Setup

To Preparation WordPress wp-api,  you have three setup steps:

  1. JSON REST API
  2. Authenticate
  3. Permalink

JSON REST API

Grab the latest version of JSON REST API on WordPress plugin directory. Install and activate it.

Authenticate

There are three ways you can authenticate.

Using the cookies

This is one method not widely used when working with APIs. When a user navigates on the web, pages tend to store data on users side. The cookie method here is a bit different by using the nonces method.

OAuth

This plugin implements the version 1.0a of OAuth. This method is widely used. Google, Facebook, Twitter and Flickr use OAuth for third party authentication.

Basic Authentication

Using this method you have to send your username and password each time you make a request. Client tools for REST testing usually have this method implemented themselves. This method is mainly used when developing. Is rarely used on production. On production consider using OAuth.

the Basic Authentication plugin only on it’s GitHub repository.

git clone https://github.com/WP-API/Basic-Auth basicAuth

Permalink

Change the permalink configuration to any other that not default.

WP- REST-API with AppInventor

AppInventorはAndoridのApp作りに簡単な環境です。WordPressはWebコンテンツを作るに最適な環境。

AppInventor is a easy way to creating an Android app from web browser.  WordPress is a best web content management tool.

WP- REST-APIは、両者の長所を連携し、WordPressをAppInventorのWebサービスとして利用するためのAPIとして利用する。

WP- REST-API use you WordPress as a web service for AppInventor App.

API endpoint

 

Posts

Get

Post

Firefox_Screenshot_2015-09-05T10-22-07.193Z

Delete

Media

Post

Firefox_Screenshot_2015-09-05T10-24-14.020Z

Users

Get

WP- REST-API with Python

API endpoint

import http.client
 
def main():
    conn = http.client.HTTPConnection("wp-api.pw")
    
    conn.request("GET", "/wp-json/")
    res = conn.getresponse()
    print(res.status, res.reason)
    print(res.read())
    conn.close()
 
if __name__ == "__main__":
    main()

Posts

Get

Post

Delete

Media

Post

Users

Get

WP- REST-API with cURL

API endpoint

[chen@luna ~]$ curl -l http://wp-api.pw/wp-json/

Posts

Get

The Posts endpoint returns a Post Collection containing a subset of the site’s posts.

[chen@luna ~]$ curl -l http://wp-api.pw/wp-json/posts

Post

Create a Post Requires authentication

[chen@luna ~]$ cat data.json
{
    "title": "This is a post",
    "content_raw": "This is some content"
}
[chen@luna ~]$ curl --user test:password -X POST http://wp-api.pw/wp-json/posts --data @data.json

Delete

Delete a Post Requires authentication

[chen@luna ~]$ curl --user test:password -X DELETE http://wp-api.pw/wp-json/posts/229
{"message":"Deleted post"}

Media

Post

To create the raw data for an attachment. This is a binary object (blob), such as image data or a video.

[chen@luna ~]$ curl --user test:password -H 'Content-Type:image/jpeg' -H 'Content-Disposition: attachment; filename="test1551.jpg"' -X POST http://wp-api.pw/wp-json/media --data-binary @/home/chen/IMG_1551.jpg

Users

Get

This endpoint offers a permalink to get the current user, without needing to know the user’s ID.

get user self

[chen@luna ~]$ curl --user test:password http://wp-api.pw/wp-json/users/me

get user list

[chen@luna ~]$ curl --user test:password http://wp-api.pw/wp-json/users

WP- REST-API with Java

API endpoint

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
 
 
public class Main {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://wp-api.pw/wp-json/");
 
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
 
            System.out.printf("Response: %d %sn", conn.getResponseCode(), conn.getResponseMessage());
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String input;
 
            while ((input = br.readLine()) != null) {
                System.out.println(input);
            }
            br.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Posts

Get

The Posts endpoint returns a Post Collection containing a subset of the site’s posts.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
 
 
public class Main {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://wp-api.pw/wp-json/posts");
 
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
 
            System.out.printf("Response: %d %sn", conn.getResponseCode(), conn.getResponseMessage());
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String input;
 
            while ((input = br.readLine()) != null) {
                System.out.println(input);
            }
            br.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Post

Create a Post Requires authentication

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
 
 
public class Main {
    public static void main(String[] args) {
        try {
            String content = '{"title": "This is a post","content_raw": "This is some content"}';
            URL url = new URL("http://wp-api.pw/wp-json/posts");
 
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString("test:password".getBytes(StandardCharsets.UTF_8)));
            conn.setRequestProperty("Content-Length", String.valueOf(content.getBytes("UTF-8").length));
            conn.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
            wr.writeBytes(content);
            wr.flush();
            wr.close();
 
            System.out.printf("Response: %d %sn", conn.getResponseCode(), conn.getResponseMessage());
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String input;
 
            while ((input = br.readLine()) != null) {
                System.out.println(input);
            }
            br.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Delete

Delete a Post Requires authentication

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
 
 
public class Main {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://wp-api.pw/wp-json/posts/229");
 
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("DELETE");
            conn.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString("test:password".getBytes(StandardCharsets.UTF_8)));
 
            System.out.printf("Response: %d %sn", conn.getResponseCode(), conn.getResponseMessage());
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String input;
 
            while ((input = br.readLine()) != null) {
                System.out.println(input);
            }
            br.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Media

Post

To create the raw data for an attachment. This is a binary object (blob), such as image data or a video.

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
 
 
public class Main {
    public static void main(String[] args) {
        try {
            char[] buffer = new char[1024];
            StringWriter writer = new StringWriter();
            FileReader fileReader = new FileReader("/home/chen/IMG_1551.jpg");
            for (int n = 0; -1 != (n = fileReader.read(buffer));) {
                writer.write(buffer, 0, n);
            }
            fileReader.close();
            String content = writer.toString();
            URL url = new URL("http://wp-api.pw/wp-json/media");
 
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "image/jpeg");
            conn.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString("test:password".getBytes(StandardCharsets.UTF_8)));
            conn.setRequestProperty("Content-Length", String.valueOf(content.getBytes("UTF-8").length));
            conn.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
            wr.writeBytes(content);
            wr.flush();
            wr.close();
 
            System.out.printf("Response: %d %sn", conn.getResponseCode(), conn.getResponseMessage());
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String input;
 
            while ((input = br.readLine()) != null) {
                System.out.println(input);
            }
            br.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Users

Get

This endpoint offers a permalink to get the current user, without needing to know the user’s ID.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
 
 
public class Main {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://wp-api.pw/wp-json/users/me");
 
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString("test:password".getBytes(StandardCharsets.UTF_8)));
 
            System.out.printf("Response: %d %sn", conn.getResponseCode(), conn.getResponseMessage());
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String input;
 
            while ((input = br.readLine()) != null) {
                System.out.println(input);
            }
            br.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}