Seth
Seth

Reputation: 313

simple Google Drive access with Dart

I am trying to read a basic text file(no authorization needed) from google drive with Dart. The code below returns a 400 Error. If the API_KEY is removed then a 403 error. I can input the file id into the Google get file reference page and it will return the metadata correctly.

Any Ideas would be great. Thanks

final url = "https://www.googleapis.com/drive/v2/files/FILE?key={API_KEY}";

  var request = new HttpRequest();

  request.on.loadEnd.add( (Event e) 
  {
    if (request.status == 200) 
    {
      var data = JSON.parse(request.responseText);
      query("#file").text = data;
    } 
    else 
    {
      query("#file").text = "Error ${request.status}: ${request.statusText}";
    }
  });

  request.open("GET", url);
  request.send();

Upvotes: 2

Views: 1094

Answers (1)

adam-singer
adam-singer

Reputation: 4837

Your best bet is to use the drive_v2_api_client.

This can be done by setting up your google console apis with the following settings for localhost testing with DartEditor

Redirect URIs:  http://127.0.0.1:3030/oauth2callback
JavaScript origins: http://127.0.0.1:3030

Then use the dart drive package drive_v2_api_client by putting the following depenencies in your pubspec.yaml file.

dependencies:
  drive_v2_api_client:
    git: git://github.com/Scarygami/dart_drive_v2_api_client.git

This example allows the client to get the fileid after the client has authenticated with the client id.

import 'dart:html';
import 'dart:json';
import "package:drive_v2_api_client/drive_v2_api_client.dart" as drivelib;
import "package:google_oauth2_client/google_oauth2_client.dart";

final CLIENT_ID = "<YOUR CLIENT ID FROM CONSOLE API>";
final SCOPES = [drivelib.Drive.DRIVE_FILE_SCOPE];

void main() {
  var fileid = "1B_cGCNFjnK3dDriTMLsSS_zExfGFkQeewb3dcP4xSPg";
  var auth = new OAuth2(CLIENT_ID, SCOPES);
  var drive = new drivelib.Drive(auth);
  drive.makeAuthRequests = true;
  var loginButton = query("#login");
  var output = query("#text");

  loginButton.on.click.add((Event e) {
    auth.login().then((token) {
      output.appendHtml("Got Token ${token.type} ${token.data}<br><br>");

      drive.files.get(fileid)
      ..then((data) {
        output.appendHtml(data.toString());
      });

    });
  });
}

You can find all the source code to a working example here https://gist.github.com/4588427

Upvotes: 6

Related Questions