Set GOOGLE_APPLICATION_CREDENTIALS in Python project to use Google API

Liam picture Liam · Aug 4, 2017 · Viewed 70.6k times · Source

I am a programming beginner and thing I'm trying to learn how to use google API with Python.

I have:

  1. created a project on Google Cloud and enabled the API that I want to use, Natural Language API.
  2. created a credential and downloaded the credential JSON file, saved it as apikey.JSON
  3. In the Terminal I have ran this command: export GOOGLE_APPLICATION_CREDENTIALS=apikey.JSON, no error popped.

However, even when I ran the simplest of codes for this, I have errors which says the credential variable is not found.

I am not sure what to do now. Please kindly help.

This is my code:

from google.cloud import language

def sentiment_text(text):

    client = language.LanguageServiceClient()

    sentiment = client.analyze_sentiment(text).document_sentiment

    print('Score: {}'.format(sentiment.score))
    print('Magnitude: {}'.format(sentiment.magnitude))

sampletxt='Python is great'

sentiment_text(sampletxt)

And I have errors:

> Traceback (most recent call last):   File
> "/Users/YELI1/Downloads/googlecloud/sentimentanalysis/simple.py", line
> 21, in <module>
>     sentiment_text(sampletxt)
> 
>   File
> "/Users/YELI1/Downloads/googlecloud/sentimentanalysis/simple.py", line
> 5, in sentiment_text
>     client = language.LanguageServiceClient()
> 
>   File
> "/usr/local/lib/python3.6/site-packages/google/cloud/gapic/language/v1/language_service_client.py",
> line 147, in __init__
>     ssl_credentials=ssl_credentials)
> 
>   File "/usr/local/lib/python3.6/site-packages/google/gax/grpc.py",
> line 106, in create_stub
> 
>     credentials = _grpc_google_auth.get_default_credentials(scopes)   File
> "/usr/local/lib/python3.6/site-packages/google/gax/_grpc_google_auth.py",
> line 62, in get_default_credentials
>     credentials, _ = google.auth.default(scopes=scopes)
> 
>   File
> "/usr/local/lib/python3.6/site-packages/google/auth/_default.py", line
> 282, in default
> 
>     raise exceptions.DefaultCredentialsError(_HELP_MESSAGE) google.auth.exceptions.DefaultCredentialsError: Could not
> automatically determine credentials. Please set
> GOOGLE_APPLICATION_CREDENTIALS or explicitly create credential and
> re-run the application. For more information, please see
> https://developers.google.com/accounts/docs/application-default-credentials.

The value is not in the environment

import os 
print(os.environ['GOOGLE_APPLICATION_CREDENTIALS']) 
   File "/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework‌​/Versions/3.6/lib/py‌​thon3.6/os.py", line 669, in getitem  
raise KeyError(key) from None KeyError: 'GOOGLE_APPLICATION_CREDENTIALS'

Answer

Marius picture Marius · Oct 9, 2017

If you're working on a jupyter notebook and want to set GOOGLE_APPLICATION_CREDENTIALS environment variable in Python code :

import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="/path/to/file.json"