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 generates ipsum copy text. Basically, it’s a free gobbledygook generator 😎 😎 😎

To 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 take the following parameters:

  • ipsum (Type of Ipsum): The name of the ipsum generator to use, because Flipsum Ipsum lets us choose what sort of gobbledygook we want.
  • paragraphs (Number of Paragraphs): How much 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.
if (!defined('WPINC')) {
	die;
}

const FIS_DEFAULT_IPSUM_PARAGRAPHS = 5;

function do_shortcode_flipsum_ipsum($atts) {
	// Parse the shortcode's options.
	$args = shortcode_atts(
		array(
			'ipsum' => '',
			'paragraphs' => FIS_DEFAULT_IPSUM_PARAGRAPHS,
			'debug' => 0,
		),
		$atts
	);

	$html = '';

	$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']);
	}

	if (empty($json_response = file_get_contents($url))) {
		// No data returned from the server.
		$html .= sprintf('<p><strong>ERROR:</strong> No respone from the server.</p>');
	} elseif (boolval($args['debug'])) {
		// Render the raw JSON response, so we can see what the server has sent
		// back to us.
		$html .= sprintf('<pre>%s</pre>', $json_response);
	} elseif (empty($ipsum_paragraphs = json_decode($json_response, true))) {
		// There was a problem converting the server response into an array.
		$html .= sprintf(
			'<p><strong>ERROR:</strong></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. Call the standard PHP function file_get_contents() to query the API with our URL.
  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>.

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, so we can see what the Flipsum Ipsum API has really generated.
[flipsum_ipsum ipsum=’recipe’ paragraphs=10]Generated 10 paragraphs of tasty gobbledygook and render it normally, in paragraph HTML elements.

In the block editor, create a shortcode block, enter [flipsum_ipsum], save your content and the view it. Boom! Instant nonsense for your website!

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

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 our transient.
    • Otherwise…
      • go and 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.

Better Error Handling

The nature of fetching data from another server, which could be on a different continent, means that you might not always get a response. Instead of using the standard file_get_contents() function, you can use PHP cURL instead. This is more complex to set up, but you can do loads more with it, including catching error codes properly.

That’s it. Go forth and spread the gobbledygook 😎👍

Leave a Comment

Your email address will not be published. Required fields are marked *