WP Snippet #005 Simple custom Rest Api route
Tags: wordpress, webdev, javascript
Published: 2020-02-13 19:29:25

---
title: WP Snippet #005 Simple custom Rest Api route
published: true
description: How to register a custom wordpress rest api end-point or your theme and use javascript to make a call for that custom data.
canonical_url: https://since1979.dev/snippet-005-simple-custom-rest-api-route/
cover_image: https://since1979.dev/wp-content/uploads/2020/02/snippet-005-custom-rest-api-route.jpg
tags: wordpress, webdev, javascript
---
[Originally posted on my website on February 13th 2020](https://since1979.dev/snippet-005-simple-custom-rest-api-route/)


How to create a custom WordPress Rest Api route.
------------------------------------------------

The [WordPress Rest Api](https://developer.wordpress.org/rest-api/) has many build in [endpoints](https://developer.wordpress.org/rest-api/reference/) for you to access. But sometimes you may need something a little more specific, or need access to a resource that is not supported out of the box. In these cases you can create your own custom endpoint. In this example we create a (pretty useless) endpoint for fetching post meta values.

{% gist https://gist.github.com/vanaf1979/97e9dd42950d82e57717845a4e8d5487 %}

With the snippet above we add an action to the *[rest_api_init](https://developer.wordpress.org/reference/hooks/rest_api_init/)* hook, and register a new callback function called *mytheme_get_meta_value*.

With the *mytheme_get_meta_value* function we make a call to the *[register_rest_route](https://developer.wordpress.org/reference/functions/register_rest_route/)* function and pass three parameters:

-   **$namespace**: A unique namespace that groups your custom endpoints. This will be the first URL segment after core prefix.
-   **$route**: The actual route. Usually a resource name with optional parameters.
-   **$args**: An array of arguments.

For the *$route* parameter we pass a string including two parameter expressions like *(?P<post>[\d]+)* This tells WordPress that we are expecting a parameter *(?P)* by the name of "*post"* with a value that must follow the regular expression of *[\d]+* meaning an integer/id. Second we expect a parameter by the name of "*key*" that must follow the regular expression of [a-zA-Z0-9_-]+ meaning a string of letters, numbers. underscores and dashes.

**Note:** You don't have to use url parameters in this way. You could also pass Get parameters (?posts=9&key=some_value) or Post parameters.

For the arguments parameter we pass an array with two key/value pairs:

-   **Methods:** The request method. E.g. GET, POST or a [WP_REST_Server constant](https://developer.wordpress.org/reference/classes/wp_rest_server/) like
    WP_REST_Server::READABLE = 'GET',
    WP_REST_Server::EDITABLE = 'POST, PUT, PATCH',
    WP_REST_Server::DELETABLE = 'DELETE',
    WP_REST_Server::ALLMETHODS = 'GET, POST, PUT, PATCH, DELETE'
-   **Callback:** The callback function that will be called when the route is requested.

**Note:** You could also pass an array of arrays where each inner array has a different *method* and *callback* function. This is useful when you need a different callback function for Get and Post methods.

### End-point callback function.

In the code above we passed *mytheme_handle_get_meta_value* as our route callback function. Lets create that function now.

{% gist https://gist.github.com/vanaf1979/d8561a6e16b2fa992de363f71863434f %}

In this callback function we first extract the *post* and *key* parameters from the passed in $request array. These values come from the Url parameters we set for the *$route* parameter in the *register_rest_route* function earlier.

We then use these values to retrieve the meta value using the *get_post_meta* function. If the value can not be found we return a [*WP_Error*](https://developer.wordpress.org/reference/classes/wp_error/) object explaining what went wrong. If we did find a value we use the *[rest_ensure_response](https://developer.wordpress.org/reference/functions/rest_ensure_response/)* function to return it. The *rest_ensure_response* function expects an array so we create one with a key of *meta* and the value we need to return. We use the meta key in our javascript later to retrieve the value.

### Calling the End-point with Javascript

Now that our endpoint is set up, we can try and call it using Javascript.

{% gist https://gist.github.com/vanaf1979/e68c33575c2e47a478915e980c88f67b %}

Here we use the *[$.ajax](https://api.jquery.com/jquery.ajax/)* function to make a GET request to *'/wp-jsaon/mytheme/v1/meta/9/_thumbnail_id',* where *9* is a post id and *_thumbnail_id* is the meta value we want to retrieve. On success we get the *meta* key from the returned *data* object to get our meta value and log it to the console. This *meta* key comes from the array we passed to *rest_ensure_response* earlier. If we get an error we use *error.responseJSON.message* to get the error message and log that to the console.

### Further reading

This is just a simple/basic example and we didn't handle things like securing the endpoint which I highly recommend you do when dealing with delicate data. You can read up on security and more in the [Rest Api handbook](https://developer.wordpress.org/rest-api/) under [Adding custom endpoints](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/).

#### Follow
Found this post helpful? Follow me on twitter [@Vanaf1979](https://twitter.com/Vanaf1979) or here on Dev.to [@Vanaf1979](https://dev.to/vanaf1979) to be notified about new articles, and other WordPress development related resources.

**Thanks for reading**