I am trying to create a Google Drive permission on a file via cURL in PHP but the Google Drive Create Permission API seems to throws Errors.
Here is Create File Permission API Sample Request Data
POST https://www.googleapis.com/drive/v3/files/FILE_ID/permissions
{
"requests": [
{
"type": "user",
"role": "commenter",
"emailAddress": "nancyxxxx@gmail.com"
}
]
}
I have tried two sample code below
Below is my sample code 1.
$access_token = 'xxxxxxxxxxxx';
$file_id ='file id goes here';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/drive/v3/files/$file_id/permissions");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer $access_token",
'Content-Type: application/x-www-form-urlencoded'
]);
//curl_setopt($ch, CURLOPT_POSTFIELDS, "{\n \"requests\": [\n {\n \"type\": \"anyone\",\n \"role\": \"reader\"\n\n }\n ]\n}");
//curl_setopt($ch, CURLOPT_POSTFIELDS, '{\n "requests": [\n {\n "type": "anyone",\n "role": "reader"\n\n }\n ]\n}');
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\n \"requests\": [\n {\n \"type\": \"anyone\",\n \"role\": \"reader\"\n\n }\n ]\n}");
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
Below is my sample code 2.
$access_token = 'xxxxxxxxxxxx';
$file_id ='file id goes here';
$headers = array(
"Authorization: Bearer $access_token",
"Content-Type: application/json"
);
$post_fields = '{
"requests": [
{
"type": "anyone",
"role": "reader"
}
]
}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/drive/v3/files/$file_id/permissions");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
$response = curl_exec($ch);
var_dump($response);
Here is the error both 2 code above throws
{ "error": { "code": 400, "message": "The permission type field is required.", "errors": [ { "message": "The permission type field is required.", "domain": "global", "reason": "required", "location": "permission.type", "locationType": "other" } ] } } string(323) "{ "error": { "code": 400, "message": "The permission type field is required.", "errors": [ { "message": "The permission type field is required.", "domain": "global", "reason": "required", "location": "permission.type", "locationType": "other" } ] } } "
It seems this permission request data below is not properly passed in the API or that Google Drive Rest API has some bugs. How can I proceed?
{
"requests": [
{
"type": "anyone",
"role": "reader"
}
]
}
In your script, please modify your request body in your "Below is my sample code 2." as follows and test it again.
$post_fields = '{
"requests": [
{
"type": "anyone",
"role": "reader"
}
]
}';
$post_fields = '{"type": "anyone", "role": "reader"}';