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()
Related
I'm trying to refresh a dataflow using python. It is working for me in Powershell. I'm not sure if I'm using Python correctly. Using Python, I'm able to do get method working correctly.
Python (get method :-> working)
import requests
groupID = <groupid>
#url = 'https://api.powerbi.com/v1.0/myorg/capacities'
header = {'Authorization': f'Bearer {access_token}','Content-Type':'application/json'}
datasets_request_url = 'https://api.powerbi.com/v1.0/myorg/groups/' + groupID + '/datasets'
response = requests.get(url=datasets_request_url, headers=header)
Python failing (POST Method)
dataflowid = <dataflowid>
dataflowrefresh_url = 'https://api.powerbi.com/v1.0/myorg/groups/' + groupID + '/dataflows/'+dataflowid+'/refreshes'
response = requests.post(url=dataflowrefresh_url, headers=header)
HTTPError: 400 Client Error: Bad Request for url:
PowerShell (POST method working)
$workspaceid = <groupid>
$dataflowid = <dataflowid>
$uri = "https://api.powerbi.com/v1.0/myorg/groups/$workspaceid/Dataflows/$dataflowid/refreshes"
# Build JSON, convert back and forth as we're just defining it as a string.
$json = '{"notifyOption": "MailOnFailure"}' | ConvertFrom-Json
$body = $json | ConvertTo-Json
# Refresh the dataflow
Invoke-RestMethod -Uri $uri -Headers $authHeader -body $body -Method POST -Verbose
If I remove the parameter $body, it fails with error 400. I don't know how to convert the working Powershell api call to Python.
Used the same token generated by below code. POST method worked in Powershell but not in Python, GET worked in both.
context = adal.AuthenticationContext(authority=authority_url,
validate_authority=True,
api_version=None)
token = context.acquire_token_with_client_credentials(resource_url, client_id, client_secret)
access_token = token.get('accessToken')
url = 'https://api.powerbi.com/v1.0/myorg/groups/' + workspaceID + '/dataflows/' +dataflowid+ '/refreshes'
payload= {'refreshRequest': 'y'}
data = json.dumps(payload)
headers = header
response = requests.request("POST", url, headers=headers, data=data)
Using refreshRequest : 'Y' made it work. In powershell, I didn't have to give this parameter.
Trying to get the access token in response for google but can't figure out what I'm doing wrong.
This is what I've done so far:
import requests
authorization_code_req = {
'client_id':'key',
'client_secret':'key',
'redirect_uri':'http://localhost:5000',
'grant_type':'authorization_code'}
r = requests.get('https://accounts.google.com/o/oauth2/token',
params=authorization_code_req)
print (r)
you should send authorization_code_req as json and not as params. So your code should look something like this:
import requests
authorization_code_req = {
'client_id':'key',
'client_secret':'key',
'redirect_uri':'http://localhost:5000',
'grant_type':'authorization_code'
}
r = requests.get('https://accounts.google.com/o/oauth2/token',
json=authorization_code_req)
print(r)
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 need to implement the following curl:
curl -k https://somelinkhere/get_info -d auth_info='{"session_id":"blablablaidhere"}' -d params='{"id":"12345"}'
Currently I have the following code. It is working, but not exactly as I need. I need to get json content from the reply, just one parameter.
url = 'https://somelinkhere/get_info'
data = {'auth_info':'{"session_id":"blablablaidhere"}', 'params':'{"id":"12345"}'}
response = requests.post(url, data=data)
res = response.content
print res
Now it returns
'�Z[o�6�+���֖���ې�0�{h�`
AK�M�"����o�9�dI���t��#RI<��"�GD�D��.3MDeN��
��hͣw�fY)SW����`0�{��$���L��Zxvww����~�qA��(�u*#��݅Pɣ����Km���'
etc.
What i need is to output
res['balance_info']['balance']
If i launch cURL (provided above) from a command line, i have the following:
{"balance_info":{"enabled":"Y","balance":"0.55000","out_date_format":"MM-DD-YYYY","password":"12345","blocked":"N"
But do not know how to get this parameter using python script
As in documentation,content property gives the binary version of response.
You'll need to get the decoded version of request using .text then load it as json.
response = requests.post(url, data=data)
#load it as json
item = json.loads(response.text)
And now you can access your keys as:
response['balance_info']['balance']
What you get is a Gziped JSON string.
You have to decompress before reading json. Then you can use the response as a python dict.
Something like res = json.loads(zlib.decompress(response.content))
Here is an example using Requests:
>>> import requests
>>> r = requests.post('https://somelinkhere/get_info',
data = {"id": "12345"})
See also the documentation to install Requests on your virtualenv.
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)