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:


[gist id=”dd15de71e3c563a3e6577acea7fa2d9d” file=”wordpress-easy-post.php” lines=”9-21″]

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.

Example URL with query strings:


[gist id=”dd15de71e3c563a3e6577acea7fa2d9d” file=”wordpress-easy-post.php” lines=”23-71″]

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.

[gist id=”dd15de71e3c563a3e6577acea7fa2d9d” file=”wordpress-easy-post.php” lines=”73-123″]

Using the Data

When accessing your endpoint, the JSON data fetched from Easy Post should now appear.

Easy Post API

Need to pull shipping rates into your site dynamically? Now you’re ready to go.

You can view the full file here.

About Devin

I am a developer based in Austin, Texas. I run a little theme shop called DevPress and help manage a WooCommerce shop with Universal Yums. Find me on twitter @devinsays.

2 Responses

  1. Dear Devon,
    Thanks so much for this example! I am a newb working with WP and I have a question. Where would this file live? I assume it should be in the cPanel. Please advise. Thanks so much!

Leave a Reply