difference between curl and python requests - python

I am trying to access my firewall API.
and i got a good answer in curl with:
curl -k -i -u admin:xxxx -X POST https://10.0.0.2:9443/api/sonicos/auth
#=> Ok
with requests, api said HTTP 406
here is my code:
import requests
from requests.auth import HTTPBasicAuth
r = requests.post(
'https://10.0.0.2:9443/api/sonicos/auth',
auth=HTTPBasicAuth('admin', 'xxxx'),
headers={'Content-type': 'Application/JSON'},
verify=False
)
API documentation said: 406 Not acceptable
Mime-type in content-type not supported.
I try a lot of parameters without success.
Any idea to help me?
Thanx

As far as I know, and according to the RFC 2045, the content type should be lowercase. In your case, "'Content-type': 'application/json'"

Related

How to pass oauth token in requests without specifying client id as passed in curl?

I am trying to port this
curl -L -u 12343434343:x-oauth-basic https://github.com/company/myproj-config/archive/master.zip --output pcfg.zip
in python-requests
All options suggested in requests docs or requests-oauthlib docs mandates passing client-id
Is there a way to achieve what I could do with curl above using requests without passing client-id ?
ok, I managed to find the answer if anyone is interested in
request = requests.get(http_url,
headers={
"Authorization": "token " + github_token,
"Accept": "application/vnd.github.v3.raw"
})

How to covert curl into a python code with native library 2.7

How do i convert the below curl into python code.
I am confused on how to include the api key, i know what value it should be.
The python code must only contain native libraries
curl -G -H "api_key: YOUR_API_KEY" https://api.semantics3.com/test/v1/products --data-urlencode 'q={"search":"apple iphone"}'
Thanks
Daniel
The easiest and convenient way is to use requests library in python.
Just import the requests library and you can do all REST operations
Example:-
>>> r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
>>> r.status_code
200
>>> r.headers['content-type']
'application/json; charset=utf8'
>>> r.encoding
'utf-8'
>>> r.text
u'{"type":"User"...'
>>> r.json()
{u'private_gists': 419, u'total_private_repos': 77, ...}
Please follow below guide. Very convenient to use.
http://docs.python-requests.org/en/master/
i am going to use the requests library.
I can send the request
but i caannot send the same api key that works when i curl as it comes with an error message invalid api
the python code... which throws up invalid api key error despite using the same key as curl code
import requests
payload = {'api_key:SEM3DC0261ECC65764A9F8B2B8008F16XXXX' 'q': {'search', 'apple iphone'}}
r = requests.get('https://api.semantics3.com/test/v1/products ', params=payload)
print(r.url)
print(r.text)
curl code which works fine
curl -G -H "api_key: SEM3DC0261ECC65764A9F8B2B8008F16XXXX" https://api.semantics3.com/test/v1/products --data-urlencode 'q={"search":"apple iphone"}'
The api keys are partially blanked out
What can i do?
Thanks Daniel

Transform cURL command to Python Requests command

I'm new with cURL and Requests and I have a doubt on how I can transform a cURL petition to a Requests command in Python.
Looking at Apache Stratos documentation Doc Page to perform a login against the server, in cURL you use:
curl -X GET -H "Content-Type: application/json" -k -v -u admin:admin https://localhost:9443/api/session
And it works on the terminal. Now, I want to do the same on my Django website and to transform the curl URL to python code and use the module "requests" I don't know how pass the user and pass info on the petition.
The code that I have now it's:
headers = {'Content-Type':'application/json'}
data = {}
req = requests.post('https://localhost:9443/api/session', headers=headers, params=data)
But I don't know how pass the user and password so I tried this (Requests Python Login Tutorial)
data = {"username":"admin","password":"admin"}
But I get a certificate error from server:
File "/usr/lib/python2.7/dist-packages/requests/adapters.py", line 385, in send raise SSLError(e)
requests.exceptions.SSLError: [Errno 1] _ssl.c:510: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
So, I'm sending correctly the user and password? How I can solve the certificate error?
Thanks and regards
You can turn off SSL cert verification with the verify flag, and use basic authentication by specifying auth.
from requests.auth import HTTPBasicAuth
req = requests.post('https://localhost:9443/api/session', headers=headers, auth=HTTPBasicAuth('admin', 'admin'), verify=False)
See the requests docs for more info.
You are using your localhost which almost certainly doesn't have a valid certificate.
For testing purposes disable ssl verification (it is still encrypted just not verifying certificate)
req = requests.post('https://localhost:9443/api/session', headers=headers, params=data, verify=False)
After the #Sam solution and looking on the Requests Auth Doc Page I found the solution:
The Python Resquest code it's:
requests.get('https://localhost:9443/api/session', headers=headers, auth=HTTPBasicAuth('admin', 'admin'), verify=False)
The "params" field it's not needed.
And then:
u'{"Success":{ "sessionId": "547D78FD4966DDBE21AEFDAECE909DEC"}}'
Hope it helps someone!

