Convert cURL command Into Python using requests - python

I am trying to convert the following cULR command into Python:
curl --location --request POST 'api.datamyne.com/frontend/REST/application' \
--header 'Content-Type: application/json' \
--data-raw '{
"token": "boKnofR06mzldz5eL00ARwa3B9winzpn",
"idApp":44
}'
I have the following Python code, but does not seem to work. Any idea how to include the raw data into into the request?
import requests
headers = {
'Content-Type': 'application/json',
'token': 'boKnofR06mzldz5eL00ARwa3B9winzpn',
'idApp': '44'
}
response = requests.get('http://api.datamyne.com/frontend/REST/applications', headers=headers)
print(response.content)

So in your python example you have called request.get().
If you call request.post() it will instead become a POST request.
as for adding it to the body, you could try a body variable:
data = {
'token': 'boKnofR06mzldz5eL00ARwa3B9winzpn',
'idApp': '44'
}
response = requests.post('http://api.datamyne.com/frontend/REST/applications',
headers=headers,
data = data)
Update:
This still fails because of an incorrectly formatted body.
to fix this i imported the json package and wrote:
#load string into a json object
data = json.loads('{"token": "boKnofR06mzldz5eL00ARwa3B9winzpn", "idApp": 44 }')
# json.dumps outputs a json object to a string.
response = requests.post('https://api.datamyne.com/frontend/REST/application', headers=headers, data=json.dumps(data))

Related

POST of JSON data not working the same with requests as with curl

I have problem with post method of REST in python.
when i am invoking REST API post method from curl it is working but when i invoke same from python program i have bad request 400 error.
The following curl command works:
curl -k -d #data.json -H "Content-Type: application/json" -v https://dsp.corpo.t-mobile.pl/npitapi/pn/saveAll
Data id data.json file
[{
"msisdn": "483260321",
"date_from": "2019-04-25T18:30:00.000+0000",
"date_to": "2019-04-24T18:30:00.000+0000",
"opr_recpn_id": 5,
"date_last": "2019-04-21T18:30:00.000+0000"
}]
My python code:
import json
import httplib
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
url = 'https://dsp.corpo.t-mobile.pl/npitapi/pn/saveAll';
pay= {'msisdn': '483260329',
'date_from': '2019-04-25T18:30:00.000+0000',
'date_to': '2019-04-24T18:30:00.000+0000',
'opr_recpn_id': 5,
'date_last': '2019-04-21T18:30:00.000+0000'}
response = requests.post(url, json=pay,verify=False)
print(response)
output response:
<Response [400]>
Can somebody help me what is the issue in data ?
i think json data is correct and it is same what i have in curl command.
import json
import requests
url = 'https://dsp.corpo.t-mobile.pl/npitapi/pn/saveAll'
headers = {
'content-type': "application/json"
}
pay= [{'msisdn': '483260329',
'date_from': '2019-04-25T18:30:00.000+0000',
'date_to': '2019-04-24T18:30:00.000+0000',
'opr_recpn_id': 5,
'date_last': '2019-04-21T18:30:00.000+0000'}]
response = requests.post(url, data=json.dumps(pay), headers=headers)
print(response)
Can you try this?

Python post request returns 500

I am using requests to make a POST request to create a user. The request succeeds with 201 created when I use curl, however fails with a 500 response when I use requests. My curl command is
curl --user administrator:password -H "Content-Type: application/json" https://localhost:8080/midpoint/ws/rest/users -d #user.json -v
And my python script is:
import requests
import json
headers = {
'Content-Type': 'application/json',
}
with open('user.json') as j:
data = json.load(j)
response = requests.post('https://localhost:8080/midpoint/ws/rest/users', headers=headers, data=str(data), auth=('Administrator', 'password'))
print(response)
Can anyone see a reason why my python script would be failing? I am at a loss.
str(data) returns the Python representation of data, not its JSON representation. These two forms can differ in things like ' vs. ", True vs. true, and None vs. null. To properly JSONify data, call json.dumps() on it:
response = requests.post(..., data=json.dumps(data))
or let requests do the JSONification:
response = requests.post(..., json=data)
or use the JSON as it appears in user.json directly:
with open('user.json') as j:
data = j.read()
response = requests.post(..., data=data)

Formatting Header Dictionary for Requests in Python

