There are loads of free, and paid-for, REST APIs out there that provide access to data and services. You can hook into these to build your own web-based apps. Learn how to add some code to your WordPress website to consume data from an external REST API, and then display it on your site.
For this tutorial, we’re going to pull some data from a public ipsum text generator API. Basically, it’s a free gobbledygook generator π π π
importantTo follow this tutorial, you’ll need to be using a custom child theme so you can edit your functions.php.
How it Works
We’re going to create a shortcode that pulls some gobbledygook from the Ipsum API and then renders it in the HTML output back to the browser. The shortcode will be called [flipsum_ipsum]
and it’ll take the following parameters:
- ipsum (string): The name of the ipsum generator to use, because Flipsum Ipsum lets us choose what sort of gobbledygook we want.
- paragraphs (int): How many paragraphs of gobbledygook do we want?
Accessing REST APIs uses exactly the same process as accessing web pages. All we need to do is create a URL, request that URL from the relevant server, then process the result. The API result will be in JSON format, which PHP can convert into an array for us. The Flipsum Ipsum API is easy to use. Here’s an example URL – paste this into a new tab to see the API response.
https://power-plugins.com/api/flipsum/ipsum/lorem-ipsum
Available Ipsums
- Anchorman Quotes IpsumAnchorman
- Cannonball Run IpsumCannonball Run
- Coffee Shop IpsumCoffee Shop
- Compliments IpsumCompliments
- Corporate IpsumCorporate
- Fairy Tale IpsumFairy Tale
- Groovy IpsumGroovy
- Jabberwocky IpsumJabberwocky
- Kids Questions IpsumKids Questions
- Classic Lorem IpsumClassic Lorem Ipsum
- Movie Quotes IpsumMovie Quotes
- Naked Gun IpsumNaked Gun
- Cooking Recipe IpsumRecipe
- Seaside IpsumSeaside
- Simpsons IpsumSimpsons
- Song Lyrics IpsumSong Lyrics
- Star Trek IpsumStar Trek
- Withnail & IpsumWithnail & I
Let’s Write some Code
In your custom child theme’s folder, create a file called shortcode-ipsum.php and paste the following into it.
<?php /** * Flipsum Ipsum Shortcode * * https://wp-tutorials.tech/add-functionality/access-a-rest-api-from-wordpress/ */ // If this file is called directly, abort. defined('WPINC') || die(); const FIS_DEFAULT_IPSUM = 'lorem-ipsum'; const FIS_DEFAULT_PARAGRAPHS = 5; const FIS_DEFAULT_ENABLE_DEBUG = false; function do_shortcode_flipsum_ipsum($atts) { $html = ''; if (is_admin() || wp_doing_ajax()) { // ... } else { // Parse the shortcode's options. $args = shortcode_atts( array( 'ipsum' => FIS_DEFAULT_IPSUM, 'paragraphs' => FIS_DEFAULT_PARAGRAPHS, 'debug' => FIS_DEFAULT_ENABLE_DEBUG, ), $atts ); $url = sprintf( 'https://power-plugins.com/api/flipsum/ipsum/%s?paragraphs=%d', urlencode($args['ipsum']), $args['paragraphs'] ); // Create a Curl Handle. $ch = curl_init(); // Standard PHP/Curl options for a simple GET request. curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Execute the request. $json_response = curl_exec($ch); $response_code = intval(curl_getinfo($ch, CURLINFO_HTTP_CODE)); // Close the Curl Handle. curl_close($ch); if ($response_code != 200) { $html .= sprintf('<p><strong>ERROR:</strong> Got HTTP response %d from the server.</p>', $response_code); } elseif (empty($json_response)) { // No data returned from the server. $html .= sprintf('<p><strong>ERROR:</strong> Empty respone from the server.</p>'); } elseif (boolval($args['debug'])) { // Render the raw JSON response. $html .= '<pre>'; $html .= sprintf("HTTP_RESPONSE=%d\n", $response_code); $html .= sprintf("%s", print_r(json_decode($json_response), true)); $html .= '</pre>'; } elseif (empty($ipsum_paragraphs = json_decode($json_response, true))) { $html .= sprintf( '<p><strong>ERROR:</strong> Failed to process the JSON response.</p><pre>%s</pre>', esc_html($json_response) ); } else { // Loop through the paragraphs foreach ($ipsum_paragraphs as $ipsum_paragraph) { $html .= sprintf('<p>%s</p>', esc_html($ipsum_paragraph)); } } } return $html; } add_shortcode('flipsum_ipsum', 'do_shortcode_flipsum_ipsum');
The logic is pretty straightforward. The main sequence breaks down like this:
- Create a URL to access the Flipsum Ipsum API.
- Create a Curl Handle (
$ch
)…- Set some standard options.
- Execute the request.
- Store the result body (hopefully, a big string full of JSON data).
- Store the HTTP Response Code (hopefully 200=OK).
- Close the Curl Handle.
- If the API returns nothing (an empty string) then set the returned HTML to an error string.
- If we’ve passed
debug=true
in our shortcode parameters then set the returned HTML to the raw text returned by the API. Useful for debugging/testing. - If PHP can’t convert the API response into an array using json_decode() then return an error string AND the raw response, so we can figure out what the problem is.
- Loop over the returned paragraphs and return the HTML to the frontend, with each paragraph wrapped in <p></p>.
Next, open your child themeβs functions.php and paste this into it.
// WP Tutorials : Flipsum Ipsum Shortcode require_once dirname(__FILE__) . '/shortcode-ipsum.php';
In the block editor, create a shortcode block, enter [flipsum_ipsum], save your content and the view it. Boom! Instant nonsense for your website!
Shortcode Examples
Shortcode | Description |
---|---|
[flipsum_ipsum] | Let the API pick a random ipsum generator for us, and return the default number of paragraphs. |
[flipsum_ipsum ipsum=’coffee-shop’ debug=true] | Grab some “coffee-shop” gobbledygook with the default number of paragraphs, and show the raw API response. |
[flipsum_ipsum ipsum=’recipe’ paragraphs=10] | Generated 10 paragraphs of tasty gobbledygook and render it normally, in paragraph HTML elements. |
Extending the Shortcode
This shortcode here is pretty basic, but works well enough. There are plenty of ways to extend it.
Cache the API Response in a Transient
To speed things up for your visitors, you might want to cache the API responses, so you don’t have to query the API for every request that comes to your site. You can store the gobbledygook in a WordPress transient – a short-lived data store that vanishes after a timeout (e.g. 1 hour or 1 day).
It could work something like this:
- The user wants some gobbledygook.
- Do we already have some gobbledygook in our transient?
- If yes then…
- Grab the gobbledygook from the transient.
- Else…
- Fetch some gobbledygook from the Flipsum Ipsum API.
- Store the new gobbledygook in our transient with a timeout of 1 hour (or whatever you want).
- If yes then…
- Render the gobbledygook.
The next time a user wants some gobbledygook, you can just use what’s in the transient, which will be much faster than calling the remote API every time.
Go forth and spread the gobbledygook ππ
Hello Paul,
Though it was looking promising, I must say I could not make it work properly,
First you say to create a shortcode-ipsum.php under the child theme, which I did.
The basic shortcode (no param) on the test page (or post) did not get interpreted.
Next, I realize I may need to add this code into the functions.php, instead of shortcode-ipsum.php:
Now I get “ERROR: No respone from the server.”
Better (in a way), still no satisfactory…
Cheers !
Hi!
I’ve just rerun the tutorial myself on a dev site and it works correctly, although I’ve added s bit to make a reference to functions.php. My mistake.
If you’re getting no response from the server, my guess is that your server’s IP address has ended up on an IP firewall block list. What’s your server’s IP address and I’ll check our logs for you.
Paul
Hello Paul,
Thank you for your time.
Here’s the url : https://www.xcontest.org/world/en/pilots/detail:El_Condorito
Cheers
It looks like your server’s IP address is 81.0.213.97 (Prague) and it isn’t on any of our blocklists, so the code should be able to connect to the Flipsum Ipsum server without a problem. Maybe your web server is having a problem with the
file_get_contents()
function?I’ve rewritten the code this morning so instead of using file_get_contents() to GET the data from the remote server, we’re using PHP/Curl. It’s a few extra lines of code but it will probably be more robust. Try copying-and-pasting the new version into shortcode-ipsum.php and see if it works now.
Hello Paul,
Thanks for checking out and providing a new version.
Maybe there was a misunderstanding : My website is parapente-mexico.com, but I am trying to fetch data from the site quoted above.
Anyway, even with the verbatim new code provided (hence fetching the flipsum-ipsum webservice), I would get the following error : “Got HTTP response 0 from the server.”
Here’s the page : https://parapente-mexico.com/ipsum-impl/
In the page editor, all I put was the following shortcode :
[flipsum_ipsum]
erm… It should work fine, but clearly it’s not working. I just ran the tutorial on a totally separate machine and it is good.. I wonder if it’s because your hosting/server has disabled certain PHP functions? Some web server block PHP from downloading external files to prevent malware.
Maybe try this… In your website’s root folder (where WordPress is installed) create a new file called phpinfo-test.php and put the following in it:
phpinfo();
…then point your browser at /phpinfo-test.php – Have a look for the directive called disable_functions. Don’t forget to delete phpinfo-test.php when you’ve finished.
or… we (Headwall Hosting) could host your site ππ …although we only have European servers at the moment (UK and Germany).
Hello,
Thank you again for your time.
May I suggest you implement a plugin like https://wordpress.org/plugins/comment-reply-email-notification/ ?
For the record, I implemented this example : https://github.com/YTTechiePress/query-apis
And it works, only when I change the url for yours (flipsum) it would display an error.
As for your question, “opcache_get_status” is disabled.
My hosting is in France, and I am happy with them (ikoula.com)
Don’t worry. I will find out a solution. π