how do I use requests for the below API calls? - python

below is my code for calling the GitHub api via curl with python, how do I stop using curl and use the requests library to make the API calls? I'm just confused on how calling the below api endpoints will look like when using requests.
def api_request(self):
api_key = sys.argv[0]
organization = sys.argv[1]
print("------------------------------------------People with 2FA Disabled-----------------------------------------------")
comm = 'curl -v "https://api.github.com/orgs/"{}"/members?filter=2fa_disabled" -H "Authorization: bearer {}"'.format(organization, api_key)
os.system(comm)
print("-----------------------------------------Collaborators being listed----------------------------------------------")
comm2 = 'curl -v "https://api.github.com/orgs/"{}"/outside_collaborators" -H "Authorization: bearer {}"'.format(organization, api_key)
os.system(comm2)
print("-----------------------------------------Members and data Being listed----------------------------------------------")
comm3 = 'curl -v "https://api.github.com/orgs/"{}"/members" -H "Authorization: bearer {}"'.format(organization, api_key)
os.system(comm3)

import requests
import urllib.request
import io
api_key = sys.argv[0]
organization = sys.argv[1]
url="https://api.github.com/orgs/"{}"/members?filter=2fa_disabled" -H "Authorization: bearer {}".format(organization, api_key)
response = requests.get(url).content
depending of the format of the answer, you can then try
import pandas
df=pandas.read_csv(io.StringIO(response.decode('utf-8')))

I'm just confused on how calling the below api endpoints will look
like when using requests.
Something like:
import requests
import sys
import os
def api_request(self):
api_key = sys.argv[0]
organization = sys.argv[1]
print("------------------------------------------People with 2FA Disabled-----------------------------------------------")
requests.get("https://api.github.com/orgs/{}/members?filter=2fa_disabled".format(organization), auth=('bearer', api_key))

Here is the example which might help you:
responseAPI1 = requests.post('URL',json=data,auth = ('username','password'))
OR
headers = {
'X-ABC-API-ID': 'x-x-x-x-x',
'X-ABC-API-KEY': 'nnnnnnnnnnnnnnnnnnnnnnn',
'X-DE-API-ID': 'x',
'X-DE-API-KEY': 'nnnnnnnnnnnnnnnnnnnnnnnn'
}
r = requests.get('https://www.somecompany.com/api/v2/groups/', headers=headers)

Related

Curl requests in python

I have a curl request like this:
curl -X POST http://mdom-n-plus-1.nonprod.appsight.us:8081/mesmerdom/v3/getByImageAndDom -F "data=$DATA" -F "dom=#$DOM" -F "image=#$IMG"
I am trying to convert it to python by using something like this:
import requests
import json
url = "http://mdom-n-plus-1.nonprod.appsight.us:8081/mesmerdom/v1/getByScreen"
payload = {"data": json.dumps({"screen":["screen-id", "57675"]}), dom:"abc", image:"xyz"}
req = requests.post(url, data=payload)
print (req.text)
but it is not working.

Convert cURL to Python - Upload A File

