①エンドポイントの作成

Kotlin

functions.php

add_action('rest_api_init', function(){
    register_rest_route('custom/v1', '/register', array(
        'methods' => 'POST', ※1
        'callback' => 'register_app_user',
        'permission_callback' => '__return_true',
    ));
});

※1 … POSTとGET

POST … AndroidStudioからWordPressのデータベースにデータを保存するとき

GET … WordPressのデータベースからデータをGETしてAndroidStudio側に表示するとき

'methods' => array('GET', 'POST'),

としてGETでもPOSTでも問題ないようにします。

コードが正しい場合

実際に、https://xxx.com/wp-json/custom/v1/register にアクセスすると次のような配列が表示されます。

[{"id":"1","en1":"h","en2":"o","en3":"t","en4":"","en5":"d","en6":"o","en7":"g","en8":"","en9":"","en10":"","en11":"","en12":"","en13":"","en14":"","en15":"","en16":"","en17":"","en18":"","en19":"","en20":"","en21":"","en22":"","en23":"","en24":"","en25":"","en26":"","en27":"","en28":"","en29":"","en30":""}]

コードが正しくない場合

コードが正しくない場合、https://xxx.com/wp-json/custom/v1/register にアクセスすると次のようなコードが表示されます。

{"code":"rest_no_route","message":"URL \u3068\u30ea\u30af\u30a8\u30b9\u30c8\u30e1\u30bd\u30c3\u30c9\u306b\u4e00\u81f4\u3059\u308b\u30eb\u30fc\u30c8\u304c\u898b\u3064\u304b\u308a\u307e\u305b\u3093\u3067\u3057\u305f\u3002","data":{"status":404}}

これは「404エラー」であり、このURLのエンドポイントが存在しないことを意味します。

以下の2点を確認してください。

・エンドポイントのURL文字列が正しいかどうか

・’methods’ => ‘POST’ なのか ‘GET’なのか

BACK