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)
Related
Using v5 of the pinterest api and stuck on the authentication flow: https://developers.pinterest.com/docs/getting-started/authentication/
Completed the first step and got the access code.
However, I get the below error when I try to use this code to get the access token.
{"code":1,"message":"Missing request body"}
Here is my code:
client_id= 'my_client_id'
client_secret = 'my_client_secret'
data_string = f'{client_id}:{client_secret}'
token = base64.b64encode(data_string.encode())
headers = {
'Authorization': 'Basic ' + token.decode('utf-8'),
'Content-Type': 'application/x-www-form-urlencoded',
}
url = "https://api.pinterest.com/v5/oauth/token"
code = "my_code_that_i_got_in_the_first_step"
params = {
'grant_type':'authorization_code',
'code': code,
'redirect_url':'https://my_redirect_uri'
}
r = requests.post(url, headers=headers, params=params)
print(r.json())
Below is the correct way to get the access token:
client_id= 'my_client_id'
client_secret = 'my_client_secret'
data_string = f'{client_id}:{client_secret}'
token = base64.b64encode(data_string.encode())
headers = {
'Authorization': 'Basic ' + token.decode('utf-8'),
'Content-Type': 'application/x-www-form-urlencoded',
}
url = "https://api.pinterest.com/v5/oauth/token"
code = "my_code_that_i_got_in_the_first_step"
data= {
'grant_type':'authorization_code',
'code': code,
'redirect_uri':'https://my_redirect_uri'
}
r = requests.post(url, headers=headers, data=data)
print(r.json())
In my question, I had mistyped redirect_uri as redirect_url. Also, when sending a POST, you should use data instead of params. See the comment by Amos Baker.
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')
Would someone be able to help me understanding how can I pass values from multiple lists as function parameters? I'm trying to update email for each of myemailId with url that includes customerId.
my code so far:
emailId = [732853380,7331635674]
customerId = ['cust-12345-mer','cust-6789-mer']
for x, y in zip(emailId, customerId):
def update_email(emailId, token, user, notes="https://myurl.com/customer?customerId =" + customerId):
headers = { 'accept': 'application/json',
'Content-Type': 'application/json',
'token': token,
'user': user}
endpoint = 'email/'
body = {'emailId': emailId, 'user': user, 'notes': notes}
requests.put(url = host + endpoint, headers = headers, json=body)
return True
but receiving this error that is corresponding to the line that starts with def update_email...:
TypeError: must be str, not list
Thanks in advance!
First of all, you shouldn't define the function for each loop iteration but once before executing the loop.
In order to pass the values, use:
emailId = [732853380, 7331635674]
customerId = ['cust-12345-mer', 'cust-6789-mer']
def update_email(emailId, token, user, customerId):
notes = "https://myurl.com/customer?customerId =" + customerId
headers = {'accept': 'application/json',
'Content-Type': 'application/json',
'token': token,
'user': user}
endpoint = 'email/'
body = {'emailId': emailId, 'user': user, 'notes': notes}
requests.put(url=host + endpoint, headers=headers, json=body)
return True
for x, y in zip(emailId, customerId):
update_email(x, token, user, y)
customerId is the list, y is the value from that list. Use
notes="https://myurl.com/customer?customerId =" + y
I need to POST a JSON from a client to a server. I'm using Python 2.7.1 and simplejson. The client is using Requests. The server is CherryPy. I can GET a hard-coded JSON from the server (code not shown), but when I try to POST a JSON to the server, I get "400 Bad Request".
Here is my client code:
data = {'sender': 'Alice',
'receiver': 'Bob',
'message': 'We did it!'}
data_json = simplejson.dumps(data)
payload = {'json_payload': data_json}
r = requests.post("http://localhost:8080", data=payload)
Here is the server code.
class Root(object):
def __init__(self, content):
self.content = content
print self.content # this works
exposed = True
def GET(self):
cherrypy.response.headers['Content-Type'] = 'application/json'
return simplejson.dumps(self.content)
def POST(self):
self.content = simplejson.loads(cherrypy.request.body.read())
Any ideas?
Starting with Requests version 2.4.2, you can use the json= parameter (which takes a dictionary) instead of data= (which takes a string) in the call:
>>> import requests
>>> r = requests.post('http://httpbin.org/post', json={"key": "value"})
>>> r.status_code
200
>>> r.json()
{'args': {},
'data': '{"key": "value"}',
'files': {},
'form': {},
'headers': {'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'close',
'Content-Length': '16',
'Content-Type': 'application/json',
'Host': 'httpbin.org',
'User-Agent': 'python-requests/2.4.3 CPython/3.4.0',
'X-Request-Id': 'xx-xx-xx'},
'json': {'key': 'value'},
'origin': 'x.x.x.x',
'url': 'http://httpbin.org/post'}
It turns out I was missing the header information. The following works:
import requests
url = "http://localhost:8080"
data = {'sender': 'Alice', 'receiver': 'Bob', 'message': 'We did it!'}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(data), headers=headers)
From requests 2.4.2 (https://pypi.python.org/pypi/requests), the "json" parameter is supported. No need to specify "Content-Type". So the shorter version:
requests.post('http://httpbin.org/post', json={'test': 'cheers'})
Which parameter between data / json / files you need to use depends on a request header named Content-Type (you can check this through the developer tools of your browser).
When the Content-Type is application/x-www-form-urlencoded, use data=:
requests.post(url, data=json_obj)
When the Content-Type is application/json, you can either just use json= or use data= and set the Content-Type yourself:
requests.post(url, json=json_obj)
requests.post(url, data=jsonstr, headers={"Content-Type":"application/json"})
When the Content-Type is multipart/form-data, it's used to upload files, so use files=:
requests.post(url, files=xxxx)
The better way is:
url = "http://xxx.xxxx.xx"
data = {
"cardno": "6248889874650987",
"systemIdentify": "s08",
"sourceChannel": 12
}
resp = requests.post(url, json=data)
headers = {"charset": "utf-8", "Content-Type": "application/json"}
url = 'http://localhost:PORT_NUM/FILE.php'
r = requests.post(url, json=YOUR_JSON_DATA, headers=headers)
print(r.text)
Works perfectly with python 3.5+
client:
import requests
data = {'sender': 'Alice',
'receiver': 'Bob',
'message': 'We did it!'}
r = requests.post("http://localhost:8080", json={'json_payload': data})
server:
class Root(object):
def __init__(self, content):
self.content = content
print self.content # this works
exposed = True
def GET(self):
cherrypy.response.headers['Content-Type'] = 'application/json'
return simplejson.dumps(self.content)
#cherrypy.tools.json_in()
#cherrypy.tools.json_out()
def POST(self):
self.content = cherrypy.request.json
return {'status': 'success', 'message': 'updated'}
With current requests you can pass in any data structure that dumps to valid JSON , with the json parameter, not just dictionaries (as falsely claimed by the answer by Zeyang Lin).
import requests
r = requests.post('http://httpbin.org/post', json=[1, 2, {"a": 3}])
this is particularly useful if you need to order elements in the response.
I solved it this way:
from flask import Flask, request
from flask_restful import Resource, Api
req = request.json
if not req :
req = request.form
req['value']
It always recommended that we need to have the ability to read the JSON file and parse an object as a request body. We are not going to parse the raw data in the request so the following method will help you to resolve it.
def POST_request():
with open("FILE PATH", "r") as data:
JSON_Body = data.read()
response = requests.post(url="URL", data=JSON_Body)
assert response.status_code == 200
I am having trouble sending a topic downstream message using Firebase. Everything works fine when I send to single or multiples users using tokens, my code looks like this
notif = {
'to': 'TOKEN',
'data': {'msg': 'whatever'},
}
opener = urllib2.build_opener()
data = json.dumps(notif)
req = urllib2.Request(
FCM_URL,
data=data,
headers={
'Content-Type': 'application/json',
'Authorization': 'key=' + API_KEY,
}
)
response = opener.open(req)
However if I replace the recipients using a topic, more precisely the code becomes
notif = {
'to': '/topic/MY_TOPIC',
'data': {'msg': 'whatever'},
}
opener = urllib2.build_opener()
data = json.dumps(notif)
req = urllib2.Request(
FCM_URL,
data=data,
headers={
'Content-Type': 'application/json',
'Authorization': 'key=' + API_KEY,
}
)
response = opener.open(req)
{"multicast_id":id,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
Is there something I am missing? I should outline that sending topic messages from the firebase console works fine.
Any help more than welcome,
Best & thanks!
Alex
Ah so silly...
I was missing s in topics, the correct form is hence
notif = {
'to': '/topics/MY_TOPIC',
'data': {'msg': 'whatever'},
}
Hope it helps someone anyway!
Best,
A