How to interact with an API using WordPress standard functions?

To interact with APIs is a very common thing in the Web Development, WordPress gives us the utility functions to interact with APIs. As you know to interact with an API requires good knowledge of cURL and many other things, WordPress takes this responsibility and wrap the inner stories into utility functions for you.

wp_remote_get is the function which gets the data for you from an API. All you have to do is just put the endpoint as argument and voila! It’s magic.

This function basically takes two arguments
1. $url – Resource to retrieve data from. This must be in a standard HTTP format
2. $args – OPTIONAL – You may pass an array of arguments in here to alter behavior and headers, such as cookies, follow redirects, etc.

Let’s make a call to github API and see what happens.

It will retrieve following data:

If you want to get the body part from the response, you can do like this:

If you want to get the response code, you can do like this:

The next part of the interaction is to post the values to an API. You can use this function wp_remote_post. This function takes first argument the URL on which the data has to be posted and second argument the data which has to be posted. The data should be in the key value pair array. As github doesn’t let us to post data so we just assume some URL.

The last important thing is to make any kind of call. Like you want to delete an object from database table using the API. It will be done like this:

This is the most easiest and interactive way to use an API using WordPress using standard functions. Feel free to comment below and let us know how this tutorial helps you.

0Shares

Related posts:

Leave a Reply

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