Quantcast
Channel: Active questions tagged rest - Stack Overflow
Viewing all articles
Browse latest Browse all 4140

Authentication with a service account to an API runing in Google Cloud Run in Python

$
0
0

I'm trying to connect to a Fast API (running in Google Cloud Run) from outside the Google Cloud Project. For this I have created a Service Account with the role Cloud Run Invoker (using IAM).

Now I'm trying to make a REST call to the API.I got it working somehow. But I'm not satisfied with the solution.

Is there a way I can avoid the gcloud command and do the whole thing in python without default login?I want to avoid setting the service account credential with gcloud and accessing it with default login, because the API will be used by others and it should be minimal affort to get started with. Installing and set up of gcloud isn't.Any kind of hints would be appreciated.

I downloaded the service account credential info file (key.json).I activate the service account with the command:

gcloud auth activate-service-account caller-sa@api_proj.iam.gserviceaccount.com --key-file=./key.json --project=api_proj

Then I used the following code:

import google.authimport google.auth.transport.requestsfrom google.auth.transport.requests import Requestimport google.oauth2.id_tokenimport requestsimport google.oauth2.credentialsservice_account_file = "./key.json"credentials, project_id = google.auth.default()request = Request()credentials.refresh(request)id_token = credentials.id_tokenheaders = {"Authorization": f"Bearer {id_token}"}url = "https://api-proj.europe-west3.run.app/predict"data = """ Mi chiamo Pietro. Sono di Roma."""response = requests.post(url=url, headers=headers, json={"data": data})response.raise_for_status()print(response.json())

Viewing all articles
Browse latest Browse all 4140

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>