Convert curl request to python request error - python

I'm trying to convert the cURL to Python request but doesn't work.
cURL:
curl -G 'http://10.255.254.212:8086/query?db=telegraf' --data-urlencode 'q=SELECT last("value")/10 FROM "Cisco-IOS-XR-asr9k-sc-envmon-oper:environmental-monitoring/racks/rack/slots/slot/modules/module/sensor-types/sensor-type/sensor-names/sensor-name/value-detailed" WHERE "source" = $source_value AND "rack" = $rack_value AND "slot" = $slot_value AND "name" = $name_value' --data-urlencode 'params={"source_value":"mkm_mkm_pe2","rack_value":"0","slot_value":"0","name_value":"host__die_FabSwitch"}'`
It doesn't work and gives me 400 bad requests error.
I tried converting using the https://curl.trillworks.com/
which gives me the following code which doesn't work either.
import requests
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
params = {
'db': 'telegraf',
}
data = 'q=SELECT last("value")/10 FROM "Cisco-IOS-XR-asr9k-sc-envmon-oper:environmental-monitoring/racks/rack/slots/slot/modules/module/sensor-types/sensor-type/sensor-names/sensor-name/value-detailed" WHERE "source" = $source_value AND "rack" = $rack_value AND "slot" = $slot_value AND "name" = $name_value&params={"source_value":"mkm_mkm_pe2","rack_value":"0","slot_value":"0","name_value":"host__die_FabSwitch"}'
response = requests.get('http://10.255.254.212:8086/query', params=params, headers=headers, data=data)
Can anyone please help me identify the issue here.

Related

JSON parse error when using python requests for an API

If I run a curl statement in bash I get the result I want with no problem.
curl --header 'Content-Type: application/json' --header 'Authorization: Token ABC123' --data '{"jsonrpc":"2.0","method":"enterprise/getEnterpriseEdges","params":{"with":["certificates","configuration","links","recentLinks","site","licenses","analyticsMode","selfHealing"],"edgeIds":[4723]},"id":34123423}' --request POST 'https://my-portal.velocloud.net/portal/'
When putting it into a python script, I keep getting this result instead of the massive JSON array of data.
{'jsonrpc': '2.0', 'error': {'code': -32603, 'message': 'JSON parse error'}, 'id': 1}
This is a copy of my Python script
import requests
payload_headers = {
"Content-Type": "application/json",
"Authorization": "Token ABC123"
}
payload_data = {
"jsonrpc": "2.0",
"method": "enterprise/getEnterpriseEdges",
"params": {
"with": ["certificates", "configuration", "links", "recentLinks", "site", "licenses", "analyticsMode", "selfHealing"],
"edgeIds": [4723]
},
"id": 34
}
response = requests.post("https://my-portal.velocloud.net/portal/", headers=payload_headers, data=payload_data, verify= False)
json_info = response.json()
print(json_info)
I was hoping to get a JSON output of the data like I get with the curl in bash, and eventually incorporate a loop to run through a list to get multiple JSONs to build out an API.
You need to dump the dict to str:
import json
response = requests.post("https://my-portal.velocloud.net/portal/",
headers=payload_headers,
data=json.dumps(payload_data),
verify=False)
Or just use json parameter:
response = requests.post("https://my-portal.velocloud.net/portal/",
headers=payload_headers,
json=payload_data,
verify=False)

PiXhost's API- upload images

I'm trying to use PiXhost's api to upload images. Every time I request something from https://api.pixhost.to/images it always returns 400 Bad request. Their API documentation uses python unirest package, but I can't install it as it seems to use too old code.
Am I doing something wrong here?
Link to documentation
my code:
import requests
headers = {
"Content-Type": "multipart/form-data; charset=utf-8",
"Accept": "application/json"
}
params = {
"content_type": "0",
"max_th_size": "420"
}
files = {
"img": open("image.jpg", mode="rb")
}
response = requests.post("https://api.pixhost.to/images", headers=headers, params=params, files=files)```
import requests
url = "https://api.pixhost.to/images"
payload={'content_type': '0',
'max_th_size': '420'}
files={
'img': ('1.JPG', open('C:/Users/prave/Desktop/1.JPG', 'rb')),
'content_type': '0',
'max_th_size': '420'
}
headers = {
}
response = requests.request("POST", url, data=payload, files=files)
print(response)
Here you go
output :
Response 200
Issue with your code:
THe endpoint expects formdata , you are passing query parameter
So how did i figure it out
goto documentation and click curl tab to get curl equalent code:
Now goto postman and click import>Raw text > paste the curl , and click continue and then import
This creates the request for you
Now goto body and select img type as file and upload the file:
Now click code and generate equalent curl and python request code:
THe generated python code had few isseus one was to remove header completely and then to remove one slash from the file name.
Just a quick test, I managed to get it done via cURL
curl -X POST --include "https://api.pixhost.to/images" \
-H 'Content-Type: multipart/form-data; charset=utf-8' \
-H 'Accept: application/json' \
-F 'img=#test1.jpg' \
-F 'content_type=0' \
-F 'max_th_size=420'
https://pixhost.to/show/39/178828640_test1.jpg
Note: the test1 image is in the same folder when I running the script
I also receive 400 status code without a body when removing the # before the URL (so check you URL again)
HTTP/1.1 400 Bad Request
Server: nginx/1.10.3 (Ubuntu)

