Null response from dialogAction(Python) - python

I am getting null response while my code is successfully working. I am not able to get response from dialogAction, i am
import json
import requests
def getdata(intent_name, fulfillment_state, message):
response = {
'dialogAction': {
'type': 'Close',
'intentName': intent_name,
'fulfillmentState': fulfillment_state,
'message': message
}
}
return response
def lambda_handler(event,context):
payload = {'userId':4,'type':'PARENT'}
r = requests.post("http://ec2-54-226-57-153.compute-1.amazonaws.com:8080/Tracking/rest/api", data=json.dumps(payload), headers = {'Content-Type': 'application/json','Accept': 'application/json'})
print(r.content)
getdata(
'currentIntent',
'Fulfilled',
{
'contentType': 'PlainText',
'content': 'message'
}
)

From what I understand, your code should be:
import json
import requests
def getdata(message):
return {
'dialogAction':{
'type':'Close',
'fulfillmentState':'Fulfilled',
'message':{
'contentType':'PlainText',
'content':message
}
}
}
def lambda_handler(event, context):
payload = {'userId':4,'type':'PARENT'}
r = requests.post("http://ec2-54-226-57-153.compute-1.amazonaws.com:8080/Tracking/rest/api", data=json.dumps(payload), headers = {'Content-Type': 'application/json','Accept': 'application/json'})
print(r.content)
return getdata(r.content)
Let us know if you are getting any error.

Related

Problem with Post action on Strapi via Python

I'm trying to send a POST and I get this error:
{"data":null,"error":{"status":400,"name":"ValidationError","message":"Missing "data" payload in the request body","details":{}}}
In [ ]:
This is my code:
import requests
import json
myToken = '256e8f598edc0990b39dbfe8c4acf39ec83ee3a1a8f212a7656b3892585755c52857503a356ed003fa6b1f5f4b89fc34b0aa64000bb1bf5bba75257a0128365c75aa96a8cb4ed7a32e7fc7b5ec899ae6d2633a7004ef7f991b8ca6e6bdac4a3a75954425f95cc1a209e09272b5582f58690759f81aecb506070c3c19b3cdac2f'
myUrl = 'http://localhost:1337/api/countries'
head = { 'Authorization': 'Bearer {}'.format(myToken), 'Content-Type': 'application/json'}
session = requests.Session()
session.headers.update(head)
Get request & response (working well):
response = session.get(myUrl)
print (response.text)
{
"data":[
{
"id":1,
"attributes":{
"name":"United States",
"createdAt":"2022-04-09T04:15:13.925Z",
"updatedAt":"2022-04-09T04:15:15.226Z",
"publishedAt":"2022-04-09T04:15:15.220Z"
}
}
],
"meta":{
"pagination":{
"page":1,
"pageSize":25,
"pageCount":1,
"total":1
}
}
}
Post request & response:
data = json.dumps(['data', {'name': 'United States'}])
response = session.post(myUrl, data = data)
print (response.text)
{
"data":null,
"error":{
"status":400,
"name":"ValidationError",
"message":"Missing \"data\" payload in the request body",
"details":{
}
}
}
Thanks in advance
I did the solution for that,
First of all: I changed the "data" to "json"
data = {'data': {'name': 'United states'}}
request = session.post(myUrl, json = data)
print (request.text)

python requests not recognizing params

I am requesting to mindbodyapi to get token with the following code using requests library
def get_staff_token(request):
URL = "https://api.mindbodyonline.com/public/v6/usertoken/issue"
payload = {
'Api-Key': API_KEY,
'SiteId': "1111111",
'Username': 'user#xyz.com',
'Password': 'xxxxxxxx',
}
r = requests.post(url=URL, params=payload)
print(r.text)
return HttpResponse('Done')
gives a response as follows
{"Error":{"Message":"Missing API key","Code":"DeniedAccess"}}
But if I request the following way it works, anybody could tell me, what I am doing wrong on the above code.
conn = http.client.HTTPSConnection("api.mindbodyonline.com")
payload = "{\r\n\t\"Username\": \"username\",\r\n\t\"Password\": \"xxxxx\"\r\n}"
headers = {
'Content-Type': "application/json",
'Api-Key': API_KEY,
'SiteId': site_id,
}
conn.request("POST", "/public/v6/usertoken/issue", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
In the second one, you are passing the API Key in headers and the credentials in the body of the request. In the first, you are sending both the API Key and credentials together in the query string, not the request body. Refer to requests.request() docs
Just use two dictionaries like in your second code and the correct keywords, I think it should work:
def get_staff_token(request):
URL = "https://api.mindbodyonline.com/public/v6/usertoken/issue"
payload = {
'Username': 'user#xyz.com',
'Password': 'xxxxxxxx',
}
headers = {
'Content-Type': "application/json",
'Api-Key': API_KEY,
'SiteId': "1111111",
}
r = requests.post(url=URL, data=payload, headers=headers)
print(r.text)
return HttpResponse('Done')

Retrieving single json object from python requests results as list

I'm trying to retrieve only requestId object from json results after querying my API.
my code:
def findRequests(group, token, user):
headers = { 'accept': 'application/json',
'Content-Type': 'application/json',
'token': token,
'user': user}
endpoint = 'requests/find'
body = {'groupIDs': [group], "createdDate": {'operator': "BETWEEN", 'fromDate': "01-APR-2020 00:00:00", 'toDate': "21-APR-2020 00:00:00"}}
r = requests.post(url = host + endpoint, headers = headers, json=body, verify=False)
data = json.loads(r.text)
print (data[0]['requestId'])
json data:
[{'requestId': 2567887, 'requestName': 'Here is a sample name', 'requestSubject': 'sample subject', 'createdDate': '01-APR-2020 14:06:03'}, {'requestId': 7665432,...}]
then I would like to save all the values for requestId object found in results as a list:
myRequestsList = print(findRequests(group, token, user))
However the above will only return a single requestId and not all of the ones that were returned in data variable in def findRequests(group, token, user). What am I doing wrong?
Output:
2567887
None
Desired output:
2567887,
7665432
Could someone help me with this? thanks in advance!
First, you should modify your func:
Then, assign the variable to the func, not the print:
myRequestsList = list(findRequests(group, token, user)))
(!) However, I assume that group,token, user are replaced by other variables.
And finally, to get the output:
for req in myRequestsList:
print(req)
Later edit:
def findRequests(group, token, user):
headers = { 'accept': 'application/json',
'Content-Type': 'application/json',
'token': token,
'user': user}
endpoint = 'requests/find'
body = {'groupIDs': [group], "createdDate": {'operator': "BETWEEN", 'fromDate': "01-APR-2020 00:00:00", 'toDate': "21-APR-2020 00:00:00"}}
r = requests.post(url = host + endpoint, headers = headers, json=body, verify=False)
data = json.loads(r.text)
final_list = []
for each_req in data:
final_list.append(each_req['requestId'])
return final_list
myRequestsList = findRequests(group, token, user)
for each in myRequestsList:
print(each)

