Search code examples
pythongoogle-drive-api

How to authenticate with a service account or OAuth consent automatically for Google Drive API?


I am trying to make a simple POST request as the following :

POST https://www.googleapis.com/drive/v3/changes/watch
Authorization: Bearer auth_token_for_current_user
Content-Type: application/json

{
  "id": "4ba78bf0-6a47-11e2-bcfd-0800200c9a77", // Your channel ID.
  "type": "web_hook",
  "address": "https://www.example.com/notifications", // Your receiving URL.
  ...
  "token": "target=myApp-myChangesChannelDest", // (Optional) Your changes channel token.
  "expiration": 1426325213000 // (Optional) Your requested channel expiration date and time.
}

From this guide and i need the auth_token_for_current_user value from authentication.

I need to make this request from python, but i am unable to find a documentation on how to use a client library or getting the authenticated token to use a POST request with the requests package.

My question is how to authenticate for this API ? I prefer an automated solution than an OAuth consent screen that i should fill manually.

Thanks in advance


Solution

  • Try something like this.

    auth with service account

    def build_service(credentials, scope, delegated_user):
    
        credentials = ServiceAccountCredentials.from_json_keyfile_name(
            credentials,
            scopes=scope,
        )
        credentials = credentials.create_delegated(delegated_user)
        try:
            return build('drive', 'v3', credentials=credentials)
        except HttpError as error:
            # TODO(developer) - any errors returned.
            print(f'An error occurred: {error}')
    

    Request

    def get_watch(drive_service, token):
    channel_id = str(uuid.uuid4()),
    
    body = {
        "id": channel_id,
        "type": "web_hook",
        "address": "https://www.example.com/notifications"
    }
    return     drive_service.changes().watch(body=body,pageToken=token).execute()
    

    which gives you the following results.

    {'kind': 'api#channel', 'id': 'REDACTED', 'resourceId': 'REDACTED', 'resourceUri': 'https://www.googleapis.com/drive/v3/changes?alt=json&pageToken=45', 'expiration': '1698691440000'}

    Note: PageToken

    Make sure you created the page token first

    def get_start_page_token(drive_service):
        response = drive_service.changes().getStartPageToken(
            driveId = DRIVE_ID,
            supportsAllDrives = True
            ).execute()
        token = response.get("startPageToken")
        print(F'Start token: {token}')
        return token
    

    stop watch

    def stop_watch(drive_service, channel_id,resource_id):
    
    
        body = {
            "id": channel_id,
            "resourceId" : resource_id
        }
        return drive_service.channels().stop(body=body).execute()