python-3.xgoogle-cloud-platformgoogle-cloud-source-repos

Make requests to Google API with Python


I'm trying to make requests to the Google API to create source repositories using a service account and his JSON key file. Since there are no client libraries for this product, I am using the queries with Python using this documentation https://cloud.google.com/source-repositories/docs/reference/rest

I already used a similar code to invoke my cloud-functions with success, but this time I'm block for these requests at the 401 error. I set up the GOOGLE_APPLICATION_CREDENTIALS with the JSON of my service account, give the service-account the permissions of Source Repository Administrator, but still return 401.

Here's my code

import urllib.request
import json
import urllib
import google.auth.transport.requests
import google.oauth2.id_token

body = { "name" : "projects/$my_project_name/repos/$name_repo"}
jsondata = json.dumps(body).encode("utf8")
req = urllib.request.Request('https://sourcerepo.googleapis.com/v1/projects/$my_project_name/repos')
req.add_header('Content-Type', 'application/json; charset=utf-8')

auth_req = google.auth.transport.requests.Request()
id_token = google.oauth2.id_token.fetch_id_token(auth_req, 'https://www.googleapis.com/auth/cloud-platform')
req.add_header("Authorization", f"Bearer {id_token}")
response = urllib.request.urlopen(req, jsondata)
print (response.read().decode())

I tried also using the with an API-KEY at the end of the url like this

req = urllib.request.Request('https://sourcerepo.googleapis.com/v1/projects/$my_project_name/repos?key=$my-api-key')

Thank you


Solution

  • I tried also using the with an API-KEY at the end of the url like this

    API Keys are not supported.

    Your code is using an OIDC Identity Token instead of an OAuth Acess Token.

    from google.oauth2 import service_account
    
    credentials = service_account.Credentials.from_service_account_file(
        '/path/to/key.json',
        scopes=['https://www.googleapis.com/auth/cloud-platform'])
    
    
    request = google.auth.transport.requests.Request()
    credentials.refresh(request)
    

    // Use the following code to add the access token:

    req.add_header("Authorization", f"Bearer {credentials.token}")