Translating a curl to python requests - python

I'm trying to create a python script to interact with an API for a system called Xibo. My problem is that I don't know python very well and the documentation for this system is what could generously be described as poor. Parts of their documentation use the format of the requests but their official API manual suggested the following curl command to update a media file on the system. I understand that requests are the best format to interact with APIs over and above curl so obviously I'd rather do it in requests if the general idea is that it's better.
curl -X POST "http://129.12.19.62/api/library" -H "accept: application/json" -H "Content-Type: multipart/form-data" -F "files=#47.htz" -F "name=47" -F "oldMediaId=47" -F "updateInLayouts=1" -F "deleteOldRevisions=1"
That is the command. Could anyone give me assistance by helping me translate it to the format of a request? I have tried using curl.trillworks but for some reason, it says that there was an "Error parsing curl command.". I understand if this is not possible or if you need some more information, I'll do my best to provide what anyone needs to help me.
Thank you.

Try something like this:
import requests
entry_point = 'http://129.12.19.62/api/library'
headers = {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
}
data = {
'files': '#47.htz',
'name': '47',
'oldMediaId': '47',
'updateInLayouts': '1',
'deleteOldRevisions': '1'
}
r = requests.post(entry_point, headers=headers, data=data)

If you try pasting your curl command into curlconverter.com again, it now generates correct requests code:
import requests
headers = {
'accept': 'application/json',
# requests won't add a boundary if this header is set when you pass files=
# 'Content-Type': 'multipart/form-data',
}
files = {
'files': open('47.htz', 'rb'),
'name': (None, '47'),
'oldMediaId': (None, '47'),
'updateInLayouts': (None, '1'),
'deleteOldRevisions': (None, '1'),
}
response = requests.post('http://129.12.19.62/api/library', headers=headers, files=files)

Related

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)

How to do this REST API call in Python?

I'm struggling with how to properly do this REST API call in Python using requests package.
curl --user aa43ae0a-a7a7-4016-ae96-e253bb126aa8:166291ff148b2878375a8e54aebb1549 \
--request POST --header "Content-Type: application/json" \
--data '{ "startDate": "2016-05-15" , "endDate": "2016-05-16", "format": "tsv", "dataset": "appStart" }' \
https://analytics.cloud.unity3d.com/api/v2/projects/aa43ae0a-a7a7-4016-ae96-e253bb126aa8/rawdataexports
I don't know, how to set the parameters of:
r = requests.post("https://analytics.cloud.unity3d.com/api/v2/projects/aa43ae0a-a7a7-4016-ae96-e253bb126aa8/rawdataexports", ...)
Any help would be appreciated, thanks in advance.
Something like this should do the job :
auth = HTTPBasicAuth('aa43ae0a-a7a7-4016-ae96-e253bb126aa8', '1662[....]549')
payload = {
"startDate": "2016-05-15" ,
"endDate": "2016-05-16",
"format": "tsv",
"dataset": "appStart",
}
url = "https://analytics.cloud.unity3d.com/api/v2/projects/aa43ae0a-a7a7-4016-ae96-e253bb126aa8/rawdataexports"
result = requests.post(url, json=payload, auth=auth)
Authentication : --user argument of curl comand allows to setup an HTTP Basic Auth
--data was a JSON payload, while the requested content-type is configured (via headers) with Content-Type: application/json. Simplify this with requests using json argument and passing a valid python dict as payload. The payload will be converted to json, and the correct header will be added to the request to retrieve a response with json data.
Be careful ! In your question, you provided the user/password used to call this REST API. If this information is the real one, posting it on Stack Overflow is probably a security issue !

Translating curl to python requests

Making a multipart/form-data request to an api endpoint: https://api-reference.smartling.com/#tag/Files%2Fpaths%2F~1files-api~1v2~1projects~1%7BprojectId%7D~1file%2Fpost
I'm using python requests module with this syntax:
headers = {
'Authorization': 'Bearer ...',
'Content-Type': 'multipart/form-data'
}
files = {'file': open('myfile.xliff', 'rb')}
data = {
'fileUri': '...',
'fileType': 'xliff',
...
}
requests.request('POST', endpoint, headers=headers, files=files, data=data)
I am receiving an error from the endpoint unfortunately it just gives me a general http 500 error.
This does work fine if I manually do it via curl:
curl -XPOST -H 'Authorization: Bearer ...' -F "file=#myfile.xliff' -F "fileUri=..." ...
So I don't believe its the endpoint not accepting a proper request.
Does this curl statement and this python call seem equivalent? Been stuck on this problem, I have tried the following resources:
https://github.com/spulec/uncurl
https://curl.trillworks.com/
To try and get a curl to python equivalent for verification.
Unfortunately uncurl cannot parse my curl statement at all despite it working and curl.trillworks gives me a malformed 'files' dictionary and no 'data':
files = {
'file': ('myfile.xliff.;type', open('myfile.xliff;type', 'rb')),
'fileUri': (None, 'myfile.xliff'),
'fileType': (None, 'xliff'),
}
which is incorrect. (I tried it anyways as I was stuck)
try remove Content-Type from headers it will created automatically

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
)

Port cURL CLI shell command with multiple forms and file contents to Python

I have a cURL command which I am successfully invoking in BASH, and I wish to port it into Python. The BASH is as follows:
#!/bin/bash
ACCESS_TOKEN="123456789"
METADATA_FILENAME="metadata.json"
AUDIO_FILENAME="audio.wav"
curl -s -i \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-F "metadata=<${METADATA_FILENAME};type=application/json; charset=UTF-8" \
-F "audio=<${AUDIO_FILENAME};type=audio/L16; rate=16000; channels=1" \
https://access-alexa-na.amazon.com/v1/avs/speechrecognizer/recognize \
-o response.txt
I am currently trying to use the requests library in Python, but cannot seem to decipher the fields/forms. I currently have this, and can't identify how to deconstruct the cURL command into a format compatible with Python:
endpoint = "https://access-alexa-na.amazon.com/v1/avs/speechrecognizer/recognize"
r = requests.post(
endpoint,
headers={
"Authorization": "Bearer " + ACCESS_TOKEN
},
forms={
# ???
},
files={
# ???
}
)
Any help is appreciated :)
Thanks to the comment by t.m.adam.
It turns out that the last field in the files parameter takes all of the information, separated by semi-colon. I was therefore able to get it working with this:
r = requests.post(
endpoint,
headers={
"Authorization": "Bearer " + auth.ACCESS_TOKEN
},
files={
'metadata': (METADATA_FILENAME, open(METADATA_FILEPATH, 'rb'), 'application/json; charset=UTF-8'),
'audio': (AUDIO_FILENAME, open(AUDIO_FILEPATH, 'rb'), 'audio/L16; rate=16000; channels=1')
}
)
Try using this:
cURL to Python Requests

Categories

Resources