python curl for assembla - python

I am trying to port the following curl call into a python script using urllib/urllib2 :
curl -H "X-Api-Key: ccccccccccccccccccccccc" -H "X-Api-Secret: cbcwerwerwerwerwerwerweweewr9" https://api.assembla.com/v1/users/user.xml
I tried using the standard url call, but it failed:
url_assembla = 'https://api.assembla.com/v1/users/suer.xml'
base64string_assembla = base64.encodestring('%s:%s' % ('ccccccccccccccccccccccc','cbcwerwerwerwerwerwerweweewr9')).replace('\n', '')
req_assembla = urllib2.Request(url_assembla)
req_assembla.add_header("Authorization", "Basic %s" % base64string_assembla)
ET.parse(urllib2.urlopen(req_assembla))
Can any one advice on how to incorporate the Api-secret and Api-key. I want to do this as a script, so did not want to install the assembla package.
Thanks

If the curl command above works, you should perhaps just add the same headers into the urllib2 query?
Try this instead of the add_header("Authorization") line:
req_assembla.add_header("X-Api-Key", 'ccccccccccccccccccccccc')
req_assembla.add_header("X-Api-Secret", 'cbcwerwerwerwerwerwerweweewr9')

Related

Open Terminal and Run Curl in Python

I have been trying to run this code,
import csv
import os
token = 'Bearer xxx"'
with open('uris.csv', 'r', newline = '',encoding = 'utf-8') as ifp:
ir = csv.reader(ifp)
for i, row in enumerate(ir):
v = ('curl -X "POST" "https://api.spotify.com/v1/playlists/7miRhC7OZhQUvnP1ONghJm/tracks?uris=spotify%3Atrack%3A'+
', '.join(row)+
'" -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: '+
token + '\n')
os.system("gnome-terminal -e 'bash -c \""+v+"; sleep 10\" '")
print(v)
which takes some spotify track uris from a csv and
puts them into the curl that anyone can get from Spotify Api. This curl adds the specific track to my playlist. Then I open a new terminal and execute the curl. (the os.system command was found from open terminal run command python)
The problem is that when I execute this code with python3 code.py new terminals for each curl open but none curl is executed. The curls themselves are right. If I copy paste one curl and run it, the track is added to my playlist. Also if I run a curl separately, I get a response in the terminal which i don't get if I run curls through the code. The response is something like this:
{
"snapshot_id" : "MTQxxx"
}
Thanks a lot.
Silly to ask, but why not just directly call curlOutput = os.system("curl [your concatenation]")?
Might just solve your issue.

Posting a file with a REST API: from a curl example to Python code

I'm trying to code the upload of a file to a web service through a REST API in Python. The service's documentation shows a example using curl as client:
curl -X POST -H \
-H "Content-Type: multipart/form-data" \
-F "file=filename.ext" \
-F "property1=value1" \
-F "property2=value2" \
-F "property3=value3" \
https://domain/api/endpoint
The difficulty for me is that this syntax doesn't match multipart form-data examples I found, including the requests documentation. I tried this, which doesn't work (rejected by the API):
import requests
file_data = [
("file", "filename.ext"),
("property1", "value1"),
("property2", "value2"),
("property3", "value3"),
]
response = requests.post("https://domain/api/endpoint",
headers={"Content-Type": "multipart/form-data"}, files=file_data)
With the error: "org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found"
Can anybody help in transposing that curl example to proper Python code?
Thanks!
R.
OK, looks like the web services documentation is wrong, and metadata simply needs to be sent as parameters. Moreover, I found in another request that you shouldn't set the header. So I was starting from a wrong example.

Curl to httplib

