Set GOOGLE_APPLICATION_CREDENTIALS in Python project to use Google API
PythonGoogle ApiPython Problem Overview
I am a programming beginner and thing I'm trying to learn how to use google API with Python
.
I have:
- created a project on Google Cloud and enabled the API that I want to use,
Natural Language API
. - created a credential and downloaded the credential JSON file, saved it as
apikey.JSON
- 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/python3.6/os.py", line 669, in getitem
raise KeyError(key) from None KeyError: 'GOOGLE_APPLICATION_CREDENTIALS'
Python Solutions
Solution 1 - Python
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"
Solution 2 - Python
I know that this post was answered but the following is a cleaner way to specify the GOOGLE_APPLICATION_CREDENTIALS
variable.
client = language.LanguageServiceClient.from_service_account_json("/path/to/file.json")
Solution 3 - Python
There is 1 more simpler way of making it working by explicity mentioning Credentials and passing them to client as shown below.
import os
from google.oauth2 import service_account
credentials = service_account.Credentials.from_service_account_file("your-json-path-with-filename.json")
client = language.LanguageServiceClient(credentials=credentials)
Solution 4 - Python
In case you have the credentials in memory (environment variable for example), and you don't want to create a file especially for it:
from google.cloud import storage
from google.oauth2 import service_account
gcp_json_credentials_dict = json.loads(gcp_credentials_string)
credentials = service_account.Credentials.from_service_account_info(gcp_json_credentials_dict)
client = storage.Client(project=gcp_json_credentials_dict['project_id'], credentials=credentials)
Using python3.7 and google-cloud-storage==1.35.0
Solution 5 - Python
Another way to test this is to go into the terminal and type:
# Linux/Unix
set | grep GOOGLE_APPLICATION_CREDENTIALS
or
# Windows:
set | Select-String -Pattern GOOGLE_APPLICATION_CREDENTIALS
This will show you the environment variable and the path where it is located. If this returns nothing then you have not set the variable or you may have the wrong path set