I'm trying to send data through POST request in django
url = 'http://db-003:8013/v1/upgrade-ce'
payload = {
"cluster_name": cluster_name,
"cec_id": cec_id,
"new_version": new_version,
"cr_number": cr_number,
}
response = requests.post(url, data=payload)
On receiver end post method:
cluster name = request.data.get('cluster_name')
Data on receiver's end
<QueryDict: {'cluster_name': ['abcd'], 'cec_id': ['abc'], 'new_version': ['8.0.23'], 'cr_number': ['6587657']}>
The obtained data is a list, and not an individual string string.
Tried json.dumps() , but on the receiver end, data is empty.
How do i get an individual string
Sending Content-Type as application/json in headers and json.dumps(payload) should work.
url = 'http://db-003:8013/v1/upgrade-ce'
payload = {
"cluster_name": cluster_name,
"cec_id": cec_id,
"new_version": new_version,
"cr_number": cr_number,
}
headers = {'Content-Type': 'application/json'}
response = requests.post(url, data=json.dumps(payload), headers=headers)
Related
Hey i have an api request and i need the value in payload to by dynamic, i tried with f'' but it wont make it dynamic
will appreciate your help.
import requests
url = "https://www.stie.com/api/conversations/KJQ-CZHNR-985/fields"
valuetarget = "123"
payload = {'apikey': 'zbyc88srdi333d3dpq5lye48pgg1tfo1pnjvj65ld',
'customfields': '[{"code": "orderno", "value":"valuetarget"}]'}
files = [
]
headers = {}
response = requests.request("POST", url, headers=headers, data=payload, files=files)
print(response.text)
You just need to load json and dump it to string and send it.
import json
valuetarget = "123"
payload = {
'apikey': 'zbyc88srdi333d3dpq5lye48pgg1tfo1pnjvj65ld',
'customfields':
json.dumps([{"code": "orderno", "value":valuetarget}])
}
You should escape the curly braces in the formatted string, like so:
f'[{{"code": "orderno", "value":"{valuetarget}"}}]'
But why not let requests format the string for you?
import requests
url = "https://www.stie.com/api/conversations/KJQ-CZHNR-985/fields"
valuetarget = "123"
# 'customfields' is now a list of dictionaries
payload = {'apikey': 'zbyc88srdi333d3dpq5lye48pgg1tfo1pnjvj65ld',
'customfields': [{"code": "orderno", "value": valuetarget}]}
files = [
]
headers = {}
response = requests.request("POST", url, headers=headers, data=payload, files=files)
print(response.text)
I have an array of ice cream flavors I want to iterate over for an API GET request. How do I loop through an array such as [vanilla, chocolate, strawberry] using the standard API request below?
import requests
url = "https://fakeurl.com/values/icecreamflavor/chocolate?"
payload = {}
headers = {
'Authorization': 'Bearer (STRING)',
'(STRING)': '(STRING)'
}
response = requests.request("GET", url, headers=headers, data = payload)
my_list = (response.text.encode('utf8'))
You could probably try string formatting on your url. You could loop through your array of ice-cream flavors, change the url in each loop and perform API GET request on the changed url.
import requests
iceCreamFlavors = ["vanilla", "chocolate", "strawberry"]
url = "https://fakeurl.com/values/icecreamflavor/{flavor}?"
payload = {}
headers = {
'Authorization': 'Bearer (STRING)',
'(STRING)': '(STRING)'
}
my_list = []
for flavor in iceCreamFlavors:
response = requests.request("GET", url.format(flavor=flavor), headers=headers, data = payload)
my_list.append(response.text.encode('utf8'))
I am trying with replace two literals with variable for for a payload for an sms:
import requests
url = "https://api.aql.com/v2/sms/send"
token='07ae4cca3f90a49347ccb5cfghypdngthwss85d9ce71862663e4b8162b366ba6c2db8f5f'
msg = "Ambient temperature has dropped to 10 Deg.C"
phone = "441234567890"
payload = "{\"destinations\" : [\"447753448024\"], \"message\": \"Hello, I am a message\"}"
headers = {
'x-auth-token': token,
'content-type': "application/json"
}
response = requests.post(url, data=payload, headers=headers)
print(response.text)
I wish to insert the variables phone and msg in place or the literals
Any help will be gratefully received
You may use json attribute from .post() it'll handle the content-type header and the conversion from dict to str
url = "https://api.aql.com/v2/sms/send"
token='07ae4cca3f90a49347ccb5cfghypdngthwss85d9ce71862663e4b8162b366ba6c2db8f5f'
msg = "Ambient temperature has dropped to 10 Deg.C"
phone = "441234567890"
payload = {'destinations':[phone], 'message':msg}
response = requests.post(url, json=payload, headers={'x-auth-token': token})
I need your help.
I am looking to communicate with a REST API containing sensor data at port number 3.
I have a Json (POST) request that works perfectly executed on a REST client like Insomnia.
My request :
{ "header": { "portNumber": 3 }, "data": { "index": 40 } }
Picture of my request
However I am unable to make it work on Python and to recover data from my sensor.
My Python code :
import requests
import json
url = 'http://192.168.1.100/iolink/sickv1' # Address of the OctoPrint Server
header = {'portNumber': '3', 'Content-Type': 'application/json'} #Basic request's header
data = {'index': 40}
def get_sensor_measure():
r = requests.post(url + '/readPort', headers=header, data=data)
print(r.content)
print(r.status_code)
I get the error:
b'{"header":{"status":1,"message":"Parsing Failed"}}'
Thank you in advance
You should pass 'portNumber': '3' in data not in header:
header = {'Content-Type': 'application/json'}
data = {'header': {'portNumber': '3'}, 'data': {'index': 40}}
And also as Karl stated in his answer you need to changes data to json:
r = requests.post(url + '/readPort', headers=header, json=data)
My guess would be that you are using the wrong field to pass your payload. It isn't really obvious, but the requests package expects JSON-type payload to be sent with the json field, not the data field, i.e.:
r = requests.post(url + '/readPort', headers=header, json=data)
With a few changes (Bold), it works. Thanks
url = 'http://192.168.1.100/iolink/sickv1' # Address of the OctoPrint Server
header = {'Content-Type': 'application/json'} #Basic request's header
**data = {'header': {'portNumber': 3}, 'data': {'index': 40}}**
def get_sensor_measure():
r = requests.post(url + '/readPort', headers=header, json=data)
print(r.content)
print(r.status_code)
Trying to use python requests. I'm getting a {"code":141,"error":"success/error was not called"} error when I try to save the response I receive from the url into a variable and then post it back to a different url. Any ideas how I can fix this?
payload = { "email" : "jade#gmail.com", "github" : "https://github.com/"}
headers = {'content-type': 'application/json', "Accept": 'application/json'}
r = requests.post("http://challenge.code2040.org/r", json = payload, headers = headers)
#Store the token into a variable
token = r.text
payload = { "token" : token}
headers = {'content-type': 'application/json', "Accept": 'application/json'}
r = requests.post("http://challenge.code2040.org/api/getstring", json = payload, headers = headers)
print r.text
You have to use the actual tokens you get back:
Based on the instructions from the main page:
================================
Stage I: Reverse a string
================================
Once you’re registered, it’s time to get started on the challenges.
The first one is straightforward. You’re going to reverse a string.
That is, if the API says “cupcake,” you’re going to send back “ekacpuc.”
POST a JSON dictionary with the key token and your previous token value to this endpoint:
http://challenge.code2040.org/api/getstring
The getstring endpoint will return a string that your code should then reverse, as in the example above.
Once that string is reversed, send it back to us. POST some JSON to:
http://challenge.code2040.org/api/validatestring
Use the key token for your token.
Use the key string for your reversed string.
Part 1 get out token:
payload = { "email" : "jade#gmail.com", "github" : "https://github.com/"}
headers = {'content-type': 'application/json', "Accept": 'application/json'}
r = requests.post("http://challenge.code2040.org/api/register", json = payload, headers = headers)
#Store the token into a variable
token = r.json() # {u'result': u'ZO8FFqVjWp'}
part 2 get the string:
payload = { "token" :token["result"]}
headers = {'content-type': 'application/json', "Accept": 'application/json'}
r = requests.post("http://challenge.code2040.org/api/getstring", json = payload, headers = headers)
jsn = r.json() # {"result":"Wv55g"} # we need to reverse that string
The final part is actually reversing the string you get from our last post:
payload = {"token" :token["result"], "string" :jsn["result"][::-1]} # jsn["result"][::-1]} reverse the string
r = requests.post("http://challenge.code2040.org/api/validatestring", json = payload, headers = headers)
print(r.json())
{u'result': u'PASS: stage1. Enrollment record updated!'} # all good!
You also had an extra r in your address "http://challenge.code2040.org/r" <- should not be there