Monday 23 January 2017

Writing a WP REST API endpoint in 2 minutes


I need to write a REST API endpoint, but lets assume we know nothing about REST APIs. The Task
My homepage has a box that contains a magical word, and I’m going to use the REST API to grab this word and display it on my site:

… word goes here …

I’m going to need:
A word to use, I’ve chosen “moomins”
A REST API endpoint on my site to send the word from
Some Javascript to ask the API for the magic word
The Endpoint
This parts easy. REST API endpoints live at /wp-json, and they have a namespace so your endpoints don’t clash with those of other plugins. My endpoint is going to live at tomjn.com/wp-json/tomjn/v1/test.
When my endpoint is called, I want to return the word “moomins”, so I’ve prepared a function to do just that:
function tomjn_rest_test() {
return "moomins";
}
and I’ll register my endpoint, and tell WordPress what to do when it’s called like this:
add_action( ‘rest_api_init’, function () {
register_rest_route( ‘tomjn/v1’, ‘/test/’, array(
‘methods’ => ‘GET’,
‘callback’ => ‘tomjn_rest_test’
Source: https://managewp.org/articles/14258/writing-a-wp-rest-api-endpoint-in-2-minutes




source https://williechiu40.wordpress.com/2017/01/23/writing-a-wp-rest-api-endpoint-in-2-minutes/

No comments:

Post a Comment