Consume an External REST API from WordPress

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 the Flipsum Ipsum website, which is a free Ipsum generator. 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 Flipsum Ipsum site 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 that returns 5 paragraphs of Fairy Tale Ipsum.

https://flipsum-ipsum.net/api/icw/v1/generate?ipsum=fairy-tale&paragraphs=5

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_PARAGRAPHS = 5;

function do_shortcode_flipsum_ipsum($atts) {
	$html = '';

	if (is_admin()) {
		// ...
	} elseif (wp_doing_ajax()) {
		// ...
	} else {
		// Parse the shortcode's options.
		$args = shortcode_atts(
			array(
				'ipsum' => '',
				'paragraphs' => FIS_DEFAULT_IPSUM_PARAGRAPHS,
				'debug' => false,
			),
			$atts
		);

		$url = sprintf(
			'https://flipsum-ipsum.net/api/icw/v1/generate?paragraphs=%d',
			$args['paragraphs']
		);

		// If we've specified an ipsum generator, then add it to the URL.
		if (!empty($args['ipsum'])) {
			$url .= sprintf('&ipsum=%s', $args['ipsum']);
		}

		// 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", $json_response);
			$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:

  1. Create a URL to access the Flipsum Ipsum API. If we don’t specify which ipsum generator to use, the site will pick a random one for us.
  2. Create a Curl Handle ($ch)…
    1. Set some standard options.
    2. Execute the request.
    3. Store the result body (hopefully, a big string full of JSON data).
    4. Store the HTTP Response Code (hopefully 200=OK).
    5. Close the Curl Handle.
  3. If the API returns nothing (an empty string) then set the returned HTML to an error string.
  4. 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.
  5. 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.
  6. 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

ShortcodeDescription
[flipsum_ipsum]Let the API pick a random ipsum generator for us, and return the default number of paragraphs.
[flipsum_ipsum ipsum=’cafe’ debug=true]Grab some cafe 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.
Example usage of the flipsum_ipsum shortcode

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).
  • 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.

That’s it. Go forth and spread the gobbledygook πŸ˜ŽπŸ‘

Like This Tutorial?

loading

Let us know

7 thoughts on “Consume an External REST API from WordPress”

  1. Avatar

    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 !

    1. Avatar

      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

    1. Avatar

      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.

      1. Avatar

        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]

        1. Avatar

          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).

          1. Avatar

            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. πŸ˜‰

Leave a Comment

Your email address will not be published.