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:
<div id="tomsword">... word goes here ...</div>
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',
'permission_callback' => '__return_true',
'callback' => 'tomjn_rest_test'
) );
} );
Congrats! I now have an endpoint, and you can see it by visiting https://tomjn.com/wp-json/tomjn/v1/test :

As for what those parameters do:
tomjn/v1is the namespace and beginning of the URL ( /wp-json/tomjn/v1/test )/test/is the name of the endpoint ( /wp-json/tomjn/v1/test )'methods' => 'GET'tells it to respond to normal browser GET requests, like<form method="get"...or just loading the page in a browser via the address bar'permission_callback' => '__return_true',is a chance to name a function that controls if the user can or cannot use this. I’ve chosen__return_trueso everybody can use it'callback' => 'tomjn_rest_test'when someone uses this endpoint, call thetomjn_rest_testfunction to get the answer
Using our Endpoint in The Theme
Let’s write some javascript in our template:
<script>
jQuery.ajax({
url: <?php echo wp_json_encode( esc_url_raw( rest_url( 'tomjn/v1/test' ) ) ); ?>
}).done(function( data ) {
jQuery( '#tomsword' ).text( data );
});
</script>
It’s that simple! Now our homepage runs a bit of code when we load it, that fetches a word from a REST API, and puts it in a div.
Writing REST API endpoints is quick, and easier to secure. There’s no reason to use the AJAX API in the future.
Leave a Reply