Authorizing a python script to access the GData API without the OAuth2 user flow
Question: I'm writing a small python script that will retrieve a list of my Google
Contacts (using the [Google Contacts
API](https://developers.google.com/google-apps/contacts/v3/)) and will
randomly suggest one person for me to contact (good way to automate keeping in
touch with friends!)

This is just a standalone script that I plan to schedule on a cron job. The
problem is that Google seems to require OAuth2 style authentication, where the
user (me) has to approve the access and then the app receives an authorization
token I can then use to query the user's (my) contacts.

Since I'm only accessing my own data, is there a way to "pre-authorize"
myself? Ideally I'd love to be able to retrieve some authorization token and
then I'd run the script and pass that token as an environment variable

    
    
    AUTH_TOKEN=12345 python my_script.py
    

That way it doesn't require user input/interaction to authorize it one time.


Answer: The implementation you're describing invokes the full "three-legged" OAuth
handshake, which requires explicit user consent. If you don't need user
consent, you can instead utilize "two-legged" OAuth via a [Google service
account](https://cloud.google.com/compute/docs/access/create-enable-service-
accounts-for-instances), which is tied to an _application_ , rather than a
_user_. Once you've [granted
permission](https://console.developers.google.com/permissions/serviceaccounts)
to your service account to access your contacts, you can use the
[`oauth2client`](https://github.com/google/oauth2client)
[`ServiceAccountCredentials`
class](https://github.com/google/oauth2client/blob/bb2386ea51b330765b7c44461465bdceb0be09b4/oauth2client/service_account.py#L43-L542)
to directly access GData without requiring user consent.

Here's the two-legged authentication example from the [Google service account
documentation](https://developers.google.com/api-client-
library/python/auth/service-accounts):

    
    
    import json
    
    from httplib2 import Http
    
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    scopes = ['https://www.googleapis.com/auth/sqlservice.admin']
    
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
            'service-account.json', scopes)
    
    sqladmin = build('sqladmin', 'v1beta3', credentials=credentials)
    response = sqladmin.instances().list(project='examinable-example-123').execute()
    
    print response
    

