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:
/wp-json/easy-post/v1/rates/
[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:
/wp-json/easy-post/v1/rates/?zip=78701&width=10&length=10&height=10&weight=10&shipping_zip=78751
[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.
Need to pull shipping rates into your site dynamically? Now you’re ready to go.
You can view the full file here.
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!
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.
I’d recommend working locally while you do development (watch this video to learn how): https://wptheming.com/2018/01/setting-up-a-local-environment/. Then, once you have everything working, upload the new/updated files via SFTP.