Sentiment Analysis using Google Cloud API in Python giving error - python

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)

Related

SNS always sends default message instead of the specific protocol message that is given

Here is the code
message = {
"default":"Sample fallback message",
"http":{
"data":[
{
"type":"articles",
"id":"1",
"attributes":{
"title":"JSON:API paints my bikeshed!",
"body":"The shortest article. Ever.",
"created":"2015-05-22T14:56:29.000Z",
"updated":"2015-05-22T14:56:28.000Z"
}
}
]
}
}
message_as_json = json.dumps(message)
response = sns_client.publish(TopicArn = "arn:aws:sns:us-east-1:MY-ARN",
Message = message_as_json, MessageStructure = "json")
print(response)
To test, I used ngrok to connect the localhost (which runs my flask app) to the web and created a http subscription.
When I publish the message I can only see default message in that.
Any idea why this happens?
You need to specify the value of the http key as a simple JSON string value according to the AWS boto3 docs:
Keys in the JSON object that correspond to supported transport
protocols must have simple JSON string values.
Non-string values will cause the key to be ignored.
import json
import boto3
sns_client = boto3.client("sns")
message = {
"default": "Sample fallback message",
"http": json.dumps(
{
"data": [
{
"type": "articles",
"id": "1",
"attributes": {
"title": "JSON:API paints my bikeshed!",
"body": "The shortest article. Ever.",
"created": "2015-05-22T14:56:29.000Z",
"updated": "2015-05-22T14:56:28.000Z",
},
}
]
}
),
}
response = sns_client.publish(
TopicArn="arn:aws:sns:us-east-1:MY-ARN", Message=json.dumps(message), MessageStructure="json"
)

Microsoft Graph - Create Teams API Returns "Bind requests not supported for containment navigation property ."

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.

directline v3 gives error 400

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.

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)

PayPal Adaptive Payments - Preapproval request results in "Invalid request" error

I can't figure out what's happening with my Preapproval HTTP POST request. I'm just trying to do a basic call to PayPal's Adaptive Payments API, the Preapproval call specifically. And the PayPal error 580001 "Invalid request" is not that helpful in itself.
Request Headers (based on my Sandbox's account credentials, which I changed to xxx):
{
'X-PAYPAL-REQUEST-DATA-FORMAT': 'JSON',
'X-PAYPAL-SECURITY-PASSWORD': 'xxx',
'X-PAYPAL-RESPONSE-DATA-FORMAT': 'JSON',
'X-PAYPAL-SECURITY-SIGNATURE': 'xxx',
'X-PAYPAL-SECURITY-USERID': 'xx',
'X-PAYPAL-APPLICATION-ID': 'APP-80W284485P519543T'
}
My request payload (HTTP POST, body encoded in JSON):
{
"requireInstantFundingSource": "TRUE",
"returnUrl": "http://www.google.com/?paypal=ok",
"maxTotalAmountOfAllPayments": 1002,
"maxNumberOfPaymentsPerPeriod": 1,
"endingDate": "2014-03-14T16:49:36+0000",
"requestEnvelope.errorLanguage": "en_US",
"clientDetails.applicationId": "XXX",
"cancelUrl": "http://www.google.com/paypal=cancel",
"startingDate": "2013-09-15T16:49:36+0000",
"feesPayer": "PRIMARYRECEIVER",
"currencyCode": "SEK"
}
The above POST body is posted to:
https://svcs.sandbox.paypal.com/AdaptivePayments/Preapproval
Response from Paypal ("prettified" for understanding):
{
"responseEnvelope": {
"ack": "Failure",
"timestamp": "2013-09-10T09:56:43.031-07:00",
"build": "6941298",
"correlationId": "26d55e6bfcaa0"
},
"error": [
{
"category": "Application",
"domain": "PLATFORM",
"severity": "Error",
"message": "Invalid request: {0}",
"subdomain": "Application",
"errorId": "580001"
}
]
}
Any feedback is appreciated.
OK fixed. How?
Fix #1
The arguments requestEnvelope.errorLanguage and clientDetails.applicationId need to be "JSONified" into objects on their own, such as:
"requestEnvelope": {
"errorLanguage": "en_US"
},
and
"clientDetails": {
"applicationId": "APP-XXXXXXXXXXXXX"
},
respectively.
Fix #2
Date formats; date format should be of the form 2014-03-15T20:14:38.007+00:00 and not 2014-03-14T20:14:38+0000 as I was passing. Note the milliseconds, and the timezone with the colon in the utc offset.
Next time an Invalid request comes up the parameters I'm passing will be the first thing to look at.

Categories

Resources