I have the following format for request headers:
{
"projectName": New001,
"cloudRegions":{"REGION1":"centralus"},
"cloudAccountName":"XXX-XXXX-XXXX"
}
How do I format this to accept the {"REGION1":"centralus"}?
My Python code:
url = 'www.myexample.com'
headers = {'Content-Type': 'application/json',
'projectName': New001,
'cloudRegions':{'REGION1':'centralus'},
'cloudAccountName':'XXX-XXXX-XXXX'
}
r = requests.post(url, headers=headers)
The problem is I can't make the request to where cloudRegions will be formatted correctly. The value is in dictionary format but it doesn't like that. I've tried wrapping it in str(), using json.loads(), json.dumps(), but it always ends up formatted wrong. How do I format it to be an object that will be accepted as a pair?
This CURL works, and you will see the same format:
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ \
"projectName": "New001", \
"cloudRegions":{"REGION1":"centralus"}, \
"cloudAccountName":"XXX-XXXX-XXXX" \
}' 'http://www.myexample.com'
You are using HTTP headers to send your data (which is very unusual), while your curl example clearly shows that you must send the data in HTTP body, formatted as JSON. requests can do that very easily.
So simply use:
url = 'www.myexample.com'
data = {'projectName': 'New001',
'cloudRegions': {'REGION1':'centralus'},
'cloudAccountName': 'XXX-XXXX-XXXX'
}
r = requests.post(url, json=data)

HTTP Error 422: Unprocessable Entity - when calling API from Python (but curl works)

When trying out the digitalocean v2 api I come across the following behaviour:
curl -X POST "https://api.digitalocean.com/v2/droplets" \
-d'{"name":"t002","region":"ams3","size":"512mb","image":"debian-7-0-x64","ssh_keys":[123]}' \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json"
Works fine and the droplet gets created.
Now when I do call it from python with:
json_values = {'name': 's002', 'region': 'ams3', 'size': '512mb', 'image': 'debian-7-0-x64', 'ssh_keys': [123]}
data = urllib.parse.urlencode(json_values)
data = data.encode("utf-8")
try:
req = urllib.request.Request(create_droplets_url, data)
req.add_header("User-Agent", uagent) # set custom user agent
req.add_header("Authorization", BearerToken) # set custom user agent
response = urllib.request.urlopen(req)
I get back: HTTP Error 422: Unprocessable Entity with no further information. Am i doing something wrong on the python side? Thx
Additional Info:
I figured out that the problem must be with ssh_keys. If I remove that element everything works fine.
Why are you url-encoding the data? That's not what the curl version is doing. Dump it to JSON instead:
data = json.dumps(json_values)
req = urllib.request.Request(create_droplets_url, data)
I have received the same error and realized it has occurred due to the server side validation failed with your post data.
Solution:
use requests.post instead of urllib.request.Request then you could get the accurate error message for that serverside 422 error code.
Sample code:
import requests
API_URL = "***"
TOKEN = "***"
HEADERS = {
"User-Agent": "Python API Sample",
"Authorization": "Bearer " + TOKEN,
"Content-Type": "application/json"
}
data = {
"user_id": "***",
"project_id": "***"
}
json_data = json.dumps(data).encode('utf8')
response = requests.post(url=API_URL, headers=HEADERS, data=json_data)
print(json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": ")))
Thanks :)

How to make a post request with REQUESTS package for Python?

I am trying to use the toggl api.
I use Requests instead of Urllib2 for doing my GETs en POSTS. But i am stuck.
payload = {
"project":{
"name":"Another Project",
"billable":False,
"workspace":{
"Name":"jorrebor's workspace",
"id":213272
},
"automatically_calculate_estimated_workhours":False
}
}
url = "https://www.toggl.com/api/v6/projects.json"
r = requests.post(url, data=json.dumps(payload), auth=HTTPBasicAuth('j_xxxxx#gmail.com', 'mypassword'))
Authentication seems to be fine, but the payload format probably isn't.
a curl command with the same parameters:
curl -v -u heremytoken:api_token -H "Content-type: application/json" -d "{\"project\":{\"billable\":true,\"workspace\":{\"id\":213272},\"name\":\"Another project\",\"automatically_calculate_estimated_workhours\":false}}" -X POST https://www.toggl.com/api/v6/projects.json
does work fine.
What wrong with my payload? The response is get is:
["Name can't be blank","Workspace can't be blank"]
which leads me to conclude that the authentication works but toggl cannot read my json object.
Seems like you should try setting the header to a JSON application, rather than the default format, and send a JSON object instead of the Python dict. Check it out here:
payload = {"project":{"name":"Another Project",
"billable":False,
"workspace":{"Name":"jorrebor's workspace",
"id":213272},
"automatically_calculate_estimated_workhours":False
} }
parameters_json = json.dumps(payload)
headers = {'Content-Type': 'application/json')
r = client.post(url, data=parameters_json, headers=headers)
which should allow the site to read the json object just fine.

Categories

Resources