Kris Kris - 10 months ago 50
Python Question

Google Datastore API Authentication in Python

Authenticating requests, especially with Google's API's is so incredibly confusing!

I'd like to make authorized HTTP POST requests through python in order to query data from the datastore. I've got a service account and p12 file all ready to go. I've looked at the examples, but it seems no matter which one I try, I'm always unauthorized to make requests.

Everything works fine from the browser, so I know my permissions are all in order. So I suppose my question is, how do I authenticate, and request data securely from the Datastore API through python?

I am so lost...

Answer Source

You probably should not be using raw POST requests to use Datastore, instead use the gcloud library to do the heavy lifting for you.

I would also recommend the Python getting started page, as it has some good tutorials.

Finally, I recorded a podcast where I go over the basics of using Datastore with Python, check it out!

Here is the code, and here is an example:

#Import libraries
from gcloud import datastore
import os

#The next few lines will set up your environment variables
#Replace "YOUR_RPOEJCT_ID_HERE" with the correct value in
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "key.json"


os.environ["GCLOUD_TESTS_PROJECT_ID"] = projectID
os.environ["GCLOUD_TESTS_DATASET_ID"] = projectID

#Let us build a message board / news website

#First, create a fake email for our fake user
email = ""

#Now, create a 'key' for that user using the email
user_key = datastore.Key('User', email)

#Now create a entity using that key
new_user = datastore.Entity( key=user_key )

#Add some fields to the entity

new_user["name"] = unicode("Iam Fake")
new_user["email"] = unicode(email)

#Push entity to the Cloud Datastore
datastore.put( new_user )

#Get the user from datastore and print
print( datastore.get(user_key) )

This code is licensed under Apache v2