I am able to access a webservice by using curl as given below
curl -k -u "admin:password" "https://10.184.39.12:8080/mypage/managed/user?_query=query-all"
I want to access it by python code. I can use httplib.
connection.request("GET",url,params,headers)
Are the options -k, -u "admin:password" are headers.
If so how could I write in code as headers?
Please help.
You need to encode your username and password as base64 and add that to the headers. Something like this:
import base64
import string
import httplib
auth = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
webservice = httplib.HTTP(host)
webservice.putheader("Authorization", "Basic %s" % auth)
# Add other headers etc
There's more information on this blog post: http://mozgovipc.blogspot.nl/2012/06/python-http-basic-authentication-with.html

Python Requests Put not working with build.phonegap.com

I am making a python build script for a phonegap project.
I need to open the ios key before i build
I am trying to do this with a http put request through the requests module for python.
If i do it with cURL from command line, it works fine
curl -vvv -d 'data={"password":"myPassWord"}' -X PUT https://build.phonegap.com/api/v1/keys/ios/193686?auth_token=passwordlesstokenphg
But from python like this.
password_for_key = {'password': 'myPassword'}
authentication_token = {'auth_token': 'passwordlesstokenphg'}
requests.put('https://build.phonegap.com/api/v1/keys/ios/193686', data=password_for_key, params=authentication_token)
It just returns the json you would recieve if you did a cURL without the data.
For me it seems like the data is not being sent to phonegap correctly.
API reference from build.phonegap.com
docs.build.phonegap.com/en_US/2.9.0/developer_api_write.md.html
Please help :)
So when you do
curl -d "..." -X PUT https://example.com
curl sends exactly what's in that string. requests does not translate so directly to curl. To do something similar in requests you need to do the following:
import json
password_for_key = {'password': 'myPassword'}
authentication_token = {'auth_token': 'passwordlesstokenphg'}
requests.put('https://build.phonegap.com/api/v1/keys/ios/193686',
data={'data': json.dumps(password_for_key)},
params=authentication_token)
What requests will do is build data={"password":"myPassword"} for you if you use the above. First you have to JSON encode the data in password_for_key then pass it in the dictionary to data.

Convert this curl cmd to Python 3

The following curl command works perfectly (private data anonymized):
curl -X POST 'https://api.twilio.com/2010-04-01/Accounts/abc/SMS/Messages.json' \
-d 'From=%2B14155551234' \
-d 'To=%2B17035551212' \
-d 'Body=This+is+a+test' \
-u foo:bar
How can I send out this exact same HTTPS POST request in the proper Python3.3 way? I don't want to have to use anything other than Python 3.3's standard library if I can avoid it (in other words, not using the twilio python module, or "requests", or pycurl, or anything outside the plain vanilla Python 3.3 installation).
The preferred Python approach seems to keep evolving from version to version, the snippets I find by Googling never mention which version they're using or don't do the login part, the Python docs are full of "deprecated since 3.x" but never include code examples of the new way to do things....
If curl can do this so easily, so can standard Python 3.3. But how exactly is this supposed to be done now?
Here's a version that works both on Python 2 and 3:
import requests # pip install requests
url = 'https://api.twilio.com/2010-04-01/Accounts/abc/SMS/Messages.json'
r = requests.post(url, dict(
From='+17035551212',
To='+17035551212',
Body='This is a test'), auth=('foo', 'bar'))
print(r.headers)
print(r.text) # or r.json()
To make https post request with basic http authentication on Python 3.3:
from base64 import b64encode
from urllib.parse import urlencode
from urllib.request import Request, urlopen
user, password = 'foo', 'bar'
url = 'https://api.twilio.com/2010-04-01/Accounts/abc/SMS/Messages.json'
data = urlencode(dict(From='+17035551212', To='+17035551212',
Body='This is a test')).encode('ascii')
headers = {'Authorization': b'Basic ' +
b64encode((user + ':' + password).encode('utf-8'))}
cafile = 'cacert.pem' # http://curl.haxx.se/ca/cacert.pem
response = urlopen(Request(url, data, headers), cafile=cafile)
print(response.info())
print(response.read().decode()) # assume utf-8 (likely for application/json)

Categories