I have a curl command which is sending a jpg image converted to base64 to a web service:
curl -X POST --insecure \
https://link_to_the_web_service.com \
-H 'authorization:authorization_token' \
-H 'cache-control: no-cache' \
-H 'content-type: application/json' \
-d '{"model_spec": {"name": "inception", "signature_name": "predict_images"}, "inputs": {"images": {"dtype": 7, "tensor_shape": {"dim":[{"size": 1}]}, "string_val": ["IMAGE_CONVERTED_TO_BASE_64"]}}}'
I am converting the jpg image to base64 using the below website: "https://www.browserling.com/tools/image-to-base64". The execution of the curl command gives a success output.
Now I am testing the web service by taking jpg images, converting the curl command to python3 and the image to base64 using python3 like this:
import requests
import base64
host = 'https://link_to_the_web_service.com'
image = 'sample5.jpg'
image_64_encode = base64.b64encode(open('sample5.jpg',"rb").read())
headers = {'authorization': token, 'cache-control': 'no-cache', 'content-type': 'application/json'}
data={"model_spec": {"name": "inception", "signature_name": "predict_images"}, "inputs": {"images": {"dtype": 7, "tensor_shape": {"dim":[{"size": 1}]}, "string_val": [str(image_64_encode)]}}}
request = requests.post(url=host,
data=data,
headers=headers,
verify=False)
print(request)
and I receive a <500> response which means the web service is not able to read the image input.
I even tried 'base64.encodestring' to convert to base64 but no luck.
How do I properly convert the above curl command to python?
The data parameter of the requests.post method expects a string, not a dict. You should post your payload as JSON with the json parameter instead:
request = requests.post(url=host,
json=data,
headers=headers,
verify=False)
Related
I was trying to write the result of curl to a file and extracting it and assign it to variable but i was not able to keep getting validations error
cmd='curl -k -u admin:admin -X POST --header "Content-Type:multipart/mixed"--header "Accept:application/json"-F "myPartnm1=#sftprest;type=application/json"-F" myPartname2=#sftppvteopenkey;type=application/json/oc-stream" http://cdrteo456.serms.com:4456/api/v/cert'
with open("dff.json","w") as f:
json.dump(os.system(cmd),ident=25)
with open("dff.json") as f1:
data= json.loads(f1)
print(data['id'])
Also attempted with requests:
import requests
headers = {
'Content-Type': 'multipart/mixed,
'Content-Type': 'multipart/mixed',
'Accept': 'application/json',
}
files = {
'myPartnm1': open('sftprest/opt/tr5.txt;type=application/json', 'rb'),
'myPartname2': open('sftppvteopenkeyopt/tr5/new.pem;type=application/json/oc-stream', 'rb'),
}
response = requests.post('http://cdrteo456.serms.com:4456/api/v/cert', headers=headers, files=files, verify=False, auth=('admin', 'admin'))
{
"massage":"Error validating request",
"validationError":["unable to import cerifecate.Expecting two body parts with certificate info and certificate info and certificate data"]
}
i was able to solve this by using .sh file extension in unix along with path file instead of curl
You need to add a space before the -F options
json"-F "myPartnm1=#sftp
json" -F "myPartnm1=#sftp
Add a space after the -F and remove the space after the double quote.
/json"-F" myPa
/json" -F "myPa
curl -k -u admin:admin -X POST --header "Content-Type:multipart/mixed" --header "Accept:application/json" -F "myPartnm1=#sftprest;type=application/json" -F "myPartname2=#sftppvteopenkey;type=application/json/oc-stream" http://cdrteo456.serms.com:4456/api/v/cert
I used https://curlconverter.com to convert your curl.
It did not convert until I made the above changes.
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))
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?
I'm trying to convert curl command to python script.
Here is the curl command which works great in command line:
curl -v -H 'X-Api-Key:123456789' https://synthetics.newrelic.com/synthetics/api/v3/monitors -G -d 'limit=100'
Here is the python script:
import requests
import json
headers = {
'X-Api-Key': '123456789'
}
data = {
'limit': '100'
}
response = requests.post(
'https://synthetics.newrelic.com/synthetics/api/v3/monitors', headers=headers, data=data)
print(response.content)
The output of the script is:
{"code":415,"message":"HTTP 415 Unsupported Media Type"}
I also tried to dump the data while passing it to the request using json.dump(data) which didn't help (Got the same error).
What am i doing wrong? Please advise.
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)