How to call callback url from python? - python

I am trying to call a callback URL from a python function.
Here is the code:
rasa_url = "http://localhost:5005/webhooks/callback/webhook"
wa_data = {
"sender":"Rasa",
"message":"hi"
}
r = requests.post(url=rasa_url, data=wa_data)
In the terminal of rasa run, I am getting below error:
sanic.exceptions.InvalidUsage: Failed when parsing body as json.
I also tried,
r = requests.post(url=rasa_url, data=json.loads(json.dumps(wa_data)))
How can I solve this?

I think your request does not coincide with the documentation. The only one with both sender and message i found is to:
http://localhost:5005/conversations/{conversation_id}/messages
where you can send a JSON in this format (you also have an optional parse_data key)
{
"text": "Hello!",
"sender": "user"
}

Related

Keep getting an unexpected token k in JSON at position 0 when sending a python request

There is this game API I'm trying to develop a client for, and sending a PUT request to change the profile pic (even with the same structure as the games source code) returns an unexpected token k in JSON at position 0, the code I used is below:
with open("img.jpg", "rb") as image:
f = image.read()
bytess = str(bytearray(f))
imageParam = {
"key": "profile_image",
"data": bytess,
"filename": "profilepic.jpg",
"mimeType": "image/jpg"
}
newUrl = "https://bwsecondary.ddns.net:8080/api/v1/current_user/profile_world"
Confirm = requests.put(newUrl, data=imageParam, headers=headers)
print(Confirm.text)
It isn't the server since the game doesn`t receive the error when making a put request
Ok so, I had to parse it as Json instead of data, which is a rookie mistake, oh well...

Amazon Seller Central - SP-API - Create a feed document - InvalidInput

Trying to create feed document (here ) and I'm getting InvalidInput error code.
Authentication works well (I tried other endpoints and it works) so I think headers are not the issue.
Here is my sample code:
endpoint = 'https://sellingpartnerapi-eu.amazon.com/feeds/2020-09-04/documents'
body = {
"contentType": "text/tab-separated-values; charset=UTF-8"
}
resp = requests.post(
endpoint,
auth=self.amazon_auth.auth,
headers=self.amazon_auth.headers,
json=body
)
return resp
Response code:
{'errors': [{'code': 'InvalidInput',
'message': 'Invalid Input',
'details': ''}]}
I was also trying to use different contentType and charset (like text/plain) but I receive same error code!
This is first step of Submit feed tutorial.
I'm trying to create feed so I can get cartonIds to download labels for a shipment I created over Amazon Seller Central.
Any hint, help is more than welcome!
Thanks!
I solved this issue by:
requests.post(data=json.dumps(body))
Also make sure you pass the body for signing as well
I use RestSharp
restRequest1.AddParameter(....); gave me the same error as yours Invalid Input
but the below line gave me a response value
restRequest1.AddJsonBody(new { contentType = "text/xml; charset=UTF-8" });
It serializes obj to json format and adds it to the request body.
This code snippet in C# worked for me, i successfully uploaded a feed
My upload method:
private static bool UploadFile(byte[] encrypted, string url)
{
bool isUploaded = false;
var contentType = "text/tab-separated-values; charset=UTF-8";
var parameter = new Parameter
{
Name = contentType,
Value = encrypted,
Type = ParameterType.RequestBody
};
var restRequest = new RestRequest(Method.PUT);
restRequest.Parameters.Add(parameter);
var restClient = new RestClient(url);
var response = restClient.Execute(restRequest);
isUploaded = response.StatusCode == System.Net.HttpStatusCode.OK;
return isUploaded;
}

JSON RPC Returns 'Invalid API parameter' upon request in python

