How to perform an API request on WordPress

To perform an API request to ClickMeter servers, it could be useful to create a wrapping function  around the one offered by WordPress, for generics remote requests: wp_remote_post


function api_request($endpoint, $method, $body, $api_key, $associative = true){

$args = array(

 'method' => $method,

 'timeout' => 120,

 'redirection' => 5,

 'httpversion' => '1.0',

 'blocking' => true,

 'headers' => array(

  'Content-Type' => 'application/json',

  'X-Clickmeter-Authkey' => $api_key

 ) ,

 'body' => $body


$response = wp_remote_post($endpoint, $args);

if ($response['response']['code'] != 200) {

 echo "Error occured!";

 $response_body = $response['body'];


else {

 $response_body = $response['body'];

 return json_decode($response_body, $associative);





$output = api_request('' . $datapoint_id, 'GET', null, $api_key);


  • $endpoint: specify where the request will be forwarded, for instance

  • $method: specify the method for the request (GET,POST,PUT,DELETE).

  • $body: specify the body of the request, null if method is GET or DELETE. It have to be encoded in JSON format to be understood by ClickMeter’s APIs.

  • $api_key: specify user’s API Key, necessary to perform any kind of request

  • $associative: specify if return value will be an associative array or not.

Return value:

ClickMeter APIs produce different types of response codes (200, 403, 500..). In any case, a response body will be returned as a JSON object, containing data or error messages. The standard PHP method json_decode can be used to transform into a common array.

Have more questions? Submit a request


Article is closed for comments.