I’m currently working on a solution with an API. I’m trying to make a curl request but for some reason, the response always returns with a 0 at the end. I’m not sure if there’s a particular header I’m missing, but the documentation for the API itself only mentions using these particular headers. The code I’ve got here just needs to get an auth token from the API itself so that I can begin using that for operations with the API. For whatever reason, the API doesn’t include an API Key. But that aside, here is my code:
class API_Connection {
public $auth_token;
public function __construct() {
$api_settings = get_option('api_settings');
$url = 'https://api.example.com/api-token-auth/';
$data = array(
'username' => $geek_api_settings['username'],
'password' => $geek_api_settings['password'],
);
// get the token
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => array('Content-Type: application/json'),
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($data),
));
$result = curl_exec($curl);
$auth_token = $result;
curl_close($curl);
return $auth_token;
}
public function get_auth_token() {
return $this->auth_token;
}
}
When I get my response, which is spat out as a json string, it always includes a 0 at the end of the response. Currently the API is throttling me, so an example of the response I’m getting is {"detail":"Request was throttled. Expected available in 86400 seconds.","wait":86400}0
.
To include the JS, just for prosperities sake, the JS is the following:
$('#curlAPIToken').on('click', function(e) {
e.preventDefault();
$.ajax({
url: api_settings.ajax_url,
data: {
action: 'curl_auth_token'
},
method: 'POST',
success: function(response) {
console.log(response);
}
})
});
Just to clarify, the action curl_auth_token
is just a very simple function – instantiate the class and then call get_auth_token()
after that.
I’ve been searching around and can’t figure out why the 0 comes at the end. I know I’ve seen it before and I’ve solved it before, but I’m more used to React solutions and I can’t seem to solve it on this PHP front, and haven’t found any threads with a solution that’s worked for me. How do I get rid of the 0 at the end of the response? And yes, I’ve tried rtrim()
, that hasn’t seemed to work either.