Prabhjot Prabhjot - 1 year ago 237
Python Question

Login Required error using service account Google BigQuery API

I wrote a python script that called insert API of BigQuery to insert data to a table. I use service account for OAuth authentication. It functioned correctly for few days but now it gives Login Required error (401). Following is the code:

scopes = ['']

credentials =ServiceAccountCredentials.from_json_keyfile_name('/home/ubuntu/aha/udofy.json', scopes=scopes)

service ='bigquery', 'v2', credentials=credentials)

job_body = { } #Body JSON

request =, body=job_body)

response = request.execute()

I see the following error when I check the job logs on the UI:


"error": {

"errors": [

"domain": "global",
"reason": "required",
"message": "Login Required",
"locationType": "header",
"location": "Authorization"

"code": 401,

"message": "Login Required"



API Response:

{u'configuration': {u'query': {u'createDisposition': u'CREATE_IF_NEEDED',
u'destinationTable': {u'datasetId': u'co_gradeup_android_ANDROID',
u'projectId': u'udofy-1021',
u'tableId': u'user_answer_attempts'},
u'query': u' SELECT user_dim.user_id as user_id, event_dim.params.value.string_value as post_id, DATE(USEC_TO_TIMESTAMP(event_dim.timestamp_micros)) as attempt_date, count(*) as attempt_count FROM [udofy-1021:co_gradeup_android_ANDROID.app_events_20161101] WHERE =\'Answer_Selected\' and event_dim.params.key = \'postId\' and user_dim.user_id is not null and user_dim.user_id != "" group by 1,2,3 ',
u'writeDisposition': u'WRITE_APPEND'}},
u'etag': u'', #User_etag
u'id': u'', #User_Id
u'jobReference': {u'jobId': u'job_C9kSTaEOQBw0VPBEF_Yj44C0-Us',
u'projectId': u'udofy-1021'},
u'kind': u'bigquery#job',
u'selfLink': u'',
u'statistics': {u'creationTime': u'1478082742163',
u'startTime': u'1478082742420'},
u'status': {u'state': u'RUNNING'},
u'user_email': u''} #service_account_email

Answer Source

The issue was that the output schema/format of the query in the job body did not match the schema of the table in which the data was being inserted via the insert API. There was a minor change in the query which was executed in the job body.

The output format of the query should be exact same as the table schema in the the output data has to be inserted.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download