WordPress is a fully featured framework with high user friendly nature and variable option of customization. There is also an availability of rss feed but when we need to built our own customized API, it is a troubling matter. I assume you are already familiar with WordPress hooks, action and filter. In this tutorial, we are going to learn about how to built our own custom API and feed the data in well known JSON format.
To create an API, the three things are required:
To create an API, the three things are required:
- URI : Path for accessing API
- Custom Variable : Required if values is being sent using GET Method
- Query handler : Handling the Request
Step 1: Generating URI for the API
URI is the method of accessing API defined for particular task and addition data is send to determine the action. WordPress has a convenient way to define URL. It has a built in action for rewrite rule.add_rewrite_rule($regex, $redirect, $after);$regex- It is used to define the URI of API like what is to be sent and a what the receiver can expect. Eg: www.example.com/values/?[0-9]
- $redirect- It actually takes the GET data and array-matches[] is used to get the values. Eg: www.example.com/values/?id=matches[1]
- $after- It has two option top and bottom. "top" does not require checking of existing WordPress rule while "bottom" requires.
Step 2: Registering Custom Variables
Custom variables are the one which is sent through the URI as like values and id in above cases. In order to use custom variable, they must be registered so that WordPress can recognize them and we can use or get them anywhere we need.
add_filter( 'query_vars', 'function_name');Now, we have two variables "values" and "id" which can be passed through the URI and it can be accessed as
function function_name($vars){
$vars[]="values";
$vars[]="id";
return $vars;
}
global $wp;
$wp->query_vars['id'];
$wp->query_vars['values'];
Step 3: Sniffing Request and Handling Queries
We have all the necessary backbone for API but we need one more thing i.e. Query Handler. When a URI is entered in the address bar, we need to get that address and check whether that address is for our API or not, if yes we need to perform our task otherwise let it go. WordPress has a beautiful hook for it and check if our variable is present or not.
add_action('parse_request', 'sniff_requests');
function sniff_requests(){
global $wp;
if (!empty($wp->query_vars['values']) AND !empty($wp->query_vars['id']) ) {
$this->handle_request();
exit;
}
}
If the URI has our function, we can run our function(handle_request) otherwise we let WordPress handle it.
Thanks for sharing the best information and suggestions, If you are looking for the best Api Development Services, then Metricoid Technology Solutions. Highly energetic blog, I’d love to find out some additional information.
ReplyDelete