[Python] Google Service account authentication for API call using python

Discussão em 'Python' iniciado por Stack, Abril 9, 2025.

  1. Stack

    Stack Membro Participativo

    Wanted to call out one GCP api from my python code, following is that method -

    import google
    from google.oauth2 import service_account
    import google.auth.transport.requests
    import requests

    def get_window(self):
    credentials = service_account.Credentials.from_service_account_file(
    self.default_credentials, scopes=['https://www.googleapis.com/auth/cloud-platform']
    )
    request = google.auth.transport.requests.Request()
    credentials.refresh(request)

    # Make an authenticated API request
    request_url = "https://sqladmin.googleapis.com/v1/projects/my-projectid/instances/my-instanceid"
    headers = {"Authorization", f"Bearer {credentials.token}"}
    req = requests.get(request_url, headers=headers)
    print(req.text)


    When I call this method, following is the response:

    request = google.auth.transport.requests.Request()
    AttributeError: module 'google.auth.transport' has no attribute 'requests'


    I am using python 3.9 on my local install packages are:

    pip freeze


    aiohttp==3.8.1
    aiosignal==1.2.0
    async-timeout==4.0.2
    attrs==21.4.0
    cachetools==5.0.0
    certifi==2021.10.8
    googleapis-common-protos==1.56.0
    httplib2==0.20.4
    idna==3.3
    multidict==6.0.2
    protobuf==3.19.4
    pyasn1==0.4.8
    pyasn1-modules==0.2.8
    pycparser==2.21
    pyOpenSSL==22.0.0
    pyparsing==3.0.7
    requests==2.27.1
    rsa==4.8
    six==1.16.0
    uritemplate==4.1.1
    urllib3==1.26.9
    yarl==1.7.2

    Continue reading...

Compartilhe esta Página