Below is the curl command and wanted to use in python by using request. I am beginner to python. Appreciate advice/help.
curl --header 'Content-Type: text/xml;charset=UTF-8' --data-binary #c:/abcd.xml -X POST http://www.dneonline.com/calculator.asmx
You can use Requests to POST data:
import requests
url = 'http://www.dneonline.com/calculator.asmx'
files = {'c': open('/abcd.xml', 'rb')}
r = requests.post(url, files=files)
Requests is now a defacto standard.
Either use requests module or call it from a shell.
So,
from subprocess import call
call("curl --header 'Content-Type: text/xml;charset=UTF-8' --data-binary #c:/abcd.xml -X POST",shell=True)
Related
i have made a simple python file which want to submit in Livy.Livy is currently running in local mode.Also I have mentioned following property in livy.conf file.
Property name: livy.file.local-dir-whitelist,
value "/usr/local/livy/scripts"
My file is kept in following path "/usr/local/livy/scripts"
import json, pprint, requests, textwrap
host = 'http://localhost:8998'
data = {'kind': 'spark'}
headers = {'Content-Type': 'application/json'}
r = requests.post(host + '/sessions', data=json.dumps(data), headers=headers)
r.json()
I am submitting it using curl as follows:
curl -X POST --data '{"file": "/usr/local/livy/scripts/pi.py"}' -H "Content-Type: application/json" 10.140.178.24:8999/batches
It is giving me following error:
requirement failed: Local path /usr/local/livy/scripts/pi.py cannot be added to user sessions.
My Ubuntu system only have following things:
a)Spark
b)Livy
c)Java
What am I doing wrong here?
For people using incubating mode of livy for first time,kindly check that the template file is renamed with stripping off .template in livy.conf.template.Then make sure that the following configurations are present in it.
livy.spark.master = local
livy.file.local-dir-whitelist = /path/to/script/folder/
Kindly make sure that forward slash is present in end of path
Then write url in following manner for
Python:
curl -v -X POST --data '{"file": "/path/to/script/folder/name-of-python-file.py"}' -H "Content-Type: application/json" localhost:8998/batches
Note:It will not accept relative path,whole absolute path needs to be defined in it.
curl -X POST --data '{"file": "/usr/local/livy/scripts/pi.py"}' -H "Content-Type: application/json" 10.140.178.24:8999/batches
{"id":2,"state":"starting","log":[]}
I am trying to make a post request using curl in python but the below script throws error
import os
first_name1 = "raj"
last_name1 = "kiran"
full_name = "raj kiran"
headline = "astd"
location1 = "USA"
current_company1 = "ss"
curl_req = 'curl -X POST -H "Content-Type: application/json" -d '{"first_name":"{0}","last_name":"{1}","current_company":"{2}","title":"{3}","campus":"","location":"{4}","display_name":"{5}","find_personal_email":"true"}' http://localhost:8090'.format(first_name1,last_name1,current_company1,headline,location1,full_name)
os.popen(curl_req)
Error:
SyntaxError: invalid syntax
How to make above program work?
The problem in your code is the quotes. Change it to:
curl_req = '''curl -X POST -H "Content-Type: application/json" -d '{"first_name":"{0}","last_name":"{1}","current_company":"{2}","title":"{3}","campus":"","location":"{4}","display_name":"{5}","find_personal_email":"true"}' http://localhost:8090'''.format(first_name1,last_name1,current_company1,headline,location1,full_name)
But, as mentioned in the comments, requests will always be a better choice.
Requests syntax:
import requests
post_data = {
# all the data you want to send
}
response = requests.post('http://localhost:8090', data=post_data)
print response.text
One good resource I've used for converting a cURL request to Python requests is curlconverter. You can enter your cURL request and it will format it for Python requests.
As a side note, it can also convert for PHP and Node.js.
Hope that helps!
I'm new on REST API's and I'm unable to make run an http request.
If I try the curl command it works by terminal:
curl \
--request POST \
--header "X-OpenAM-Username: user" \
--header "X-OpenAM-Password: password" \
--header "Content-Type: application/json" \
--data "{}" \
http://openam.sp.com:8095/openamSP/json/authenticate
and the result:
{"tokenId":"AQIC5wM2LY4Sfczw67Mo6Mkzq-srfED3YO8GCSe0Be6wtPs.*AAJTSQACMDEAAlNLABM2NzQ5NjQ4Mjc0MDY0MzEwMDEyAAJTMQAA*","successUrl":"/openamSP/console"}
But now, from my web on Django I want to make a request and I'm unable to make it work, the code that I use it's:
import requests
headers = {'X-OpenAM-Username':'user', 'X-OpenAM-Password':'password', 'Content-Type':'application/json'}
data = {}
r = requests.get('http://openam.sp.com:8095/openamSP/json/authenticate', headers=headers, params=data)
and if I check the answer:
u'{"code":405,"reason":"Method Not Allowed","message":"Method Not Allowed"}'
What I'm doing wrong? I can't see where is my mistake.
Thanks and regards.
You are doing everything correct, except POST method just do this:
r = requests.post('http://openam.sp.com:8095/openamSP/json/authenticate', headers=headers, params=data)
The method URL receives is POST method not GET.
I want to execute a curl command in Python.
Usually, I just need to enter the command in the terminal and press the return key. However, I don't know how it works in Python.
The command shows below:
curl -d #request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere
There is a request.json file to be sent to get a response.
I searched a lot and got confused. I tried to write a piece of code, although I could not fully understand it and it didn't work.
import pycurl
import StringIO
response = StringIO.StringIO()
c = pycurl.Curl()
c.setopt(c.URL, 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere')
c.setopt(c.WRITEFUNCTION, response.write)
c.setopt(c.HTTPHEADER, ['Content-Type: application/json','Accept-Charset: UTF-8'])
c.setopt(c.POSTFIELDS, '#request.json')
c.perform()
c.close()
print response.getvalue()
response.close()
The error message is Parse Error. How to get a response from the server correctly?
For the sake of simplicity, you should consider using the Requests library.
An example with JSON response content would be something like:
import requests
r = requests.get('https://github.com/timeline.json')
r.json()
If you look for further information, in the Quickstart section, they have lots of working examples.
For your specific curl translation:
import requests
url = 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere'
payload = open("request.json")
headers = {'content-type': 'application/json', 'Accept-Charset': 'UTF-8'}
r = requests.post(url, data=payload, headers=headers)
Use curlconverter.com. It'll convert almost any curl command into Python, Node.js, PHP, R, Go and more.
Example:
curl -X POST -H 'Content-type: application/json' --data '{"text":"Hello, World!"}' https://hooks.slack.com/services/asdfasdfasdf
becomes this in Python
import requests
json_data = {
'text': 'Hello, World!',
}
response = requests.post('https://hooks.slack.com/services/asdfasdfasdf', json=json_data)
curl -d #request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere
its Python implementation looks like this:
import requests
headers = {
'Content-Type': 'application/json',
}
params = {
'key': 'mykeyhere',
}
with open('request.json') as f:
data = f.read().replace('\n', '')
response = requests.post('https://www.googleapis.com/qpxExpress/v1/trips/search', params=params, headers=headers, data=data)
Check this link, it will help convert cURL commands to Python, PHP and Node.js
import requests
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere"
data = requests.get(url).json
maybe?
if you are trying to send a file
files = {'request_file': open('request.json', 'rb')}
r = requests.post(url, files=files)
print r.text, print r.json
ahh thanks #LukasGraf now i better understand what his original code is doing
import requests,json
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere"
my_json_data = json.load(open("request.json"))
req = requests.post(url,data=my_json_data)
print req.text
print
print req.json # maybe?
My answer is WRT python 2.6.2.
import commands
status, output = commands.getstatusoutput("curl -H \"Content-Type:application/json\" -k -u (few other parameters required) -X GET https://example.org -s")
print output
I apologize for not providing the required parameters 'coz it's confidential.
I had this exact question because I had to do something to retrieve content, but all I had available was an old version of Python with inadequate SSL support. If you're on an older MacBook, you know what I'm talking about. In any case, curl runs fine from a shell (I suspect it has modern SSL support linked in) so sometimes you want to do this without using requests or urllib.request.
You can use the subprocess module to execute curl and get at the retrieved content:
import subprocess
# 'response' contains a []byte with the retrieved content.
# use '-s' to keep curl quiet while it does its job, but
# it's useful to omit that while you're still writing code
# so you know if curl is working
response = subprocess.check_output(['curl', '-s', baseURL % page_num])
Python 3's subprocess module also contains .run() with a number of useful options.
I use os library.
import os
os.system("sh script.sh")
script.sh literally only contains the curl.
PYTHON 3
Only works within UNIX (Linux / Mac) (!)
Executing a cURL with Python 3 and parsing its JSON data.
import shlex
import json
import subprocess
# Make sure that cURL has Silent mode (--silent) activated
# otherwise we receive progress data inside err message later
cURL = r"""curl -X --silent POST http://www.test.testtestest/ -d 'username=test'"""
lCmd = shlex.split(cURL) # Splits cURL into an array
p = subprocess.Popen(lCmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate() # Get the output and the err message
json_data = json.loads(out.decode("utf-8"))
print(json_data) # Display now the data
Sometimes you also need to install these dependencies on UNIX if you experience strange errors:
# Dependencies
sudo apt install libcurl4-openssl-dev libssl-dev
sudo apt install curl
use requests lib.. this code is :
curl -LH "Accept: text/x-bibliography; style=apa" https://doi.org/10.5438/0000-0C2G
equal to this:
import requests
headers = {
'Accept': 'text/x-bibliography; style=apa',
}
r = requests.get('https://doi.org/10.5438/0000-0C2G', headers=headers)
print(r.text)
if you os supporting curl you can do something like this:
import os
os.system("curl -d #request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere")
I'm using this way... And I think you can use this too!
by the way.. the module "os" is auto-installing when you install python.
soo, you don't need to install packages ;)
This is one approach:
Import os
import requests
Data = os.execute(curl URL)
R= Data.json()
I'm using Python requests module, but whatever I've tried to upload image, it succeeds, but image has errors when opening/reading.
I encode the image as base64, set content-type headers (image/png, image/jpeg etc...) etc...
Anyhow, I do the following using CURL and it works:
curl -u test#test.ca:test -H 'Content-Type: image/jpeg' --data-binary #test.jpeg -X POST 'https://test.test.com/api/upload.json?filename=test.jpeg'
What would be the equivalent of this request with the requests module in python (headers etc...)?
To reproduce your curl command, you don't need to encode the image in base64: --data-binary #test.jpeg curl option sends test.jpeg file as is:
import requests
r = requests.post('https://example.com/api/upload.json?filename=test.jpeg',
data=open('test.jpeg', 'rb'),
headers={'Content-Type': 'image/jpeg'},
auth=('test#test.ca', 'test')) # username, password
headers = {'Content-Type' : 'image/jpeg'}
params = {'filename' : 'test.jpg'}
r = requests.post("https://test.test.com/api/upload.json",
auth=('user','pw'), headers=headers, params=params)