How to Set JSON Endpoints in WordPress to Access an External API

There’s a lot of JSON-based APIs that only provide access through server-side methods. If you want to use client side javascript with one of these external APIs, you’ll need to have your server access the data and serve it through ajax requests or your own JSON endpoint. Thankfully, this is really easy to do with WordPress.

In this example project, I’ll show how to get shipping rates from the Easy Post API with a custom WordPress endpoint.

To simplify this tutorial, I’m only sending 6 parameters (which is just enough data for Easy Post to return a shipping rate):

Package Width

Package Height

Package Length

Package Weight

Zip Code of Sender

Zip Code of Receiver

Setting Up the JSON Endpoint

First step is to register the route where the JSON data will be served. In this case:

Displaying the Data

The endpoint route is expecting six pieces of data to be sent as query strings, and it uses that to fetch data from the remote API. If the query strings aren’t present, defaults are used. All the parameters are sanitized to ensure they are integers.

Fetching the Data

The function “easy_post_make_request” is what actually requests the data from the external API. The majority of the code here is just arranging the request into an array that the Easy Post API can process.

You could create a custom plugin or include it from your theme. If you’re including it from your theme, you’d put your custom code in a file in the theme directory, and then include that from functions.php.