I have a JSON file with BigQuery credentials. To connect with Python to BigQuery I need to give the file path in service_account.
JavaScript
x
6
1
from google.cloud import bigquery
2
from google.oauth2 import service_account
3
4
cred = service_account.Credentials.from_service_account_file(filename="credentials.json")
5
client = bigquery.Client(credentials=cred, project=cred.project_id)
6
The JSON looks like a dictionary:
JavaScript
1
13
13
1
{
2
"type": "xxxx",
3
"project_id": "xxx",
4
"private_key_id": "xxx",
5
"private_key": "xxxxxx",
6
"client_email": "xxxx@xxxxx.iam.gserviceaccount.com",
7
"client_id": "xxxxxxxxxx",
8
"auth_uri": "xxxxxx",
9
"token_uri": "xxxxxx",
10
"auth_provider_x509_cert_url": "xxxxx",
11
"client_x509_cert_url": "xxxxx.iam.gserviceaccount.com"
12
}
13
I don’t want to use a file in the project. Is there a way instead of a path to file to use JSON string from the dictionary to connect to BigQuery?
Advertisement
Answer
you can use the constructor service_account.Credentials.from_service_account_info(sa_dict)
instead.
be careful if you upload the code to a public repo though. One of the reasons to use a separate JSON file is so you can exclude it from repos.
JavaScript
1
15
15
1
sa_dict = {
2
"type": "xxxx",
3
"project_id": "xxx",
4
"private_key_id": "xxx",
5
"private_key": "xxxxxx",
6
"client_email": "xxxx@xxxxx.iam.gserviceaccount.com",
7
"client_id": "xxxxxxxxxx",
8
"auth_uri": "xxxxxx",
9
"token_uri": "xxxxxx",
10
"auth_provider_x509_cert_url": "xxxxx",
11
"client_x509_cert_url": "xxxxx.iam.gserviceaccount.com"
12
}
13
14
cred = service_account.Credentials.from_service_account_info(sa_dict)
15