I'm trying to create my own jsonrpc client for a project, using python and requests. After an hour of searching online, Most errors are to do with people executing a get rather than a post or people getting a different error. According the the JSONRPC Spec (Found Here http://www.jsonrpc.org/specification) It should work. Any help would be most grateful. Thanks Sam.
Requests & Code Below:
Post Request Body:
{"method": "GudMethod", "params": {"ur": "HELLO"}, "jsonrpc": "2.0", "id": 1}
Request Response:
{
"jsonrpc": "2.0",
"result": {
"method": "GudMethod",
"success": false,
"error": "Invalid API parameter [jsonrpc] must be 2.0 [\"GudMethod\"]",
"extra": [],
"metrics": {
"st": "2018-05-24 22:16:37",
"sspt": 0.0006299018859863281
}
},
"id": null
}
Codes:
import json
import requests
class Client():
def __init__(self,url):
self.url = url
self.id = 0
def request(self,method,prms):
rq = Request(self,method,prms)
return rq
class Request():
def __init__(self,client,method,prms):
self.client = client
self.method = method
self.prms = prms
self.rq = None
def buildRequest(self):
self.client.id = self.client.id + 1
url = self.client.url + "?method={}".format(self.method)
jb = {}
jb["jsonrpc"] = "2.0"
jb["method"] = self.method
jb["params"] = self.prms
jb["id"] = self.client.id
body = json.dumps(jb)
return url,body
def execute(self):
url , body = self.buildRequest()
self.rq = requests.post(url,data=body)
print(body)
print(self.rq.text)
Also, dont ask me to use a ready made one. I was told that already, but due to where the project will be used, I can't install any librarys. Luckily requests will be installed, that would be painful otherwise
Your client's request looks fine.
The server must be parsing your request incorrectly, assigning the value GudMethod to the name jsonrpc.
Not only is the server parsing your request incorrectly, but the response also is not valid according to the JSON-RPC specification:
1) There should be no result field:
result
This member is REQUIRED on success.
This member MUST NOT exist if there was an error invoking the method.
The value of this member is determined by the method invoked on the Server.
2) There should be a top-level error field:
error
This member is REQUIRED on error.
This member MUST NOT exist if there was no error triggered during invocation.
The value for this member MUST be an Object as defined in section 5.1.
3) The error field should be a JSON Object with the following fields:
code
A Number that indicates the error type that occurred.
This MUST be an integer.
message
A String providing a short description of the error.
The message SHOULD be limited to a concise single sentence.
data
A Primitive or Structured value that contains additional information about the error.
This may be omitted.
The value of this member is defined by the Server (e.g. detailed error information, nested errors etc.).
As the server erroneously believes the jsonrpc field is not equal to 2.0, the error code field should be -32600 and the message field Invalid Request indicating
The JSON sent is not a valid Request object.

requests.post with Python

I'm connecting to a login protected API with a Python script here below.
import requests
url = 'https://api.json'
header = {'Content-Type': 'application/x-www-form-urlencoded'}
login = ('kjji#snm.com', 'xxxxx')
mnem = 'inputRequests':'{'inputRequests':'[{'function':'GDSP','identifier':'ibm','mnemonic':'IQ_TOTAL_REV'}]}}
r = requests.post(url, auth=login, data=mnem, headers=header)
print(r.json())
The connection is established but I am getting an error from the API because of the format of the data request.The original format is here below. I cannot find a way to enter this in the mnem here above:
inputRequests={inputRequests:
[
{function:"xxx",identifier:"xxx",mnemonic:"xxx"},
]
}
The error given is
C:\Users\xxx\Desktop>pie.py
File "C:\Users\xxx\Desktop\pie.py", line 6
mnem={'inputRequests':'{'inputRequests':'[{'function':'xxx','identifier':'xx','mnemonic':'xxx'}]}}
^
SyntaxError: invalid syntax
I am unsure on how to proceed from here. I cannot find anything in the requests documentation that points to how to insert several variables in the data field.
The requests module in Python receive protogenic Python dict as the JSON data in post request but not a string. Therefore, you may try to define mnem like this:
mnem = {
'inputRequests':[
{'function':'GDSP',
'identifier':'ibm',
'mnemonic':'IQ_TOTAL_REV'
}
]}
the data parameter should be a dictionary.
therefore to pass the three parameters try using:
mnem = {'function':'GDSP','identifier':'ibm','mnemonic':'IQ_TOTAL_REV'}

How to wait in line with Udacity reviewer API in Python?

I'm trying to use the Udacity reviewer API to wait in line to be assigned projects. However, I'm not able to figure out how to use the /submission_requests POST call. Right now I'm doing this in Python:
import requests
TOKEN = os.getenv('udacity_api_key')
BASE_URL = 'https://review-api.udacity.com/api/v1/'
headers = {'Authorization': TOKEN}
req_url = BASE_URL + 'submission_requests'
proj_req_data = {
"projects": [
{
"project_id": 232,
"language": "en-us"
}
]
}
res = requests.post(req_url, headers=headers, data=proj_req_data)
and the response (print res.content) is:
{"error":"request must have at least one valid project/language pair"}
I've also tried 'en' as the language. I got the project_id from the /me/certifications GET method.
Turns out I was using the wrong argument for the requests.post() function. If the data is passed as a dict, it needs to be in the json arg. If it is in the data arg, it needs to be stringified with json.dumps().
There's a nice Python API code example here: https://github.com/udacity/grading-assigner

Categories

Resources