Why does this curl command work but not my post request via python?

I'm trying to make a POST request to https://accounts.spotify.com/api/token via python and the request, library but can't get it to work. I'm able to execute the request via curl command:
note - params enclosed in * * are correct and work in the curl request
curl -H "Authorization: Basic *base 64 encoded client ID and secret*"
-d grant_type=authorization_code -d code=*auth code* -d
redirect_uri=https%3A%2F%2Fopen.spotify.com%2F
https://accounts.spotify.com/api/token
and the request works just fine, however when I try to make what I think is the exact same request in python, I always get the same bad request error
headers = {
"Authorization": "Basic *base64 encoded client ID and secret*"
}
params = {
"grant_type": "authorization_code",
"code": code,
"redirect_uri": "https://open.spotify.com/"
}
response = requests.post(
url,
params=params,
headers=headers
)
If you can help me figure out how the two requests differ and why the python one never seems to work that would be amazing.
see section 2. of https://developer.spotify.com/documentation/general/guides/authorization-guide/ for the params
You use -d flag in your curl request which stands for data.
So you should pass your params as data also in your Python POST request:
headers = {
"Authorization": "Basic *base64 encoded client ID and secret*"
}
params = {
"grant_type": "authorization_code",
"code": code,
"redirect_uri": "https://open.spotify.com/"
}
response = requests.post(
url,
data=params,
headers=headers
)
seems like you put payload under wrong argument, try to change params into json or data (depends on what type of requests that API accept):
response = requests.post(
url,
json=params,
headers=headers
)

Converting a cURL command to a python request

I am new to cURL; I wanted to convert a curl command of this structure:
curl -X POST "http://127.0.0.1:8881/models/faewrfaw/v1/predict" -H "Content-Type:multipart/form-data" -F "data={\"key\": \"Path\"};type=application/json" -F "Path=#C:\Users\rtam\Music\1 2 3\TEST123.jpg"
to a python request. I used https://curl.trillworks.com/ to assist me and got this as the output:
import requests
headers = {
'Content-Type': 'multipart/form-data',
}
files = {
'data': (None, '{"key": "Path"};type'),
'Path': ('C:\\Users\\rtam\\Music\\1 2 3\\TEST123.jpg', open('C:\\Users\\rtam\\Music\\1 2 3\\TEST123.jpg', 'rb')),
}
response = requests.post('http://127.0.0.1:8881/models/faewrfaw/v1/predict', headers=headers, files=files)
However, when testing the response in python I got a bad request/request the server did not understand. I noticed the trillworks website did not account for the type (application/json) in its formatting, does it need to be in the python script?
This answer might help you: How to send JSON as part of multipart POST-request
In your case it would be
files = {
'Path': (
'C:\\Users\\rtam\\Music\\1 2 3\\TEST123.jpg',
open('C:\\Users\\rtam\\Music\\1 2 3\\TEST123.jpg', 'rb'),
'application/octet-stream'
)
'data': (None, '{"key": "Path"}', 'application/json'),
}
response = requests.post(
'http://127.0.0.1:8881/models/faewrfaw/v1/predict',
files=files
)

How to POST this API code in Python 3 with Requests module? Keep getting 405 error