How to mock test python requests

I want to know how to write mock python request tests.
def request_headers():
payload = {
'client_id': settings.STAT_SERVER['CLIENT_ID'],
'client_secret': settings.STAT_SERVER['CLIENT_SECRET'],
'username': settings.STAT_SERVER['USERNAME'],
'password': settings.STAT_SERVER['PASSWORD'],
'grant_type': 'password',
}
How can I mock test all of this?
token_url = settings.STAT_SERVER['URL'] + 'o/token/'
r = requests.request(
method="POST", url=token_url, data=payload, verify=False)
if r.status_code != 200:
msg = "Failed to authenticate. Error code {}: {}"
msg = msg.format(r.status_code, r.text)
LOGGER.error(msg)
credentials = r.json()
Here's the base_headers
base_headers = {
'Content-Type': 'application/json',
'Accept': 'application/json, */*'
}
base_headers['Authorization'] = "{} {}".format(
credentials['token_type'], credentials['access_token']
)
LOGGER.debug('Get token: credentials={}'.format(credentials))
return base_headers
The unittest.mock.patch decorator is an awesome tool for solving these things.
So you would do something like:
from unittest.mock import Mock, patch
#patch("requests.request")
def test_request(request_mock: Mock):
response_mock = Mock(status_code=200)
response_mock.json.return_value = {"foo": "bar"}
request_mock.return_value = response_mock

Can upload photo when using the Google Photos API

I am trying to upload a photo (jpg image) using the new Google Photos API.
I am able to get an uploadToken but when I try to create the media item I get the following error:
{
"newMediaItemResults": [
{
"uploadToken": "CAIS+QIAkor2Yr4JcvYMMx..... ",
"status": {
"code": 3,
"message": "NOT_IMAGE: There was an error while trying to create this media item."
}
}
]
}
Here is a snippet of my code:
import sys
import json
import requests
pic = 'image.jpg'
fname = 'read_write_token_creds.json'
with open(fname) as f:
data = json.load(f)
tok = data['access_token']
# Step 1 get an upload token
URL = 'https://photoslibrary.googleapis.com/v1/uploads'
headers = {
'Content-type': 'application/octet-stream',
'X-Goog-Upload-File-Name': pic,
'X-Goog-Upload-Protocol': 'raw',
'Authorization': 'Bearer ' + tok,
}
files = {'file': open(pic, 'rb')}
r = requests.post(URL, headers=headers, files=files)
upload_token = r.text
# Step 2
album_id = 'AG.....7u'
URL = 'https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate'
header = {
'Content-type': 'application/json',
'Authorization': 'Bearer ' + tok
}
payload = {
'albumId': album_id,
'newMediaItems': [
{
'description': 'Desc.',
'simpleMediaItem': { 'uploadToken': upload_token }
}
]
}
r = requests.post(URL, headers=header, data=json.dumps(payload))
When I look at r.text from the requests module, I receive the error message which was given at the top of he message.
This worked for me.
How to authenticate user see here https://developers.google.com/photos/library/guides/upload-media
def upload(service, file):
f = open(file, 'rb').read();
url = 'https://photoslibrary.googleapis.com/v1/uploads'
headers = {
'Authorization': "Bearer " + service._http.request.credentials.access_token,
'Content-Type': 'application/octet-stream',
'X-Goog-Upload-File-Name': file,
'X-Goog-Upload-Protocol': "raw",
}
r = requests.post(url, data=f, headers=headers)
print '\nUpload token: %s' % r.content
return r.content
def createItem(service, upload_token, albumId):
url = 'https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate'
body = {
'newMediaItems' : [
{
"description": "test upload",
"simpleMediaItem": {
"uploadToken": upload_token
}
}
]
}
if albumId is not None:
body['albumId'] = albumId;
bodySerialized = json.dumps(body);
headers = {
'Authorization': "Bearer " + service._http.request.credentials.access_token,
'Content-Type': 'application/json',
}
r = requests.post(url, data=bodySerialized, headers=headers)
print '\nCreate item response: %s' % r.content
return r.content
# authenticate user and build service
upload_token = upload(service, './path_to_image.png')
response = createItem(service, upload_token, album['id'])

Categories

Resources