Using Django with requests , I want to call a rest server that be configured by Geoserver. In Geoserver docs, there are some cURLs that can used for communicate with the server.
For example this cURL:
curl -v -u admin:geoserver -XPOST -H "Content-type: text/xml"
-d "<workspace><name>acme</name></workspace>"
http://localhost:8080/geoserver/rest/workspaces
creates a new workspace.
How can I convert this cURL to python requests? Also I used following code but it was unsuccessful.
payload = {'-d':'<workspace><name>acme</name></workspace>'}
headers = {'content-type': 'text/xml'}
r = requests.post("http://localhost:8080/geoserver/rest/workspaces", auth=('admin', 'geoserver'),
data=payload,headers=headers)
I got it:
headers = {'content-type': 'text/xml'}
r1 = requests.post("http://localhost:8080/geoserver/rest/workspaces",
auth=('admin', 'geoserver'),
data='<workspace><name>acme</name></workspace>',
headers=headers)
Related
I'm using requests to pull down some JSON from a 3rd party portal.
Whenever i use requests i get a '{"Message":"Path not found"}' error
however running the command with cURL works fine. Here is the cURL command:
curl https://blah.com/api/v1/nodes --header 'Authorization: Bearer my-long-token-base64'
Trying to do this with python3 / requests i have:
#convert token to base64
base64_token = base64.b64encode(bytes(access_token, 'utf-8'))
#convert to str
base64_token = base64_token.decode("utf-8")
api = 'https://blah.com/api/v1/nodes'
headers = {'Authorization': 'Bearer ' + base64_token,
'Accept': 'application/json'}
nodes = requests.post(api, headers=headers)
whenever i run this the response is '{"Message":"Path not found"}'
I thought it might be something to do with the base64 token (which is required) but pretty sure i've got that part right because otherwise i get a 401.
any thoughts?
I'd like to issue an https request to an api from my gae-server, e.g. using urlfetch.
Example call is given as curl command.
curl <URL> \
-u <USER_KEY>: \
-d "infoa=123" \
-d "infob='ABC" \
-d "token=<SOME_TOKEN>" \
-d "description=Test"
All I want to know is, what the HTTPS request would look like, so I can replicate it using this documentation. Probably going about it wrong but I have used --trace-ascii - with curl but from the ouptut I still cannot 100% say what the request I am issuing looks like.
What aspect of an http-request do they translate to? Would it something like this work:
result = urlfetch.fetch(
url='<URL>',
payload={user: <USER_KEY>, data: {infoa=123, infob=ABC, ...}},
method=urlfetch.POST,
headers=headers)
So: -u for user goes into the authorization header. basic encryption is base64. -d for data goes into payload. Different -d are concatenated with a simple ampersand.
try:
headers = {'Content-Type': 'application/x-www-form-urlencoded',
"Authorization": "Basic %s" % base64.b64encode(<some_private_user_authentication>)} # base64 or similar needs to be imported
result = urlfetch.fetch(
url='<URL of endpoint>',
payload='infoa={}&infob={}&description=Test Transaction'.format(info_a, info_b),
method=urlfetch.POST,
headers=headers)
print repr(result.content) # do things..
except urlfetch.Error:
logging.exception('Caught exception fetching url')
print 'Caught exception fetching url' # do other things..
I have a curl command that works perfectly fine and gives me a HTTP 200.
curl -i -H "Authorization: Basic jadkfhjkafDSKJ12DD=" http://<ip>/LoadTest/rest/authentication-point/authenticate
The above API needs the authorization in base64 format and the details have to be passed as Headers. This is a GET request.
When I try to run the same in Python 2.7, I get Response [403]. Code below.
import requests
headers = {'Authorization': 'Basic jadkfhjkafDSKJ12DD='}
authurl = "http://<ip>/LoadTest/rest/authentication-point/authenticate"
r = requests.get(authurl, headers=headers)
print r.status_code
What am I missing here? How should i pass the authorization values exactly like I passed in the curl command? I've tried multiple ways but still end up getting HTTP 403 always. Kindly guide.
Thanks all for your inputs. This is the final solution. I found that there is proxy that is stopping the payload. So added the session to the request.
import requests
session = requests.Session()
session.trust_env = False
headers = {'Authorization': 'Basic jadkfhjkafDSKJ12DD='}
authurl = "http://<ip>/LoadTest/rest/authentication-point/authenticate"
r = session.get(authurl, headers=headers)
print r.status_code
Setting the trust_env=False ignores the following:
Authentication information from .netrc (code)
CA bundles defined in
REQUESTS_CA_BUNDLE or CURL_CA_BUNDLE (code)
Here is the working curl statement that I am trying to put into a python script:
curl -L -H 'X-Cisco-Meraki-API-Key: <key>' -X PUT -H'Content-Type: application/json' --data-binary '{"name":"new SSID name", "enabled":true, "authMode":"psk", "encryptionMode":"wpa", "psk":"abcd1234", "ipAssignmentMode":"Bridge mode"}' 'https://dashboard.meraki.com/api/v0/networks/[networkId]/ssids/[number]'
Here is my python code.
import requests
import json
url = "https://dashboard.meraki.com/api/v0/networks/XXXXXXX/ssids/2"
headers = {'X-Cisco-Meraki-API-Key': 'YYYYYYY', 'content-type': 'application/json'}
payload = {"name":"test", "enabled":"true", "authMode":"psk", "encryptionMode":"wpa", "psk":"abcd1234", "ipAssignmentMode":"NAT mode"}
r = requests.put(url, headers=headers, data=payload, allow_redirects=True)
print r.status_code
When I run the curl command, it works, but when I try the python script, I get a 400 error message. My guess is that it has to do with the way that the application is interpreting the payload. Any help would be greatly appreciated.
You need to use:
data=json.dumps(payload)
Instead of:
data=payload
When you add 'content-type': 'application/json' header, you mean that you're sending a json data, that's why you need to use json.dumps() to sent a valide json data instead of a Python dictionary / object.
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)