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)
Related
I'm new to Microsoft Teams, I'm trying to create a team using the following API
https://graph.microsoft.com/beta/teams
I'm using the following snippet of Python code to create the team.
url = "https://graph.microsoft.com/beta/teams"
headers = {'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json'}
data = {
"template#odata.bind": "https://graph.microsoft.com/beta/teamsTemplates('standard')",
"displayName": "FIRST TEAM",
"description": "FIRST TEAM",
"members#odata.bind": [
{
"#odata.type": "#microsoft.graph.aadUserConversationMember",
"roles": '[owner]',
"userId": "3c0d3719-6c92-4646-af05-f02df80242db"
}
]
}
response = requests.post(url, headers=headers, data=json.dumps(data))
I receive the following response.
b'{\r\n "error": {\r\n "code": "BadRequest",\r\n "message": "Bind requests not supported for containment navigation property.",\r\n "innerError": {\r\n "date": "2020-10-12T16:58:45",\r\n "request-id": "2063aba7-43f2-4024-912c-e7402bb1d6ba",\r\n "client-request-id": "2063aba7-43f2-4024-912c-e7402bb1d6ba"\r\n }\r\n }\r\n}'
I'd like to know what I'm doing wrong, I tried to learn more about the error message Bind requests not supported for containment navigation property but couldn't find anything helpful.
Can someone please help me understand what the error means and if possible what is wrong with the request itself ?
I found the answer, I had to modify data as follows.
data = {
"template#odata.bind": r"https://graph.microsoft.com/beta/teamsTemplates('standard')",
"displayName": "FIRST TEAM",
"description": "FIRST TEAM",
"members": [
{
"#odata.type": "#microsoft.graph.aadUserConversationMember",
"roles": ["owner"],
"userId": "3b0d3719-6c92-4646-af05-f02df80242db"
}
]
}
If you can't tell the key has to be members
This was discovered through trial and error though I'm not sure why.
I'm trying to perform sentiment analysis using google NLP cloud API.
Below is my code
import requests
url = "https://language.googleapis.com/v1/documents:analyzeSentiment"
myobj = {
"key": "XYZ",
"document":{
"type":"PLAIN_TEXT",
"language": "EN",
"content":"'Lawrence of Arabia' is a highly rated film biography about British Lieutenant T. E. Lawrence. Peter O'Toole plays Lawrence in the film."
},
"encodingType":"UTF8",
"Content-Type": "application/json"
}
x = requests.post(url, data = myobj)
print(x.text)
But it is giving me error
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"Content-Type\": Cannot bind query parameter. Field 'Content-Type' could not be found in request message.\nInvalid JSON payload received. Unknown name \"document\": Cannot bind query parameter. 'document' is a message type. Parameters can only be bound to primitive types.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "Invalid JSON payload received. Unknown name \"Content-Type\": Cannot bind query parameter. Field 'Content-Type' could not be found in request message."
},
{
"description": "Invalid JSON payload received. Unknown name \"document\": Cannot bind query parameter. 'document' is a message type. Parameters can only be bound to primitive types."
}
]
}
]
}
}
Does anybody know why it is happening? Will appreciate any help. Thanks.
Use the json parameter instead of data:
x = requests.post(url, json=myobj)
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
In the Step Sending an Activity to the bot As per the documentation Here,
https://docs.botframework.com/en-us/restapi/directline3/#navtitle
I should pass this as the body content of the post request
{
"type": "message",
"from": {
"id": "user1"
},
"text": "hello"
}
I am using the following parameters to make POST request in python, but its not working.
msg = {"type": "message","channelId": "directline","conversation":{"id": str(convId)},"from":{"id": "test_user1"},"text": "hello"}
header = {"Authorization":"Bearer q1-Tr4sRrAI.cwA.BmE.n7xMxGl-QLoT7qvJ-tNIcwAd69V-KOn5see6ki5tmOM", "Content-Type":"application/json", "Content-Length": "512"}
send2 = "https://directline.botframework.com/v3/directline/conversations/"+str(convId)+"/activities"
rsa1 = requests.post(send2,data=msg, headers=header)
This gives me this error:
{
"error": {
"code": "MissingProperty",
"message": "Invalid or missing activities in HTTP body"
}
}
Before this step everything is working fine.
Edit 1: Even i added content-length as updated in the code, it gives the same error
Edit 2: If i changed the msg to json.dumps(msg)
rsa1 = requests.post(send2,data=json.dumps(msg), headers=header)
I get response:
{u'error': {u'message': u'Failed to send activity: bot returned an error', u'code': u'ServiceError'}}
{
"error": {
"code": "ServiceError",
"message": "Failed to send activity: bot returned an error"
}
}
The directline API is only not working, on skype client everything is working fine.
According to the code that you've posted, your request body looks like this:
{
"type": "message",
"channelId": "directline",
"conversation": {
"id": str(convId)
},
"from": {
"id": "test_user1"
},
"text": "hello"
}
I'd suspect that your error is caused by the fact that the conversation ID value that you're including in the request body is not surrounded with double quotes in the JSON that's sent over the wire.
For simplicity (and to eliminate the error you're receiving), I'd suggest that you try omitting the channelId property and the conversation property from the request body, as I don't believe that either of these properties are necessary (i.e., you are issuing the request to the Direct Line URI, so the Bot Framework knows that Direct Line is the channel, and the conversation ID is already being specified in the request URI). In other words, try this as your request body:
{
"type": "message",
"from": {
"id": "test_user1"
},
"text": "hello"
}
When passing a dictionary to data it gets urlencoded automatically, so the api returns an error as it expects json data.
You can either use the json lib, or preferably pass your dictionary to the json parameter.
Using json.dumps :
rsa1 = requests.post(send2, data=json.dumps(msg), headers=header)
Using requests only :
rsa1 = requests.post(send2, json=msg, headers=header)
Also you don't have to add "Content-Length" in header and if you use the second example you don't have to add "Content-Type" either.
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?