django Google calendar v3 insert event - parse error - python

I'm not using client libraries but REST directly. I have succesfully created google login. I save user's access_token. I use access_token (here in this code is hardcoded) when I try to create new event and insert it in user's calendar. Here is my code
def google_get_list(request):
parser = httplib2.Http()
uri = "https://www.googleapis.com/calendar/v3/calendars/primary/events?key={YOUR_API_KEY}"\
.format(YOUR_API_KEY='AIzaSyD_Axx9SGH0Y71xxxxxxxxxxxxxxxxxxxxx')
params = urllib.urlencode({
"summary": "Test Calendar",
})
headers = {'Content-Type': 'application/json',
'Authorization': 'Bearer ya29.AHES6ZQdFo8IXu5gAns8qEiyLbcbZxxxxxxxxxxxxxxxxxxxxxxxxxx',
'X-JavaScript-User-Agent': 'Google APIs Explorer'
}
resp, content = parser.request(uri, method='POST', body=params, headers=headers)
print content
return HttpResponseRedirect('/')
content that is received (print) is
{
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "Parse Error"
}
],
"code": 400,
"message": "Parse Error"
}
}
Any help?

Related

Trying to post data to firestore using requests

im trying to post JSON data to firestore using requests and it keeps returning this error.
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"{\"data\": \"message\"}\": Cannot bind query parameter. Field '{\"data\": \"message\"}' could not be found in request message.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "Invalid JSON payload received. Unknown name \"{\"data\": \"message\"}\": Cannot bind query parameter. Field '{\"data\": \"message\"}' could not be found in request message."
}
]
}
]
}
}
I've tried different method using different types of JSON Encoding and still returns the same error. i would appreciate if someone could look into this for me. Below is my code
def thestream(self, instance):
app = App.get_running_app()
s = requests.Session()
self.data = {u'data': u'message'}
self.headers = {"authorization": "bearer " + app.idToken}
r = s.post("https://firestore.googleapis.com/v1/projects/*******************************/databases/(default)/documents/messages/TemitayoAdefemi", params=json.dumps(self.data), headers=self.headers)
print(r.ok)
print(r.content.decode())
Try defining a Document resource in your payload:
self.data = {u'fields': {u'data': {u"stringValue": u'message'}}}
In your POST request, try passing the payload in data=self.data instead of param:
r = s.post("https://firestore.googleapis.com/v1/projects/***/databases/(default)/documents/messages/TemitayoAdefemi", data=self.data, headers=self.headers)

Login error 401 while making put request in Python

I'm trying to post a videoId in a youtube playlist using youtube api in python. Below is my code,
import json
from apiclient.discovery import build
import requests
post_url = "https://www.googleapis.com/youtube/v3/playlistItems"
payload = {
'key':"*******",
'part':'snippet',
'playlistId':'****',
'videoId':'****'
}
r = requests.post(post_url, data=json.dumps(payload))
print(r.text)
But now I keep getting below error,
{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Login Required",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Login Required"
}
}
I've tried getting data by GET request in similar way and I was successful in that. What is wrong with this then?
401 means Unauthorized.
So, you need to pass authentication details.
Examples:
https://developers.google.com/youtube/v3/docs/playlists/list#examples
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets

FCM api 'Bad request 400' error

I'm trying to implement sending notifications via new FCM api protocols. I went through authenticating requests, I enabled api in google console as well. Now when I send request I'm receiving Bad request 400 error. Response doesn't contain any other information than error code and error message. Even reason field says 'Bad Request'. I'm implementing it with FCM api docs.
def fcm_test():
FCM_URL = "https://fcm.googleapis.com/v1/projects/MY_PROJECT_NAME/messages:send"
my_token = "device-token"
payload = {
"massage": {
"token": my_token,
"notification": {
"body": "body",
"title": "title"
}
}
}
payload = json.dumps(payload)
headers = {
"Authorization": "Bearer {auth_token}".format(auth_token=_get_authentication_token()),
"Content-Type": "application/json; UTF-8",
}
try:
request = moves.urllib.request.Request(FCM_URL, payload.encode('utf-8'), headers)
response = moves.urllib.request.urlopen(request, timeout=10)
except Exception as e:
pass
return
There's a typo in your payload key, can you try it again with "message" instead of "massage"?

POST to google apis compute engine gives 400

I am building a small flask app to handle automatic deployment for another project I am working on.
This involves setting a gcloud firewall rule using googleapis.
I have followed the below documentation.
https://cloud.google.com/compute/docs/reference/latest/firewalls/insert
When I make my POST call in the following manner.
headers = {
'Authorization': 'Bearer {}'.format(access_token)
}
name = unique_identifier + "-rule"
payload = {
"kind": "compute#firewall",
"name": name,
"sourceRanges": [
"0.0.0.0/0"
],
"sourceTags": [
unique_identifier
],
"allowed": [
{
"IPProtocol": "tcp",
"ports": [
port_number
]
}
]
}
data = json.dumps(payload)
r = requests.post("https://www.googleapis.com/compute/v1/projects/apollo-rocket-chat/global/firewalls?key={MY_API_KEY}", data=data, headers=headers)
where port_number and unique_idenifier are strings. access_token is retrieved using a service account I have set. I am confident that the token is good, since I can make a GET call to a protected resource using the token.
I am using python 3.5.
The response to this POST is the following.
{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Required field 'resource' not specified"
}
],
"code": 400,
"message": "Required field 'resource' not specified"
}
}
The error message is claiming that I am missing a field, although I have all the required fields that are specified at the link below.
https://cloud.google.com/compute/docs/reference/latest/firewalls/insert#request-body
What exactly am I doing wrong?
Figured it out. I removed.
data = json.dumps(payload)
and changed
r = requests.post("https://www.googleapis.com/compute/v1/projects/apollo-rocket-chat/global/firewalls?key={MY_API_KEY}", data=data, headers=headers)
to
r = requests.post("https://www.googleapis.com/compute/v1/projects/apollo-rocket-chat/global/firewalls?key={MY_API_KEY}", json=data, headers=headers)

Google URL Shortener API with python returning error

I'm trying to call the Google URL Shortener API in my python code:
def shorternUrl():
API_KEY = "AIzaSyCvhcU63u5OTnUsdYaCFtDkcutNm6lIEpw"
apiUrl = 'https://www.googleapis.com/urlshortener/v1/url'
longUrl = "http://www.cnn.com"
headers = {"Content-type": "application/json"}
data = {"longUrl": longUrl}
h = httplib2.Http('.cache')
try:
headers, response = h.request(apiUrl, "POST", urllib.urlencode(data), headers)
print response
except Exception, e:
print "unexpected error %s" % e
But I keep getting this error:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "Parse Error"
}
],
"code": 400,
"message": "Parse Error"
}
}
I'm not using the Google API for Python. Where i'm I going wrong?
You need to send JSON in a POST, not URL encoded data:
import json
# Rest of your code
headers, response = h.request(apiUrl, "POST", json.dumps(data), headers)

Categories

Resources