Students Save 30%! Learn & create with unlimited courses & creative assets Students Save 30%! Save Now
Advertisement
  1. Web Design
  2. WordPress Plugins
Webdesign

How to Incorporate External APIs in Your WordPress Theme or Plugin

by
Length:LongLanguages:

APIs can help you to add functionality to your WordPress plugins and themes. In this tutorial I will show you how to use any API (whether it be from Flickr, Google, Twitter, and so on) with WordPress. You will learn how to connect, collect data, store and render–everything you need to know to extend your plugin or theme with new functionality!

We will use Flickr as an example, creating a simple widget that displays the latest Flickr images in order of username.  

Wait, What’s an API?

“API” stands for Application Programming Interface; an intermediary between applications, allowing them to communicate, sending information back and forth in real time. We’ll be using a Web API, one which uses HTTP to fetch data from a remote location on the internet somewhere.

“APIs are used by software applications in much the same way that interfaces for apps and other software are used by humans.” – David Berlind, ProgrammableWeb

If you want to get an even clearer idea of what APIs are before we dive into our tutorial, here are some more resources to help you:

API WordPress Plugins on Envato Market

If you’d like to see what other WordPress developers are building with APIs, check out this collection of plugins on Envato Market–plenty of API goodness to get stuck into!

api wordpress plugins on codecanyon
API WordPress plugins on Envato Market

1. Organize Your Working Environment

Let’s begin by organizing our working environment. Start by downloading the Postman app, which provides an API development environment that makes it easy to connect, test, and develop any API. For individuals and small teams it’s completely free.

postman app

We’re going to build a widget in a simple WordPress plugin, so make sure you have WordPress installed.

2. Code the Plugin Basics

To start let’s create a simple plugin called flickr-widget. Create a folder with that name and create a flickr-widget.php file in it. At the top of the file place the following code (feel free to change the Author and URIs with your own details):

Note: this is rudimentary plugin, so I won’t load a language file or create any additional parameters. 

Put the freshly created plugin folder inside your WordPress install: wp-content > plugins. You can now activate it from within the WordPress admin dashboard > plugins. You won’t see any changes to your WordPress because we haven’t actually added any functional code.

A Note on Using APIs

Before we go any further, let me quickly mention API use. Any service whose API you want to use will have documentation; I highly recommend you look closely at it. You can use APIs with all kinds of development languages and often get data back in any format you need: PHP, JSON, Java etc. Good documentation will contain detailed information on how to connect to the API, with instructions for each language, and also the main API endpoints (an endpoint is one end of a communication channel).

Web APIs are typically categorized as being either SOAP or REST. SOAP relies solely on XML to provide messaging services, while REST offers a more lightweight method, using URLs in most cases to receive or send information. In our example we will use a REST API.

3. Configure and Test API with Postman

So, here is our plan:

  • Configure and test API with Postman
  • Connect, collect, and format data from Flickr REST API
  • Cache the data with WordPress transients

Let’s refer to the Flickr API documentation. Under the Request Formats section you have REST, XML-RPC, SOAP. We need the REST. Click it and you will see an example of a general Flickr REST API Endpoint: https://www.flickr.com/services/rest/.

With the Flickr REST API we can GET, POST, and DELETE any Flickr data we want. Copy the sample endpoint and paste it into Postman (make sure your request type is set to GET). 

Click the Send button and... error! 

postman error

The sample request included the compulsory Flickr API method, but we didn’t specify the API key that is required in order to connect (keys are used to track and control how an API is being used, for example to prevent malicious use or abuse of the API as defined perhaps by terms of service).

4. Get API Key

Having established that we need an API key, let’s go and get one. In order to create one you will first need to have a Flickr/Yahoo account. Once you’ve entered the API dashboard click on the link create your first:

After that click on the Request an API Key. Many API providers have their own specific terms on API usage. Some limit access, others have light and pro versions, or commercial and non-commercial. Sometimes API keys are provided after manual approval; it depends entirely on the API provider. I have chosen Flickr, because it has simple API requirements. For example, Twitter requires a detailed description of the app you want to build before providing an API key, and this is then reviewed by the review team. 

That said, click on the Apply for a non-commercial key button and provide some basic info on the app name.

app details

Once you’ve submitted the request you will get the API key (which identifies you) and secret code (which proves you are who you say you are) immediately. Keep these details safe!

5. Set the Request Parameters

Now we will need a method to request data. From the Flickr API documentation we can see that Flickr has tons to choose from. Some methods, like image posting, or deleting, require authentication. Flickr uses OAuth for this; an open, simple, and secure protocol that enables applications to authenticate users and interact with API providers on their behalf. The end user’s information is securely transferred without revealing the identity of the user.

