I've been given the following curl command as part of API documentation, and I'm trying to implement it using the requests library.
curl -v --cookie cookie.txt -X POST -H 'Accept: application/json' -F 'spot[photo]'=@rails.png -F 'spot[description]'=spot_description -F 'spot[location_id]'=9 -F 'spot[categories][]'='See the Sights' -F 'spot[categories][]'='Learn Something' http://some.server.com/api/v1/spots
my python code looks something like this:
import requests
import json
_user = 'redacted'
_password = 'redacted'
_session = requests.session()
_server = 'http://some.server.com'
_hdr = {'content-type': 'application/json', 'accept': 'application/json'}
_login_payload = {
'user': {
'email': _user,
'password': _password
}
}
r = _session.post(_server + "/users/sign_in", data=json.dumps(_login_payload), headers=_hdr)
print json.loads(r.content)
_spot_payload = {
'spot': {
'photo': '@rails.gif',
'description': 'asdfghjkl',
'location_id': 9,
'categories': ['See the Sights',]
}
}
r = _session.post(_server + '/api/v1/spots', data=json.dumps(_spot_payload), headers=_hdr)
print json.loads(r.content)
I've heard tell that you can use open('file').read() to post files, but the json encoder doesn't much like this, and I'm not sure about a way around it.