Simple WordPress HTTP API Tutorial

This article is to show beginners how to consume a Web Service and display results on your WordPress website. I say beginner, I mean a beginner in using Web Services or  a beginner in WordPress development. I also assume you have an idea of what web services are, what a Endpoint is, what is JSON, and what are RESTFUL services, You are someone just looking for advice on how to accomplish this in a WordPress website. Some knowledge of WordPress, some basic PHP and some basic knowledge of WordPress theme development and/or WordPress plugin development are suggested. If you are a brand new WordPress user that has never written any code this might not be the article for you. A person that has written some PHP code and has knowledge of the WordPress file structure should be able to understand this article.   To start, we need to take a look at the documentation for WordPress HTTP API.

WordPress HTTP API

The functions below are the ones you will use to retrieve an URL. Please be aware that these functions will return a WordPress WP_Error class on failure.

* wp_remote_get() – Retrieves a URL using the GET HTTP method.
* wp_remote_post() – Retrieves a URL using the POST HTTP method.
* wp_remote_head() – Retrieves a URL using the HEAD HTTP method.
* wp_remote_request() – Retrieves a URL using either the default GET or a custom HTTP method (should be caps) that you specify.

The other helper functions deal with retrieving different parts of the response and do the testing for WP_Error for you, these make usage of the API very simple and are the preferred method for processing response objects.

* wp_remote_retrieve_body() – Retrieves just the body from the response.
* wp_remote_retrieve_header() – Gives you a single HTTP header based on name from the response.
* wp_remote_retrieve_headers() – Returns all of the HTTP headers in an array for processing.
* wp_remote_retrieve_response_code() – Gives you the number for the HTTP response. This should be 200, but could be 4xx or even 3xx on failure.
* wp_remote_retrieve_response_message() – Returns the response message based on the response code.
So in this tutorial we will be using the wp_remote_get function to make the request to the web service API. After successfully connecting and getting back our JSON data, we will then use the wp_remote_retrieve_body function to grab just the body of the request and then parse the data. Normally, in basic PHP we would be using cURL but WordPress already has everything baked into the Core so we will be using those functions.

Lets get started. First what I am going to do is to create a new template in my present theme. So jump into your present theme’s folder and create a new file, I am calling mine rest.php. So now in my theme’s main folder I have a new file called rest.php. Now I am going to create the code so my new template will show up in my theme on the front end.  I am also going to name my new template Rest. So open up your new file called rest.php and place this in your new file.

<?php
/**
 * Template Name: Rest 
 *
 */
get_header(); 
?>
    <div id="content" class="full-width" style="padding-left: 100px;">
		<h3>WP_Http</h3>
		<?php

		/* our new code will go */

		?>        
	</div>
<?php 
get_footer(); 
?>

Now remember, my theme will be different than your theme. What I did was just copy one of my themes other template files and stripped everything out of the main content area, I left my get_header, get_footer and the main content div. OK, so now I have my new template file so I will be able to see the results on the front end.  Now, I will login into the admin side of my WP website, create a new page, and then choose the new ‘Rest’ template we just created.  Be sure and Save. Go to the front end, and you should see a new page that looks like your theme with just a heading of WP_Http (That is if you copied my code above. If you did not, then your page should be empty).

OK, now we are ready to get down to coding. So far we created a new template for our theme, created a new webpage and assigned this new template to the page. Displayed the new webpage in the front end that will be displaying our work.

We first need to code the Request part. I will be using the Github API.  For information on Github: Github

For more information on their APIs: Github API

We will be making a call using the Github API to get the names of my repositories I have on Github.

In order to do this example, you will need an account at Github. If you are one of those developers who keeps avoiding GIT and putting your code into repositories, maybe this tutorial will give you the push to start. OK, so after reading the Github API documentation, I will be using this Endpoint:

https://api.github.com/users/username/repos

Now time to start coding the request part:

$username = 'redsoxfan2499';
$url = 'https://api.github.com/users/'.$username.'/repos';
$request = wp_remote_get( $url );

if(is_wp_error($request)) {
	return false;
}

this code will be placed into my template page as such:

<main id="main" class="site-main" role="main">
	<?php if ( have_posts() ) : ?>
        
        	<?php /* Start the Loop */ ?>
        	<?php while ( have_posts() ) : the_post(); ?>
        
        	<?php
        		/** get page content **/
        		the_content();
        	?>
        
        	<?php endwhile; ?>
        
        	<?php endif; ?>
							
		<h3>WP_Http</h3>
		<p>This page is used for my WP HTTP API Tutorial.
			Check it out:   
		<a href="https://hyperdrivedesigns.com/simple-wp-http-api-tutorial/">WP HTTP API Tutorial</a>
		</p>
		<?php
			$username = 'redsoxfan2499';
			$url = 'https://api.github.com/users/'.$username.'/repos';
            $request = wp_remote_get( $url );
								
            if(is_wp_error($request)) 
            {
			    return false;
			}

			$body = wp_remote_retrieve_body($request);

			$data = json_decode($body);
								
			if(!empty($data)) {

				echo '<ul>';
				foreach( $data as $repo ) { 

					echo '<li>';
					echo $repo->name;
					echo '</li>';
				}
				echo '</ul>';
			}				
		?>
</main><!-- #main -->

$url is the Endpoint.
$username will be your username.

$request = wp_remote_get( $url );

$request: here we will use the WP HTTP API function wp_remote_get() and pass in our endpoint URL.

if(is_wp_error($request)) 
{
    return false;
}

Here we just do an error check, to make sure we have not hit an errors so far.

$body = wp_remote_retrieve_body($request);

$body: here we again use the WP HTTP API and use the wp_remote_retrieve_body function which produces only the body of the web services call response.

$data = json_decode($body);

$data: here we just use the php function json_decode so we can use the data in our php code. Time to check and see if we are successfully.

place the code below in your file after this line:

$data = json_decode($body);

This will basically dump out our json array, if we were successfully in connection to the API.

echo '<pre>';
print_r($data);
echo '</pre>';

I use the pre tags so it will print out the JSON array into a more readable formatted result.

you can just use this if you want:

print_r($data);

This section of code is just for testing. If you followed along you should see your array of information.

Now, either delete those lines of code or comment them out.

Now time to Parse our data.

if(!empty($data)) 
{
    echo '<ul>';
        foreach( $data as $repo ) 
        {
            echo '<li>';
              echo $repo->name;
            echo '</li>';
         }
    echo '</ul>';
}   

First we check and make sure that our $data array is not empty. If not then we start our list declaration.  Then using a foreach loop we loop through all instances of repositories that are in the array and print out the name of each repo, When complete, we close our list and exit.

Let’s break down our foreach loop. How did we come up with those names. Well $data is our array of data, and if you ran the print_r code you see how the data is arranged. The proper name is repositories. If we start to look down our array we can see that the proper name is name.

print-r-array

So we create the foreach loop as such:

foreach( $data as $repo ) 
{
     echo '<li>';
          echo $repo->name;
      echo '</li>';
}

So if we did everything correctly we now have a list of our Bitbucket repositories names. To see in real-time, check out the page here:

Demo Page

FINAL CODE:

<?php
/**
 * Template Name: Rest 
 *
 * This is the template that displays information from a web service.
 *
 * @package foundationwp
 */

get_header(); 
?>
	<div class="container">
        <div class="row">
        	<div id="primary" class="col-lg-12 col-md-12">
        		<main id="main" class="site-main" role="main">
							<?php if ( have_posts() ) : ?>
        
        			<?php /* Start the Loop */ ?>
        			<?php while ( have_posts() ) : the_post(); ?>
        
        				<?php
        				/** get page content **/
        				the_content();
        				?>
        
        			<?php endwhile; ?>
        
        		<?php endif; ?>
							
							<h3>WP_Http</h3>
							<p>
								This page is used for my WP HTTP API Tutorial.
								Check it out:   
								<a href="https://hyperdrivedesigns.com/simple-wp-http-api-tutorial/">
								WP HTTP API Tutorial
								</a>
							</p>
							<?php
								$username = 'redsoxfan2499';
								$url = 'https://api.github.com/users/'.$username.'/repos';
								$request = wp_remote_get( $url );
								if(is_wp_error($request)) {
									return false;
								}

								$body = wp_remote_retrieve_body($request);

								$data = json_decode($body);
								
								if(!empty($data)) {

									echo '<ul>';
									foreach( $data as $repo ) { 

										echo '<li>';
											echo $repo->name;
										echo '</li>';
									}
									echo '</ul>';
								}				
								?>
							<br/><br/>
							</main><!-- #main -->
        	</div><!-- #primary -->
				</div><!-- end row -->
    </div> <!-- .container -->
<?php get_footer(); ?>
Blog, PHP, Web Development, WordPress,