I can't seem to convert cURL to python. From the docs:
curl -i --upload-file ~/Desktop/Myimage.jpg -H 'Authorization: Bearer Redacted' "https://api.linkedin.com/mediaUpload/C5522AQHn46pwH96hxQ/feedshare-uploadedImage/0?ca=vector_feedshare&cn=uploads&m=AQLKRJOn_yNw6wAAAW2T0DWnRStny4dzsNVJjlF3aN4-H3ZR9Div77kKoQ&app=1983914&sync=0&v=beta&ut=1Dnjy796bpjEY1
I have tried using files instead of data to no avail.
The current code below creates the proper response 201, but it's blank (has no JSON details with an image to use for future API calls). Let me what changes I need to make to upload a file via a PUT request without using a multi-part form (ie "files=")
uploadUrl = data["value"]["uploadMechanism"]["com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest"]["uploadUrl"]
filename = "ffadfads.jpeg"
media_url = "https://1000logos.net/wp-content/uploads/2017/03/LinkedIn-Logo.png"
request = requests.get(media_url, stream=True)
if request.status_code == 200:
with open(filename, 'wb') as image:
for chunk in request:
image.write(chunk)
#files = {'fileupload': open(filename)}
files = {"fileupload":(filename,open(filename,"rb"),'application-type')}
image_headers = {
'Accept': 'image/jpeg,image/png,image/gif',
'Authorization': 'Bearer ' + real_token
}
response = requests.request("PUT", uploadUrl, data=open(filename,"rb"), headers=image_headers)
print response
print response.text
print response.json()
Try not to confuse a request with a response.
response1 = requests.get(media_url, stream=True)
if response1.status_code == 200:
response2 = requests.request("PUT", uploadUrl,
data=response1.iter_content(),
headers=image_headers)
If you are not bound to use the requests library, you could try running the curl command directly from python, using subprocess.run() and shlex.split() for Python 3.
Using the example curl command from your question (adding a missing double quote at the end) the following code would run it and capture the response as text.
import shlex
import subprocess
curl_command_line = '''curl -i --upload-file ~/Desktop/Myimage.jpg \
-H 'Authorization: Bearer Redacted' \
"https://api.linkedin.com/mediaUpload/C5522AQHn46pwH96hxQ/feedshare-uploadedImage/0?ca=vector_feedshare&cn=uploads&m=AQLKRJOn_yNw6wAAAW2T0DWnRStny4dzsNVJjlF3aN4-H3ZR9Div77kKoQ&app=1983914&sync=0&v=beta&ut=1Dnjy796bpjEY1"'''
args = shlex.split(curl_command_line)
response = subprocess.run(args, capture_output=True, text=True).stdout
For Python 2.7, replace the last line with:
response = subprocess.call(args)

how to assign variable value in python in terminal commands?

My code:
import os
from xml.dom import minidom
doc = minidom.parse("jobs.xml")
job = doc.getElementsByTagName("job")[0]
id = job.getElementsByTagName("id")[0]
name = job.getElementsByTagName("name")[0]
id_data = id.firstChild.data
name_data = name.firstChild.data
os.system('curl --compressed -H "Accept: application/xml" -X GET "http://localhost:19888/ws/v1/history/mapreduce/jobs/"')
>>> /home/ankit/rrd-xml/task.xml
I want to get the commands like
os.system('curl --compressed -H "Accept: application/xml" -X GET "http://localhost:19888/ws/v1/history/mapreduce/jobs/< variable value of name_data >"')
>>> /home/ankit/rrd-xml/task.xml
How can i do it in python itself?
Use single quotes around the command, or even triple quotes, so that the quotes that form part of the command are not confused with the Python string:
os.system('curl --compressed -H "Accept: application/xml" -X GET "http://localhost:19888/ws/v1/history/mapreduce/jobs/{}" >> /home/ankit/rrd-xml/task.xml'.format(name_data))
That will work, but it's not the best. It would be better for you to use Python to make the HTTP request. requests is a good module for this:
import requests
url = 'http://localhost:19888/ws/v1/history/mapreduce/jobs/{}'.format(name_data)
headers = {'Accept': 'application/xml'}
response = requests.get(url, headers=headers)
with open('/home/ankit/rrd-xml/task.xml', 'a') as outfile:
outfile.write(response.content)
This code will GET the URL, setting the Accept header to application/xml and append the response to the file. Compression is requested by default.
What you want is a simple string formatting.
import os
from xml.dom import minidom
doc = minidom.parse("jobs.xml")
job = doc.getElementsByTagName("job")[0]
id = job.getElementsByTagName("id")[0]
name = job.getElementsByTagName("name")[0]
id_data = id.firstChild.data
name_data = name.firstChild.data
url = 'http://localhost:19888/ws/v1/history/mapreduce/jobs/{name}'.format(name=name_data)
cmd = 'curl --compressed -H "Accept: application/xml" -X GET "{url}"'.format(url=url)
os.system(cmd)
Use subprocess. The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using the os.system function.
import subprocess
import shlex
command = shlex.split('curl --compressed -H "Accept: application/xml" -X GET http://localhost:19888/ws/v1/history/mapreduce/jobs/')
with open('/home/ankit/rrd-xml/task.xml', 'a') as f:
subprocess.Popen(command, stdout=f)

Why does this Translation of Curl into Python requests fail? [duplicate]