Rest API authentication and access using Python Requests

I have been regularly accessing an API at work using curl. But now i need to do a bit of automation for the same.
Was trying to translate what i do with curl into python using the requests module.
But I keep receiving a 401 error.
My curl requests that i regularly are as below:
Step1: Session Authentication with cookies:
curl -b cookies -c cookies -v -X POST -H "Content-Type: application/json" --data-binary '{"auth":{"username":"aaa","password":"bbb"}}' http://api.xyz.at/auth
Step2: Access API URL for data retrieval
curl -b cookies -c cookies http://api.xyz.at/somepage?per_id=556677
Now using Python Requests, here is what I am doing
Step1: For Authentication
username = 'aaa'
password = 'bbb'
s = requests.Session()
s.post('http://api.xyz.at/auth',auth=('username','pasword'))
This "i think" works fine, and give me the below response
<Response [200]>
Step2: Access API URL for data retrieval
s.get('http://api.xyz.at/somepage?per_id=556677')
but this Step 2 keeps returning an error
<Response [401]>
The code is failing and not sure where.
My Python skills are visibly pedestrian. I have been looking at the Requests website. But unfortunately haven't been able to decipher.
Guidance would be appreciated :)
import urllib2, urllib
url = 'http://api.xyz.at/auth'
pm = urllib2.HTTPPasswordMgrWithDefaultRealm()
pm.add_password(None, url, 'user', 'password')
auth = urllib2.HTTPBasicAuthHandler(pm)
opener = urllib2.build_opener(auth)
urllib2.install_opener(opener)
request = urllib2.Request('http://api.xyz.at/somepage?per_id=556677', None)
handler = urllib2.urlopen(request)
handler.read()
Since you are getting a 401 error I guess you are not passing the authentication token which you get as response from login API. Use the same auth token to perform other options - Get-post-Delete.

sending data parameters to rest api using python-requests

I am trying to call rest api by sending json data. The curl command is pretty straight forward but only problem that I am facing is with "--data" parameter.
For curl, the data is sent as follows:
curl -X POST -H <headers> --data 'params={...}' <url>
I am not able to figure out how to send the --data parameter with the name 'params='attached to it using python-requests.
Also while making GET requests, there are a lot of options which I have to send along with the curl requests(-O ,-J, -v, -G,-L).
I wanted to know how to supply these additional parameters using python-requests.
Thanks.
curl is a very rich library that has gone far way after a lot of developments in last decades. Compare to the curl, python's requests library is still a baby. So you can not expect all the functionalities of curl in requests. You'll only get the major functionalities of curl in your requests.
Now come to your question. If you want to send the json data through a variable, then the basic POST operation(content-type application/x-www-form-urlencoded) will do.
payload = {'params': json_string}
r = requests.post("http://url/post", data=payload)
But if you want to POST the data as json object with header content-type as json, then you have to use this
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json_string, headers=headers)
In Curl the param -L means for following the redirection. You can achieve it with allow_redirects=True parameter:
r = requests.post(url, data=json_string, headers=headers, allow_redirects=True)
Help yourself to find your needs from the requests document.

Categories

Resources