0

Trying to create a function in apex that will create Google Drive folders when creating a new record in Salesforce.

I have managed to authenticate and handle GET requests just fine. My issue is regarding the POST requests. The code below should create a folder with the label provided in the "title" parameter. The script executes and instead creates an extension-less file without a label.

public void getDriveFiles(HttpResponse authResponse) {
    http h = new Http();
    Httprequest req = new HttpRequest();
    HttpResponse res = new HttpResponse();      

    Map<String, Object> responseObject = (Map<String, Object>) JSON.deserializeUntyped(authResponse.getBody());

    req.setEndpoint('https://www.googleapis.com/upload/drive/v2/files');
    req.setMethod('POST');
    req.setHeader('Content-type', 'application/json');
    req.setHeader('Authorization', 'Bearer '+responseObject.get('access_token'));

    String jsonData = '{"title":"NewFolder", "mimeType":"application/vnd.google-apps.folder"}';
    req.setBody(jsonData);
    res = h.send(req);

    system.debug('Response ='+ res.getBody() +' '+ res.getStatusCode());
}

I have a feeling it's my request body but I have no idea what to do to fix it.

Output from Debug

pinoyyid
  • 21,499
  • 14
  • 64
  • 115

1 Answers1

0

You've used the wrong endpoint. Instead of the file endpoint, you're posting to the content endpoint.

So

req.setEndpoint('https://www.googleapis.com/upload/drive/v2/files');

should be (for the v2 API)

req.setEndpoint('https://www.googleapis.com/drive/v2/files');

or (for the v3 API)

req.setEndpoint('https://www.googleapis.com/drive/v3/files');

If you use v3 (which you probably should), your json should change thus

String jsonData = '{"name":"NewFolder", "mimeType":"application/vnd.google-apps.folder"}';

pinoyyid
  • 21,499
  • 14
  • 64
  • 115