Reputation: 8880
This question follows on from my previous one. I thought I would perform a basic token authentication by calling the get_space_usage API function. I tried
$headers = array("Authorization: Bearer token",
"Content-Type:application/json");
$ch = curl_init('https://api.dropboxapi.com/2/users/get_space_usage/');
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
The documentation does not in fact indicate that it is necessary to provide a Content-Type header. However, without that header I get the message
Bad HTTP "Content-Type" header: "application/x-www-form-urlencoded". Expecting one of "application/json",...
Putting in that header but supplying no POST fields produces another error
request body: could not decode input as JSON
Just providing some dummy post data curl_setopt($ch,CURL_POSTFIELDS,json_encode(array('a'=>1)));
does not do anything to remedy the situation. What am I doing wrong?
Upvotes: 0
Views: 889
Reputation: 16930
The documentation doesn't indicate that a Content-Type
header is expected, because, since this endpoint doesn't take any parameters, no body is expected, and so there's no content to describe via a Content-Type
header. Here's a working command line curl example, per the documentation:
curl -X POST https://api.dropboxapi.com/2/users/get_space_usage \
--header "Authorization: Bearer <ACCESS_TOKEN>"
Translating this to curl in PHP would involve making sure PHP also doesn't send up a Content-Type
header. By default though, it apparently sends "application/x-www-form-urlencoded", but that isn't accepted by the API. If you do set a "application/json", the API will attempt to interpret the body as such, but won't be able to do so, since it isn't valid JSON, and so fails accordingly.
It's apparently not easy (or maybe not possible) to omit the Content-Type
header with curl in PHP, so the alternative is to set "application/json", but supply valid JSON, such as "null". Here's a modified version of your code that does so:
<?php
$headers = array("Authorization: Bearer <ACCESS_TOKEN>",
"Content-Type: application/json");
$ch = curl_init('https://api.dropboxapi.com/2/users/get_space_usage');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "null");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>
Upvotes: 2