WordPress includes an exceptionally useful API called the HTTP API that can be used for sending data to and retrieving data from remote APIs. If you are building a plugin that talks to Stripe, MailChimp, or just about any other service that provides an API, you can use the WP HTTP API to make your job significantly easier. For this tutorial, I’m going to show you how to use wp_remote_get(), one of the several functions included in the HTTP API, to retrieve and parse JSON data from a remote API.
There are four primary functions that comprise the HTTP API in WordPress:
- wp_remote_post() – For sending data to an endpoint
- wp_remote_get() – For retrieving data from an endpoint
- wp_remote_head() – For sending a HEAD request
- wp_remote_retrieve_body() – For retrieving the main body content from the server response
For this tutorial, we will use wp_remote_get() since we wish to retrieve data from an API and then parse it.
Most modern APIs return data in a format called JSON (Javascript Object Notation). While the name includes Javascript, you don’t actually have to write or even know Javascript in order to parse JSON. For all intents and purposes, JSON can be considered a mostly universal data format that just nearly all programming languages can read, with PHP being no exception.
A simple JSON object looks like this:
{ "key":"value" }
In order to use this in PHP, we need to translate it to a format that PHP understands. To do this, we can use the json_decode() function.
$json = '{"key":"value"}'; // Translate into an object $obj = json_decode( $json ); // Translate into an array $array = json_decode( $json, true );
It is really that simple, but this is also an exceptionally simple example, so let’s look at a more complex example.
Easy Digital Downloads includes a REST API that can be used for retrieving sales, earnings, customers, discounts, and product data. The first four endpoints require a valid set of API keys for authorization, but the products endpoint of the EDD API is publicly accessible, so we’ll use that as an example.
If you visit https://pippinsplugins.com/edd-api/products in your browser, you will see raw JSON spit out:
This JSON contains all of the public information about the products I sell on this website. If we wanted to, we could easily use this API endpoint to pull product data from pippinsplugins.com and display it on an external site, perhaps in a sidebar or footer widget.
For this example, let’s assume that we want to pull this product data into a plugin that we have written and then do something with it there, perhaps display it in an admin page.
The first thing we need to do is make the request with wp_remote_get().
$request = wp_remote_get( 'https://pippinsplugins.com/edd-api/products' );
That will make a call to the specified URL and return an array of data about the response, including headers, cookies, body, and more.
Before we do anything with the response body (that’s where the JSON is stored), we need to validate it and ensure that we got back a response that we expected.
If the remote request fails, wp_remote_get() will return a WP_Error, so let’s check if the $request variable is an error:
Once we have determined that the request was not an error, we can proceed to retrieving the data. For this, we’ll use the wp_remote_retrieve_body() helper function:
The $body variable will now contain a JSON object that matches the screenshot above.
All we need to do now is translate the JSON into a format we can read, either an array or an object.
Once we have decoded the JSON, we can interact with the product data just like we would any other object in PHP. For example, we could loop through them and display the products in an unordered list:
Whatever the API, JSON responses are always very similar to work with, so once you understand the methods needed to retrieve and parse the data, working with most APIs becomes significantly easier.
Pippin,
Thanks for this post. I happen to be in the middle of trying to leverage the WP-API to create an EDD Download on EDD/FES from an application that is external to our WordPress.
I see the approach you’ve described for retrieving the publicly available data, and we’ve got that to work another way.
Is there a way in EDD/FES to create/edit a download? I can move this over to EDD forums if you would like me to.
Creating a download product is just like creating a standard WP post (with a post_type of “download”) and then supplying the appropriate meta data.
Have you familiarized yourself with how to create posts through the WP API?
Pippin,
We have familiarized ourselves about how to create the post. We were going down a route using an external plugin to communicate. However, looking at the EDD-API code and what you describe here, I think we should just focus on leveraging what you’ve built already.
The EDD API doesn’t currently support creating products (or other data), it’s only for retrieving data.
I recently learned about
wp_safe_remote_get()
first introduced in 3.6 from Nacin’s talk at Loop Conf this year. I’m wondering if rejecting unsafe URLs should be the more common approach for fetching, much likewp_safe_redirect()
has become for redirecting?LoopConf was the first time I had heard of it as well. In general, I’d say “yes”, it’s probably best to use the safe method.
This was also just pointed on by George Stephanis on Twitter: https://twitter.com/daljo628/status/601410958624448512
hi Pippin – great post. Is it possible to use the above to parse JSON data into WP with basic authentication? I’ve been experimenting with your code to try and fill in a username element (password not required) – but am not having much luck. Any thoughts?
thanks,
A
There is, though you’ll have to handle the validation of the credentials yourself. We did this recently for AffiliateWP. If you’d like to see how we did it, take a look here: https://github.com/AffiliateWP/AffiliateWP/blob/master/includes/REST/class-rest-authentication.php
Absolutely awesome point by point explanation. I am a blogger and i have some few ideas to integrate an API into my WordPress. I really very happy to move from here with hope as i will make the API integration successfully with your guide. Will back after some days with success.
Pippin,
I’ve been working on setting up JSON get statements in my WordPress for the last 20hrs. I couldnt find a single straightforward post about it.
Your post has helped me come very close to my desired output!!
Thank you sooo much for posting this.
I will be viewing the rest of your content for any gems! 🙂
Thanks Pippin! I am so glad to have read this one.
forgive me but where would I put the above code so the response data is displayed to users? I copied the above code into the footer.php but parts of the json request were displayed on the screen and not the response. I have found this implementing API into wordpress extremely difficult but see the huge potential it has. I just have not found an easy to follow how too yet everybody is saying its easy
Gam,
Any response to your question???
Like yourself, I’m finding it extremely difficult to navigate the API WP integration!
I have all the code, etc, I just need to know where do I place this code, inside my website for my clients to be able to use! This shouldn’t be difficult, but I can find no easy way to actually “link” my get response to my site
Why is this so over the top difficult?
This is quite simply excellent! Very clear and no excess fluff!
Maybe best to use wp_json_decode rather than just json_decode 😉
Ok I am an idiot, this function doesn’t exist. Maybe I thought it did, because maybe it should 😉
How does this work when calling another .php file with wp_remote_get() which accesses a database and returns multiple rows with more than one column each ( and a \n after each row) ?
To populate a webpage with the data .
Goodafternoon. I am new to API and I am having problem integratng the API of a delivery website into the place order part of the checkout page in a shopping website. Please how do I go about it?
Excellent tutorial for use third party ingratiation API. This tutorial need to be prompt more. got this tutorial after huge search.
Most of the tutorials are misguided and with insufficient information.
Thanks for such nice tutorial.
please i want the ETHBTC price to be updating dynamically without refreshing the page,,
please i want the ETHBTC price to be updating dynamically without refreshing the page,,
please i want the ETHBTC price to be updating dynamically without refreshing the page,,
$request = wp_remote_get( ‘https://api.binance.com/api/v3/ticker/price?symbol=ETHBTC’ );
$body = wp_remote_retrieve_body( $request );
$data = json_decode( $body, true );
echo ($data[‘price’] ) ;
Thank you Pippin.
Hi
Thank for you for this post!
Can you help please to parse my Json?
Below an overview ot the response:
+++++++++++++++++++
stdClass Object
(
[response] => stdClass Object
(
[status] => ok
[version] => 2
[requestid] => oaiGqA
[requests] => 8
[content] => stdClass Object
(
[total] => 72
[start] => 0
[step] => 50
[items] => Array
(
[0] => stdClass Object
(
[ID] => 002814396300022190bbd
[SubscriptionID] => 2824258
[AccountID] => 2814396
[Name] => DOMODECO Rhône-Alpes – Edition Lyon – Janvier/février 2020
[Description] => DOMODECO DECO I ARCHI I DESIGN I SOURCE D’INSPIRATION N° 93 RECONNEXION LA TOUR ROSE RENAISSANCE DESIGN ET GUSTATIVE A LA MATIERE DECORATION LES TEXTURES EN MODE 3D MISE EN BOUCHE 2020 COLLABORATIONS, NOUVEAUTES DESIGN, TENDANCES…
[Category] => MISC
[Format] => MISC
[Dialect] => fr
[Status] => DONE
[IsPublished] => 1
+++++++++++++++++++
Now what is the rich PHP loop to get, the NAME?
Here is my PHP that do not works 🙁
$request = wp_remote_get( ‘I REMOVE IT FOR SECURITY RESAON’ );
if( is_wp_error( $request ) ) {
return false; // Bail early
}
$body = wp_remote_retrieve_body( $request );
$data = json_decode( $body );
if( ! empty( $data ) ) {
echo ”;
foreach( $data->items as $product ) {
echo ”;
echo ‘name ) . ‘”>’ . $product->name . ‘‘;
echo ”;
}
echo ”;
}