I want to use the API for a link shortener site. I know the example given is in curl and that -H means there's a header as well as PUT means it's posting, but I can't seem to get the result I want no matter how much I try. All I can do is either get a 405 error or break it.
I am on Windows with Python 3 and do have requests installed already.
For developers Shorte.st prepared API which returns responses in JSON format.
Currently there is one method which can be used to shorten links on behalf of your account.
Take a look on the sample below to learn how to use our API.
curl -H "public-api-token: (my token)" -X PUT -d
"urlToShorten=google.com" https://api.shorte.st/v1/data/url
When received,
{"status":"ok","shortenedUrl":"http:\/\/sh.st\/XXXX"}
I have tried a few things namely,
import requests
import json
gogo = { 'public-api-token: (my token)' : 'urlToShorten=google.com'}
yep = requests.post('https://api.shorte.st/v1/data/url',
data=json.dumps(gogo))
print (yep.text)
shows me an HTML webpage with error 405.
import requests
import json
gogo = { 'public-api-token' : '(my token)', 'urlToShorten=' : 'google.com'}
yep = requests.post('https://api.shorte.st/v1/data/url',
data=json.dumps(gogo))
print (yep.text)
Also shows me a webpage with error 405.
I now know the -H is for headers and am using this while still just gets me the page.
import requests
import json
headers = { 'public-api-token' : '(my token)' }
gogo = {"urlToShorten" : "google.com"}
yep = requests.post('https://api.shorte.st/v1/data/url',
data=json.dumps(gogo), headers=headers)
print (yep.text)
and another attempt another 405
gogo = {"public-api-token: (my token)" : "urlToShorten=google.com"}
yep = requests.post('https://api.shorte.st/v1/data/url',
data=json.dumps(gogo))
print (yep.text)
Even this just gives me a full html page/405 if I take off the text.
headers = { "public-api-token: (my token)" : "urlToShorten=google.com" }
yep = requests.post('https://api.shorte.st/v1/data/url', headers=headers)
print (yep.text)
You are putting your PUT payload in the headers. Put it in the body instead. Your payload is not JSON, so there is no need to try and treat it as such.
The headers need to be specified as a dictionary with the header name and token as key and value. The parameters for the payload can be treated in the same way.
You are also using the wrong requests method; to send a PUT request, use the put function instead:
headers = {'public-api-token': '(my token)'}
payload = {'urlToShorten': 'google.com'}
response = requests.put(
'https://api.shorte.st/v1/data/url',
data=payload, headers=headers)
print(response.json())
The response object has a json() method to decode the JSON data returned by the API; it'll give you the Python data structure corresponding to the JSON text.
I don't have a token for the service you are using; I created a demo using the httpbin.org service; it reflects what was sent as a JSON response:
>>> import requests
>>> headers = {'public-api-token': '(my token)'}
>>> payload = {'urlToShorten': 'google.com'}
>>> response = requests.put(
... 'http://httpbin.org/put',
... data=payload, headers=headers)
>>> from pprint import pprint
>>> pprint(response.json())
{u'args': {},
u'data': u'',
u'files': {},
u'form': {u'urlToShorten': u'google.com'},
u'headers': {u'Accept': u'*/*',
u'Accept-Encoding': u'gzip, deflate',
u'Content-Length': u'23',
u'Content-Type': u'application/x-www-form-urlencoded',
u'Host': u'httpbin.org',
u'Public-Api-Token': u'(my token)',
u'User-Agent': u'python-requests/2.5.0 CPython/2.7.9 Darwin/14.1.0'},
u'json': None,
u'origin': u'94.118.96.0',
u'url': u'http://httpbin.org/put'}
If you compare that to the output produced for curl sending a PUT request to the same URL you'll see the same results are produced:
$ curl -H "public-api-token: (my token)" -X PUT \
-d "urlToShorten=google.com" http://httpbin.org/put
{
"args": {},
"data": "",
"files": {},
"form": {
"urlToShorten": "google.com"
},
"headers": {
"Accept": "*/*",
"Content-Length": "23",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"Public-Api-Token": "(my token)",
"User-Agent": "curl/7.37.1"
},
"json": null,
"origin": "94.118.96.0",
"url": "http://httpbin.org/put"
}

Categories

Resources