I am working with an API for license plate recognition ; and i get this curl command :
How to implement such call with curl in PYTHON?
curl "https://api.havenondemand.com/1/api/async/recognizelicenseplates/v1?url=https%3A%2F%2Fwww.havenondemand.com%2Fsample-content%2Fvideos%2Fgb-plates.mp4&source_location=GB&apikey=695e513c-xxxx-xxxx-xxxx-xxxxxxxxxx"
curl -X POST --form "url=https://www.havenondemand.com/sample-content/videos/gb-plates.mp4" --form "source_location=GB" --form "apikey=695e513c-xxxx-xxxx-a666-xxxxxxxxxx" https://api.havenondemand.com/1/api/async/recognizelicenseplates/v1
In Python, using the requests module is a much better option. Install it first:
pip install requests
Then do this:
import requests
API_URL = "https://api.havenondemand.com/1/api/async/recognizelicenseplates/v1"
data = {
"url": "https://www.havenondemand.com/sample-content/videos/gb-plates.mp4",
"source_location": "GB",
"apikey": "695e513c-xxxx-xxxx-a666-xxxxxxxxxx"
}
response = requests.post(API_URL, data)
print(response.json())
Basically, any form fields should go inside the data dictionary as key value pairs. We use requests.post() function here. The function takes the target URL as the first parameter. And the form values as the second parameter.
We get a response object back. You can see the raw response by printing out the value of response.content. However, if you know that the response is JSON, you can use the json() method to parse the response and get back Python data type (dictionary).
There are multiple options. You could start with urllib2 (or any other HTTP library like requests). A better option could be to directly use the python client library for havenondemand
The fastest way to call Haven OnDemand APIs is to use HPE official libraries. You can install the HOD Python lib and use it as follows:
install the lib
pip install havenondemand
# put these in your file
from havenondemand.hodclient import *
from havenondemand.hodresponseparser import *
client = HODClient("API_KEY", version="v1")
parser = HODResponseParser()
# callback function
def asyncRequestCompleted(response):
jobID = parser.parse_jobid(response)
if jobID is None:
errorObj = hodParser.get_last_error()
for err in errorObj.errors:
print ("Error code: %d \nReason: %s \nDetails: %s\n" % (err.error,err.reason, err.detail))
else:
client.get_job_status(jobID, requestCompleted)
def requestCompleted(response):
payloadObj = parser.parse_payload(response)
resp = ""
if payloadObj is None:
errorObj = parser.get_last_error()
for err in errorObj.errors:
if err.error == ErrorCode.QUEUED:
time.sleep(2)
client.get_job_status(err.jobID, requestCompleted)
return
elif err.error == ErrorCode.IN_PROGRESS:
time.sleep(10)
client.get_job_status(err.jobID, requestCompleted)
return
else:
resp += "Error code: %d \nReason: %s \nDetails: %s\n" % (err.error,err.reason)
else:
print(payloadObj)
params = {}
params['url'] = 'https://www.havenondemand.com/sample-content/videos/gb-plates.mp4'
params['source_location'] = 'GB'
hodApp = HODApps.RECOGNIZE_LICENSE_PLATE
client.post_request(params, hodApp, True, callback=asyncRequestCompleted)
Related
I'm trying to play with Petfinder's API, which recommends using curl to get a token key instead of requests. How can I convert their recommended curl code into Requests specific language that works? THe documentations is listed here https://www.petfinder.com/developers/v2/docs/#using-the-api
Recommended curl code:
curl -d "grant_type=client_credentials&client_id={CLIENT-ID}&client_secret={CLIENT-SECRET}" https://api.petfinder.com/v2/oauth2/token
I tried the below (iterating through combos of CLIENT-ID and CLIENT-SECRET, but to no success.
import requests
params = {params = {'CLIENT-ID': XXXXXXXXX,
'CLIENT-SECRET': XXXXXXXX}
}
r = requests.get('https://api.petfinder.com/v2/oauth2/token', params = params)
And I received an error 401 message that indicates that my authorization isn't sufficient.
try like this:
import requests
client_id = ""
client_pass = ""
data = {"grant_type":"client_credentials"}
api_url = "https://api.petfinder.com/v2/oauth2/token"
r = requests.post(api_url,data=data,auth=(client_id,client_pass))
r = r.json()
I want to call a REST api and get some json data in response in python.
curl https://analysis.lastline.com/analysis/get_completed -X POST -F “key=2AAAD5A21DN0TBDFZZ66” -F “api_token=IwoAGFa344c277Z2” -F “after=2016-03-11 20:00:00”
I know of python request, but how can I pass key, api_token and after? What is -F flag and how to use it in python requests?
Just include the parameter data to the .post function.
requests.post('https://analysis.lastline.com/analysis/get_completed', data = {'key':'2AAAD5A21DN0TBDFZZ66', 'api_token':'IwoAGFa344c277Z2', 'after':'2016-03-11 20:00:00'})
-F stands for form contents
import requests
data = {
'key': '2AAAD5A21DN0TBDFZZ66',
'api_token': 'IwoAGFa344c277Z2',
'after': '2016-03-11',
}
response = requests.post('https://analysis.lastline.com/analysis/get_completed', data=data)
-F means make a POST as form data.
So in requests it would be:
>>> r = requests.post('http://httpbin.org/post', data = {'key':'value'})
I'm trying to get the following curl command to work in Python 2.7:
curl --header "Accept: application/vnd.github.korra-preview" --user [username]:[password] https://api.github.com/orgs/myorg/outside_collaborators?per_page=100\&page=1
(basically just gets a list of collaborators from a GitHub organization)
This is utilising the GitHub API v3 - https://developer.github.com/v3/orgs/outside_collaborators/
I've read through the Requests library documentation and can't figure out how to pass BOTH authorisation and custom headers. Does anyone know how to do this?
This is the code I've written so far. How do I include both the auth and varHeaders in the get request?
import requests
varUsername = raw_input("GitHub username:\n")
varPassword = raw_input("GitHub password:\n")
varHeaders = {'Accept':'application/vnd.github.korra-preview'}
#req = requests.get('https://api.github.com/user/repos',auth=(varUsername,varPassword))
req = requests.get('https://api.github.com/orgs/myorg/outside_collaborators?per_page=100\&page=1',auth=(varUsername,varPassword))
print req.status_code
print req.headers
print req.encoding
print req.text
print req.json()
You can add a third parameter, in the form 'headers=varHeaders'
req = requests.get('https://api.github.com/orgs/myorg/outside_collaborators?per_page=100\&page=1',auth=(varUsername,varPassword),headers=varHeaders)
Thanks Brendan for pointing this out!
I have a python program that takes pictures and I am wondering how I would write a program that sends those pictures to a particular URL.
If it matters, I am running this on a Raspberry Pi.
(Please excuse my simplicity, I am very new to all this)
Many folks turn to the requests library for this sort of thing.
For something lower level, you might use urllib2
I've been using the requests package as well. Here's an example POST from the requests documentation.
If you are feeling that you want to use CURL, try PyCurl.
Install it using:
sudo pip install pycurl
Here is an example of how to send data using it:
import pycurl
import json
import urllib
import cStringIO
url = 'your_url'
first_param = '12'
dArrayData = [{'data' : 'first'}, {'data':'second'}]
json_to_send = json.dumps(dArrayData, separators=(',',':'), sort_keys=False)
curlClient = pycurl.Curl()
curlClient.setopt(curlClient.USERAGENT, 'curl-user-agent')
# Sets the url of the service
curlClient.setopt(curlClient.URL, url)
# Sets the request to be of the type POST
curlClient.setopt(curlClient.POST, True)
# Sets the params of the post request
send_params = 'first_param=' + first_param + '&data=' + urllib.quote(json_to_send)
curlClient.setopt(curlClient.POSTFIELDS, send_params)
# Setting the buffer for the response to be written to
bufResponse = cStringIO.StringIO()
curlClient.setopt(curlClient.WRITEFUNCTION, bufResponse.write)
# Setting to fail on error
curlClient.setopt(curlClient.FAILONERROR, True)
# Sets the time out for the connections
curlClient.setopt(pycurl.CONNECTTIMEOUT, 25)
curlClient.setopt(pycurl.TIMEOUT, 25)
response = ''
try:
# Performs the operation
curlClient.perform()
except pycurl.error as err:
errno, errString = err
print '========'
print 'ERROR sending the data:'
print '========'
print 'CURL error code:', errno
print 'CURL error Message:', errString
else:
response = bufResponse.getvalue()
# Do what ever you want with the response.. Json it or what ever..
finally:
curlClient.close()
bufResponse.close()
The requests library is most supported and advanced way to do this.
I'm having trouble understanding how to issue an HTTP POST request using curl from inside of python.
I'm tying to post to facebook open graph. Here is the example they give which I'd like to replicate exactly in python.
curl -F 'access_token=...' \
-F 'message=Hello, Arjun. I like this new API.' \
https://graph.facebook.com/arjun/feed
Can anyone help me understand this?
You can use httplib to POST with Python or the higher level urllib2
import urllib
params = {}
params['access_token'] = '*****'
params['message'] = 'Hello, Arjun. I like this new API.'
params = urllib.urlencode(params)
f = urllib.urlopen("https://graph.facebook.com/arjun/feed", params)
print f.read()
There is also a Facebook specific higher level library for Python that does all the POST-ing for you.
https://github.com/pythonforfacebook/facebook-sdk/
https://github.com/facebook/python-sdk
Why do you use curl in the first place?
Python has extensive libraries for Facebook and included libraries for web requests, calling another program and receive output is unecessary.
That said,
First from Python Doc
data may be a string specifying additional data to send to the server,
or None if no such data is needed. Currently HTTP requests are the
only ones that use data; the HTTP request will be a POST instead of a
GET when the data parameter is provided. data should be a buffer in
the standard application/x-www-form-urlencoded format. The
urllib.urlencode() function takes a mapping or sequence of 2-tuples
and returns a string in this format. urllib2 module sends HTTP/1.1
requests with Connection:close header included.
So,
import urllib2, urllib
parameters = {}
parameters['token'] = 'sdfsdb23424'
parameters['message'] = 'Hello world'
target = 'http://www.target.net/work'
parameters = urllib.urlencode(parameters)
handler = urllib2.urlopen(target, parameters)
while True:
if handler.code < 400:
print 'done'
# call your job
break
elif handler.code >= 400:
print 'bad request or error'
# failed
break