How pass option of curl in request in python? - python

As the answer and comment in https://stackoverflow.com/a/31764155/10189759
suggest that everything could be done using a curl could be done using python request.
My question is how to pass option like -u -i to the request function?
For example in this tutorial github api
curl -i -u your_username:your_token https://api.github.com/user
How could I use request to pass my args and option to the url?

You can do it like this:
import requests
response = requests.get('https://api.github.com/user', auth=('your_username', 'your_token'))

Related

How to run cURL request using python

I would like to know how to run the following cURL request using python (I'm working in Jupyter notebook):
curl -i -X GET "https://graph.facebook.com/{graph-api-version}/oauth/access_token?
grant_type=fb_exchange_token&
client_id={app-id}&
client_secret={app-secret}&
fb_exchange_token={your-access-token}"
I've seen some similar questions and answers suggesting using "requests.get", but I am a complete python newbie and am not sure how to structure the syntax for whole request including the id, secret and token elements. Any help would be really appreciated.
Thanks!
no need to use curl. use the below
import requests
graph_api_version = 'a'
app_id = 'b'
app_secret = 'c'
your_access_token = 'd'
url = f"https://graph.facebook.com/{graph_api_version}/oauth/access_token?grant_type=fb_exchange_token&client_id={app_id}&client_secret={app_secret}&fb_exchange_token={your_access_token}"
r = requests.get(url)
Convert your Curl request to Python instantly here :
https://curl.trillworks.com/
you can use some lib that run commands in python like subprocess. for example: subprocess.run(["curl", "google.com"])

How do parse a curl PUT request in Flask-RESTful?

How do I save the data uploaded using a curl command like curl localhost:5000/upload/test.bin --upload-file tmp/test.bin in a Flask-RESTful PUT handler method?
The code in Ron Harlev's answer to Flask-RESTful - Upload image works with the POST request from curl -F "file=#tmp/test.bin" localhost:5000/upload/test.bin (slightly modified below):
def post(self, filepath):
parse = reqparse.RequestParser()
parse.add_argument('file', type=werkzeug.datastructures.FileStorage, location='files')
args = parse.parse_args()
upload_file = args['file']
upload_file.save("/usr/tmp/{}".format(filepath))
return ({'filepath': filepath}, 200)
But if I try to use the code to handle the PUT request from curl --upload-file (changing post to put above, of course) I get: "'NoneType' object has no attribute 'save'". This refers to the second-last line in the above code.
How do I get a handle to the file data uploaded using curl --upload-file, so I can save it to a local file?
Update: This works around the problem: curl --request PUT -F "file=#tmp/test.bin" localhost:5000/upload/test.bin, but I still don't have an answer to my question.
curls docs define --upload-file as a PUT http request https://curl.haxx.se/docs/manpage.html#-T.
I'm not sure of the need to handle this through a restful API and I'm pretty sure that's where curl is causing problems, perhaps the assumption that this must be done through flask-restful is holding you back?
maybe try building this as a vanilla flask endpoint instead, this code should work for you.
from flask import Flask, request, jsonify
...
#app.route('/simpleupload/<string:filepath>', methods=['POST','PUT'])
def flask_upload(filepath):
with open("/tmp/{}".format(filepath), 'wb') as file:
file.write(request.stream.read())
return (jsonify({'filepath': filepath}), 200)

Run a curl tlsv1.2 http get request in python?

I have the following command that I run using curl in linux.
curl --tlsv1.2 --cert ~/aws-iot/certs/certificate.pem.crt --key ~/aws-iot/certs/private.pem.key --cacert ~/aws-iot/certs/root-CA.crt -X GET https://data.iot.us-east-1.amazonaws.com:8443/things/pi_3/shadow
This command returns JSON text that I want. However I want to be able to run the above command in Python3. I do not know what library to use in order to get the same JSON response.
P.S. I replace "data" with my account number in AWS to get JSON
After playing around with it on my own I was able to successfully do it in python using the requests library.
import requests
s = requests.Session()
r = s.get('https://data.iot.us-east-1.amazonaws.com:8443/things/pi_3/shadow',
cert=('/home/pi/aws-iot/certs/certificate.pem.crt', '/home/pi/aws-iot/certs/private.pem.key', '/home/pi/aws-iot/certs/root-CA.crt'))
print(r.text)

How to use urllib2 when users only have a API token?

how would i tranfoms this curl command:
curl -v -u 82xxxxxxxxxxxx63e6:api_token -X GET https://www.toggl.com/api/v6/time_entries.json
into urlib2?
I found this tutorial: http://www.voidspace.org.uk/python/articles/authentication.shtml
but they use a password and username. I can only use an API token.
Thank you.
see also this question:
Urllib2 raises 403 error while the same request in curl works fine
urllib2 is known to suck big time when it comes to authentication. To save some kitten lifes you should use http://docs.python-requests.org/en/latest/index.html

Sending data in a POST message to a RESTful web service

I need to send some JSON data in a POST message to a RESTful webservice.
Which python module should I be using for this? Is there some sample code I can refer to?
Which bit are you having trouble with? The JSON, or the POST?
For JSON, the json module has been included in Python since version 2.5. Just do json.dumps(my_data) to convert a data variable to JSON.
For the POST, there are various modules in the standard library, but the best bet is to install the third-party requests library.
Requests is probably the best library for the job. It certainly beats urllib and urllib2. You can get it and see an example at http://pypi.python.org/pypi/requests
or you can just install it with "pip install requests"
There's a few more examples using the Github API with both the requests library and others at https://github.com/issackelly/Consuming-Web-APIs-with-Python-Talk
here is what I've used for post and get requests
import httplib
connection = httplib.HTTPConnection('192.168.38.38:6543')
body_content = 'abcd123456xyz'
connection.request('POST', '/foo/bar/baa.html', body_content)
postResult = connection.getresponse()
connection.request('GET', '/foo/bar/baa.html')
response = connection.getresponse()
getResult = response.read()
It does same as this sequence of CLI commands:
curl -X POST -d "abcd123456xyz" 192.168.38.38:6543/foo/bar/baa.html
curl 192.168.38.38:6543/foo/bar/baa.html

Categories