displayname
displayname

Reputation: 327

List all buckets under a project from the google storage using Storage JSON API in Python

I am referring below link and below that, I have pasted a copy of my code. https://developers.google.com/apis-explorer/?hl=en_US#p/storage/v1/storage.buckets.list

   import requests
   response = requests.get('https://www.googleapis.com/storage/v1/b?project=
   {YOUR_PROJECT_NAME}&key={YOUR_API_KEY}')
   print(response.json())

When I try to access it it gives me below error

{'error': {'errors': [{'domain': 'global', 'reason': 'required', 'message': 'Anonymous users does not have storage.buckets.list access to project 72
8242242638.', 'locationType': 'header', 'location': 'Authorization'}], 'code': 401, 'message': 'Anonymous users does not have storage.buckets.list a
ccess to project 728242242638.'}}

What part I am missing?

Upvotes: 0

Views: 1068

Answers (1)

Brandon Yarbrough
Brandon Yarbrough

Reputation: 38399

You're missing authentication. An API key identifies a project, but it doesn't provide any sort of authentication. Google doesn't know that you're really a user allowed to view the access token.

If you want to see your command work real quick and you have the gcloud SDK installed, run gcloud auth print-access-token. That will give you a string like ya29.blibbity_blabbity. Attach a header to your request that reads Authorization: Bearer ya29.blibbity_blabbity, and your request should succeed.

Access tokens are only good for 5 minutes or so, and you shouldn't hardcode them into your code. You'll need a more permanent solution. The easiest way forward is to just use a higher level Google Cloud library, like google-cloud, but if you want to keep using requests directly, you'll want to start by learning more of the details of Google Cloud's auth. Start here: https://cloud.google.com/docs/authentication

Upvotes: 2

Related Questions