How to Use the WordPress HTTP API
REST APIs are becoming increasingly popular with developers, and for good reason. They provide a simple, uniform and understandable interface to third-party services like Twitter, MailChimp, and GitHub.
With the WordPress API on its way (and already available via a plugin), it’s prime time to learn all about the already existing HTTP API in WordPress.
In this article, I’ll show you what it is, how it works and what you can use it for.
What’s the HTTP API?
Not very surprisingly, the HTTP API is a way to send and receive messages using HTTP – the language of the web. Your browser sends and receives HTTP messages all the time which is how you receive any web page. Through REST APIs, HTTP messages allow you to do more elaborate things like update a post, delete a user or publish a new recipe on your website.
This is why the new WordPress API is so important, it allows for the true de-coupling of the user-facing side of your application from the WordPress core code. In order to use it, you’ll need to be familiar with sending HTTP requests and receiving responses, which is what the HTTP API is all about.
There are many ways to send HTTP requests, the HTTP API provides a unified interface using a handful of helper functions which we’ll take a look at below.
HTTP Methods and Resources
HTTP is centered around methods (sometimes called verbs) and resources. The resources define what item you want to take a specific action on, the method defines the type of action you want to take.
A resource is a URL that points to an object on the web, for example, a post. There are a number of methods, the most important of which are GET, POST, PUT and DELETE.
You already have a lot of experience with GET since this is what you use to retrieve a resource. When viewing this article your browser made a GET request to
https://wpmudev.com/blog/using-the-wordpress-http-api/. PUT requests are used to modify resources, POST requests are used to create them and DELETE requests are used for deleting them.
If WPMU DEV had a REST API in place, an admin could send a DELETE request
https://wpmudev.com/blog/wordpress-http-api/ to trash a post. This could be pretty useful for large websites with their own management mobile apps.
A Simple Request
Let’s send a simple GET request to test the waters. This can be done using the
wp_remote_get() function, which takes two parameters. The first parameter is the full URL of the resource, the second is an array of options we can use to specify details.
This will retrieve the Google home page. If you dump the value of
$test – which is the response Google sends back – you should see all the elements involved.
The headers contain additional information about each message. Some REST APIs will ask you to send specific information in headers when making requests.
The response contains the status code and phrase which you may be familiar with from 404 errors, 500 server errors or 301 and 302 redirects. W3.org has all HTTP error codes defined and described, a good resource if you need to figure out what an error means.
The body contains the response and is generally where you’ll need to look for the good stuff. In this case, we receive HTML – the full HTML of Google’s home page. When working with REST APIs it is standard practice to receive a JSON encoded string of data. Occasionally APIs will ask you to add a specific string to the body when making requests as well.
The cookies section will contain any cookies received with the message.
As you can see, sending a request with the HTTP API is very simple. What makes working with HTTP a bit difficult is that REST APIs can be very sensitive to correctly entered data (which is a good thing) so if you skip a line when reading API docs you could end up with something that doesn’t work.
Working With APIs
I think it’s a safe bet that most of you will use HTTP to interact with REST APIs around the web, in which case you’ll need to use the second parameter to specify the number of things, authenticate yourself and avoid some common pitfalls. Let’s begin with a simple example – retrieving pins from a Pinterest board.
All proper APIs require authentication, but we’ll cheat a bit here by using the Pinterest token generator. Once you authorize it you’ll get an access token you can use. Let’s make a request and list some pins!
I pasted the code above into the
content-page.php file in Twenty Fifteen to test how it works. The result is a page that displays recent pins from a Pinterest board all about Home Offices.
Make sure to use your own token in the first line. Line two decodes the body of the response so we can use the array. The pins are stored in
$pins['data'] so I just looped through the items and showed them in a simple list.
Authentication is usually where many people trip up because it requires at least one more step and usually some headers as well.
Let’s look at Twitter’s API as an example, more specifically application only authentications, which you can use to authenticate your application with Twitter.
Read the Documentation
The first place where you can mess up is not reading the documentation thoroughly. If you’re a seasoned veteran of REST API’s you may jump straight to the Authentication section and just skim through it.
If you do this, you may skip a line hidden in a list which says:
The body of the request must be grant_type=client_credentials.
Omitting this will result in complete failure, even though everything else is perfectly implemented. To stop yourself from second-guessing your code, make sure to read everything thoroughly.
Add Headers and Other Parameters
After following the directions in the documentation to the letter I’ve constructed a POST request, which should generate an access token for me. Here’s how it looks.
The first step is to URL encode the access token and secret (neither are actual access tokens, sorry). I’ve added two headers, one is an authorization header, which contains the access credentials. The second is a content type header, which Twitter instructed me to add.
The body has also been filled out as I’ve indicated above and the HTTP version has also been added, Twitter asks for this as well. The response, among other things, will contain your final access token in the body section. You’ll need this token in all other subsequent calls to the API.
Caching the Access Token
The token is valid for quite some time, requesting it on each page load or any time your application needs to do something is a waste and will get you rate limited. In WordPress, you can use a transient to store the value and use the transient in each subsequent call.
This request to the Twitter API should result in five of my followers being listed (simple list of IDs). I retrieve my token from a transient, and if it doesn’t exist I use the
get_twitter_access-token() function to grab one. This function should also add the access token to the transient so next time it will be retrieved from there.
Note that this is not a great way to do things but it shows the logic well. I a simple scenario I would simply use the
get_twitter_access_token() function, which would take care of all the ifs.
HTTP API Helper Functions
Now that we’ve got a good grasp on what this is all for, let’s look at all the functions the WordPress HTTP API helps you out with. There are four functions to make requests with:
These are pretty self-explanatory, the last one,
wp_remote_request(), is a generalized function you can use with any HTTP verb.
Five further functions allow you to retrieve responses with ease using standardized functions instead of mucking about with array keys.
Very easy to understand yet again. When possible, use these functions instead of going into the response arrays manually. This will help other developers follow along and use hooks if they become available in the future.
Working With APIs
As you can see, interacting with REST APIs is extremely easy using the WordPress HTTP API and some other WordPress functions like transients. I highly recommend giving all this a try because WordPress development is confidently heading towards an API driven world – jump on now before it’s too late!
If you would like more information about HTTP in general, I can highly recommend James Marshall’s Guide, which talks at length about HTTP verbs, resources, errors and other such things.
If you have any questions about using the HTTP API or have ideas for how you could use it, let us know in the comments below.