For now, we’ll use simple methods that don’t require oAuth. Click on flickr.photos.getRecent method to see what’s required. This method does not need authentication, but it does take several arguments: api_key (required), extras, per_page, page. Let’s make a simple request in Postman using our parameters:

  • API general endpoint - https://flickr.com/services/rest
  • API key - f49df4a290d8f224ecd56536af51FF77 (this is a sample API key which you’ll need to replace with your own)
  • Method - flickr.photos.getRecent

It will look like this:

This will return the list of recent public images from Flickr in XML format. 

XML format
XML format

I always set data format to auto to let Postman decide what format the data is. With Postman you have several data format options: JSON (my favorite), XML, HTML and Text. Flickr returns data in XML format, but this is not a problem for us, as we can add an additional parameter to get data in JSON &format=json:

JSON format
JSON format

6. Connect, Collect, and Format Data

Now we know how to request data using the REST API, let’s build our WordPress Flickr widget. In the plugin’s main PHP file paste the widget code. I won’t cover the specifics of WordPress widget creation in this tutorial as our focus is different. We have a learning guide Introduction to Creating Your First WordPress Widget by Rachel McCollin which should get you up to speed if you need it.

In the WordPress admin navigate to Appearance > Widgets and add the “Photos from Flickr” widget to a widget area. Now if you go to the front-end you will see the widget title, but no results just yet. 

Back in our plugin PHP file, here we render the widget output itself. We have our API key, and the method, and the format we’re looking for. Now we will need to make sure the Flickr user id is provided, and the number of photos the user wants to fetch. These are are gathered from the widget settings.

Note: to get a Flickr user id use this service. I am using envato as the username, and the id is 52617155@N08. Enter the following code inside IF statement:

At this point we can knit together the final REST API endpoint url with all the arguments we’ve collected. 

Now we’ll make an API request with the file_get_contents() php function:

If you now go to the front-end you will something like this outputted:

Our request was successful and returned useful data, so now let’s decode and format it. We’ll begin by cleaning up the JSON string–first by removing the wrapper (jsonFlickrApi({...});) with a str_replace. Then we’ll decode the JSON url:

Now if we print our results we will see an associative array with data. When we’re ready we can loop through that array and create the data output structure. But first, take a closer look at the small parameter stat. According to the Flickr documentation this indicates the response status. So, before creating the structure of the widget let’s use this status to make sure we have the correct data. Add an IF statement: 

Create an empty array before the IF statement. This array will then be used to contain the collected data:

Your foreach loop should now look like this:

Here we loop through each photo object in the photos array from our response data. Our widget needs the following information to function properly:

  • Image absolute URL
  • Image link to Flickr
  • Image description/alt text

Examine this page and you will understand why I used the given structure. Here you will find the detailed information on how to create the image path and image link. 

Create Widget Output

Now our $response_results array contains the exact data we need to create our widget:

We begin by making sure our response is not empty. After that we create an unordered list, storing it in $output, then loop through each image, adding a wrapper link, all the other details, and finally outputting the whole thing with echo;.

If you now go to the site front-end you will see a list of images! 

Flickr images

Let’s add some basic styling with CSS to make it look better.

Create an empty flickr-widget.css file in the root plugin folder. In the top of the plugin file paste the following code:

Then, inside the IF statement at the very top add the code:

Inside the css file add basic styling:

Now it looks much better!

Bonus: Cache the Data with WordPress Transients

At this stage we’ve finished the widget, but there is one more little thing that will take our development to the next level: caching. 

Any API request uses your site’s resources and increases load time. Each browser reload will send an API request, which could be multiple users at the same time. What if for some reason your API provider host is down? Your site will suffer load difficulties. The solution is to cache the results and update at a give time interval. So the first time a user visits our page the API request will be sent, but the next time, or with another user, we won’t need to send an API request but instead fetch the results from our site cache. 

Let’s modify the widget code to cache results:

I won’t describe what the transient is and how it works, just what it does. Any time the widget is rendered we first check if the transient is in place; if it is present we fetch results from transient, but if not, we make an API request. And each two hours our transient expires, in order to keep our latest Flickr images actual and up to date. 

With the WordPress plugin Transients Manager you can even see what your cached Flickr API request results look like:

Transients Manager plugin

And the final touch here is to remove transient for every widget update. For example, if you want to change the number of images displayed, or change the username, you’d need to make a new API request. This can be done with the widget_update_callback WordPress filter, or the widget class public function update:

Conclusion

That was a lot of effort, but now you know how to work with WordPress and APIs! If you enjoyed this post and would like to see additional tutorials on APIs or transients, let me know in the comments section.

To grab the widget sample files head over to the GitHub repository.

Advertisement
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.