I'm trying to convert the following working request in curl to a python request (using Requests).
curl --data 'query={"tags":["test1","test2"]}' http://www.test.com/match
(I've used a fake url but the command does work with the real url)
The receiving end (ran in Flask) does this:
#app.route("/match", methods=['POST'])
def tagmatch():
query = json.loads(request.form['query'])
tags = query.get('tags')
# ... does stuff ...
return json.dump(stuff)
In curl (7.30), ran on Mac OS X (10.9) the command above properly returns a JSON list that's filtered using the tag query.
My Python script is as follows, it returns a 400 Bad Request error.
import requests
payload = {"tags":["test1", "test2"]}
# also tried payload = 'query={"tags":["test1","test2"]}'
url = 'http://www.test.com/match'
r = requests.post(url, data=payload)
if __name__=='__main__':
print(r.text)
There is an open source cURL to Python Requests conversion helper at https://curlconverter.com/. It isn't perfect, but helps out a lot of the time. Especially for converting Chrome "Copy as cURL" commands. There is also a node library if you need to do the conversions programmatically
Your server is expecting JSON, but you aren't sending it. Try this:
import requests
import json
payload = {'query': json.dumps({"tags":["test1", "test2"]})}
url = 'http://www.test.com/match'
r = requests.post(url, data=payload)
if __name__=='__main__':
print r.text
Save your life
A simpler approach would be:
Open POSTMAN
Click on the "import" tab on the upper left side.
Select the Raw Text option and paste your cURL command.
Hit import and you will have the command in your Postman builder!
Hope this helps!
credit: Onkaar Singh
Try to use uncurl library. It is pretty nice to do its job. I've tried it.
u = uncurl.parse(
"curl -X GET 'https://mytesturl.com/' -H 'accept: application/json' -H 'Authorization: 1234567890'")
print(u)
It prints,
requests.get("https://mytesturl.com/",
headers={
"Authorization": "1234567890",
"accept": "application/json"
},
cookies={},
)
try this:
https://github.com/spulec/uncurl
import uncurl
print uncurl.parse("curl 'https://pypi.python.org/pypi/uncurl' -H
'Accept-Encoding: gzip,deflate,sdch'")
I wrote an HTTP client plugin for Sublime Text called Requester, and one of its features is to convert calls to cURL to Requests, and vice versa.
If you're using Sublime Text this is probably your fastest, easiest option. If not, here's the code that actually handles the conversion from cURL to Requests. It's based uncurl, but with various improvements and bug fixes.
import argparse
import json
try:
from urllib.parse import urlencode, parse_qsl
except ImportError: # works for Python 2 and 3
from urllib import urlencode
from urlparse import parse_qsl
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('command')
parser.add_argument('url')
parser.add_argument('-X', '--request', default=None)
parser.add_argument('-d', '--data', default=None)
parser.add_argument('-G', '--get', action='store_true', default=False)
parser.add_argument('-b', '--cookie', default=None)
parser.add_argument('-H', '--header', action='append', default=[])
parser.add_argument('-A', '--user-agent', default=None)
parser.add_argument('--data-binary', default=None)
parser.add_argument('--compressed', action='store_true')
parsed_args = parser.parse_args()
method = 'get'
if parsed_args.request:
method = parsed_args.request
base_indent = ' ' * 4
post_data = parsed_args.data or parsed_args.data_binary or ''
if post_data:
if not parsed_args.request:
method = 'post'
try:
post_data = json.loads(post_data)
except ValueError:
try:
post_data = dict(parse_qsl(post_data))
except:
pass
cookies_dict = {}
if parsed_args.cookie:
cookies = parsed_args.cookie.split(';')
for cookie in cookies:
key, value = cookie.strip().split('=')
cookies_dict[key] = value
data_arg = 'data'
headers_dict = {}
for header in parsed_args.header:
key, value = header.split(':', 1)
if key.lower().strip() == 'content-type' and value.lower().strip() == 'application/json':
data_arg = 'json'
if key.lower() == 'cookie':
cookies = value.split(';')
for cookie in cookies:
key, value = cookie.strip().split('=')
cookies_dict[key] = value
else:
headers_dict[key] = value.strip()
if parsed_args.user_agent:
headers_dict['User-Agent'] = parsed_args.user_agent
qs = ''
if parsed_args.get:
method = 'get'
try:
qs = '?{}'.format(urlencode(post_data))
except:
qs = '?{}'.format(str(post_data))
print(post_data)
post_data = {}
result = """requests.{method}('{url}{qs}',{data}\n{headers},\n{cookies},\n)""".format(
method=method.lower(),
url=parsed_args.url,
qs=qs,
data='\n{}{}={},'.format(base_indent, data_arg, post_data) if post_data else '',
headers='{}headers={}'.format(base_indent, headers_dict),
cookies='{}cookies={}'.format(base_indent, cookies_dict),
)
print(result)
You could make a script with this code, e.g. curl_to_request.py, and call this script from the command line like so. It will work for both Python 2 and Python 3.
python curl_to_request.py curl -X POST -d 'key2=value2&key1=value1' 'http://httpbin.org/post'
python curl_to_request.py curl -X POST -H 'Content-Type: application/json' -d '{"key2": "value2", "key1": "value1"}' 'http://httpbin.org/post'
python curl_to_request.py curl -X POST -H 'Content-Type: application/json' -d '[1, 2, 3]' 'http://httpbin.org/post'
python curl_to_request.py curl -X POST -H 'Content-Type: application/json' -d '{"name": "Jimbo", "age": 35, "married": false, "hobbies": ["wiki", "pedia"]}' 'http://httpbin.org/post'
python curl_to_request.py curl -X GET 'http://httpbin.org/get?key2=value2&key1=value1'
python curl_to_request.py curl -X GET -H 'key1: value1' -H 'key2: value2' 'http://httpbin.org/headers'
python curl_to_request.py curl -X GET -b 'key1=value1;key2=value2' 'http://httpbin.org/cookies'
From your code using requests and in Flask, it seems like you don't post the right data format. The payload should be like this:
payload = {'query': {'tags': ['test1', 'test2']},}
This seems not normal as post data when using requests.post(). So if you have posted the html form here, it may have been more clear to solve the problem.
Here is another similar question: Using Python Requests to pass through a login/password

Why do I get 'internal error' from Paypal using this call in Django?

I have a request that gets PayPal authentication. It is written in Curl and it works perfectly. Trying to rewrite it in Python leads to an error response(500000 internal error). Can anyone please direct me on how I would rewrite it or correct my existing code.
CURL
curl -s --insecure -H "X-PAYPAL-SECURITY-USERID: <user_id>" -H "X-PAYPAL-SECURITY-PASSWORD: <user_password>" -H "X-PAYPAL-SECURITY-SIGNATURE: <user_signature>" -H "X-PAYPAL-REQUEST-DATA-FORMAT: JSON" -H "X-PAYPAL-RESPONSE-DATA-FORMAT: JSON" -H "X-PAYPAL-APPLICATION-ID: APP-80W284485P519543T" https://svcs.sandbox.paypal.com/Permissions/RequestPermissions -d "{\"scope\":\"EXPRESS_CHECKOUT\", \"callback\":\"<callback_url>", \"requestEnvelope\": {\"errorLanguage\":\"en_US\"}}"
PYTHON
import settings
import urllib
import urllib2
from django.utils import simplejson
def home(request):
headers = {
"X-PAYPAL-SECURITY-USERID": settings.USERNAME,
"X-PAYPAL-SECURITY-PASSWORD": settings.PASSWORD,
"X-PAYPAL-SECURITY-SIGNATURE": settings.SIGNATURE,
"X-PAYPAL-REQUEST-DATA-FORMAT": "JSON",
"X-PAYPAL-RESPONSE-DATA-FORMAT": "JSON",
"X-PAYPAL-APPLICATION-ID": "APP-80W284485P519543T"
}
data = {"scope":"EXPRESS_CKECKOUT", callback":"http://www.example.com/success.html", "requestEnvelope": {"errorLanguage":"en_US"}}
req = urllib2.Request("https://svcs.sandbox.paypal.com/Permissions/RequestPermissions/", simplejson.dumps(data), urllib.urlencode(data), headers)
res = urllib2.urlopen(req).read()
typo in "EXPRESS_CKECKOUT" instead of "EXPRESS_CHECKOUT" and third argument urllib.urlencode(data) for urllib2.Request is not required.
data = {"scope":"EXPRESS_CHECKOUT", "callback":"http://www.example.com/success.html", "requestEnvelope": {"errorLanguage":"en_US"}}
req = urllib2.Request("https://svcs.sandbox.paypal.com/Permissions/RequestPermissions/", simplejson.dumps(data), headers)
res = urllib2.urlopen(req).read()

Categories

Resources