Get request python as a string - python

I wanted to send a get request in python and return it as a string. I wanna eventually use that string as something later on. Also by default does python return it in json format?
req = requests.get(server, auth=('user',"pass"))
thanks

Use python requests. Check the link, there are examples how you get json from response.
req = requests.get(server, auth=('user',"pass"))
req.json()
If you want it as string, use
req.text

Related

Get Set-Cookie in header using requests module

When I use PHP to get cookie, it returns:
session_id=abih14s7l4lgo3splta7f6bd14; cccaa78fa9e13785130119a4924db0f4=96637ae... (more)
But when I use Python, it returns:
session_id=abih14s7l4lgo3splta7f6bd14
... the rest of cookies is lost.
My code Python:
res_post = requests.post(LOGIN_URL, data = {mydata})
cookies = dict(res_post.cookies.items())
Looks like you're using the requests library. The response.cookies is already a dictionary, so there's no need to cast it again.
You should access the cookies on the response like so:
response = requests.post(LOGIN_URL, data={mydata})
print response.cookies['session_id']
See here for more detail: http://docs.python-requests.org/en/latest/user/quickstart/#cookies

HTTP Delete with python requests module

I would like to do a HTTP DELETE with python requests module that follows the API below;
https://thingspeak.com/docs/channels#create
DELETE https://api.thingspeak.com/channels/4/feeds
api_key=XXXXXXXXXXXXXXXX
I am using python v2.7 and requests module. My python code looks like this;
def clear(channel_id):
data = {}
data['api_key'] = 'DUCYS8xufsV613VX'
URL_delete = "http://api.thingspeak.com/channels/" + str(channel_id) + "/feeds"
r = requests.delete(URL_delete, data)
The code does not work because requests.delete() can only accept one parameter. How should the correct code look like?
You want
import json
mydata = {}
mydata['api_key'] = "Jsa9i23jka"
r = requests.delete(URL_delete, data=json.dumps(mydata))
You have to use the named input, 'data', and I'm guessing that you actually want JSON dumped, so you have to convert your dictionary, 'mydata' to a json string. You can use json.dumps() for that.
I don't know the API you are using, but by the sound of it you actually want to pass URL parameter, not data, for that you need:
r = requests.delete(URL_delete, params=mydata)
No need to convert mydata dict to a json string.
You can send the data params as #Eugene suggested, but conventionally delete requests only contains url and nothing else. The reason is that a RESTful url should uniquely identify the resource, thereby eliminating the need to provide additional parameters for deletion. On the other hand, if your 'APIKEY' has something to do with authentication, then it should be part of headers instead of request data, something like this.
headers = {'APIKEY': 'xxx'}
response = requests.delete(url, data=json.dumps(payload), headers=headers)

The request JSON is not well formed

I'm trying to re-create the example available on this page
Of course I'm changing the client_id, secret, credit card etc... with my valid data (I haven't copy-pasted the example as is).
You can see my complete code here (I've hidden sensible data with *** ).
I can get the token without any problem, but when I post the payment request I get this back:
In [11]: r2.text
Out[11]: u'{"name":"MALFORMED_REQUEST","message":"The request JSON is not well formed.","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#MALFORMED_REQUEST","debug_id":"*************"}'
I really can't understand why it says that my json is malformed :(
Anyone can help me? Thanks!
This is your code:
post_data = json.loads(s)
r2 = requests.post('https://api.sandbox.paypal.com/v1/payments/payment', headers = {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token},
data = post_data)
You have a JSON string s that you convert to a Python object and post that to the server. As the docs say, if you pass a dict as your data, it gets form-encoded, not JSON-encoded. If you want data in any other format, you're supposed to encode it yourself, as in the example:
>>> r = requests.post(url, data=json.dumps(payload))
Since you already have the JSON-encoded string s, you can just send that.
You totally misunderstood what you should pass to requests.post() method. http://docs.python-requests.org/en/latest/user/quickstart.html#more-complicated-post-requests
You are trying to pass Python objects instead of JSON. #Janne's answer is an option, but it is more convenient to build data as Python object and then use json.dumps(obj) and pass result to requests.post().

How to send a POST request using django?

I dont want to use html file, but only with django I have to make POST request.
Just like urllib2 sends a get request.
Here's how you'd write the accepted answer's example using python-requests:
post_data = {'name': 'Gladys'}
response = requests.post('http://example.com', data=post_data)
content = response.content
Much more intuitive. See the Quickstart for more simple examples.
In Python 2, a combination of methods from urllib2 and urllib will do the trick. Here is how I post data using the two:
post_data = [('name','Gladys'),] # a sequence of two element tuples
result = urllib2.urlopen('http://example.com', urllib.urlencode(post_data))
content = result.read()
urlopen() is a method you use for opening urls.
urlencode() converts the arguments to percent-encoded string.
The only thing you should look at now:
https://requests.readthedocs.io/en/master/
You can use urllib2 in django. After all, it's still python. To send a POST with urllib2, you can send the data parameter (taken from here):
urllib2.urlopen(url[, data][, timeout])
[..] the HTTP request will be a POST instead of a GET when the data parameter is provided
Pay attention, that when you're using 🐍 requests , and make POST request passing your dictionary in data parameter like this:
payload = {'param1':1, 'param2':2}
r = request.post('https://domain.tld', data=payload)
you are passing parameters form-encoded.
If you want to send POST request with only JSON (most popular type in server-server integration) you need to provide a str() in data parameter. In case with JSON, you need to import json lib and make like this:
payload = {'param1':1, 'param2':2}
r = request.post('https://domain.tld', data=json.dumps(payload))`
documentation is here
OR:
just use json parameter with provided data in the dict
payload = {'param1':1, 'param2':2}
r = request.post('https://domain.tld', json=payload)`

Put json data into url with python

I am trying to encode a json parameter within a url for use with the mongolab restAPI.
My url looks something like this
url = 'https://api.mongolab.com/api/1/databases/db/collections/coll?q={"q": "10024"}&apiKey=mykey
I am trying to open it using
urllib2.urlopen(url)
but I run into errors saying that my apikey is incorrect. I know this isn't true because if I copy and paste the url into my browser I get a correct response. I also know that I can access the rest api as long as I don't have the query there (so it must be a json/formatting problem).
So does anyone know how I could encode the json query
{"q": "10024"}
into the url? Thanks!
You'll have to properly URL-encode the string. Use the urllib.quote_plus() function:
url = 'https://api.mongolab.com/api/1/databases/db/collections/coll?q={q}&apiKey={key}'
query = urllib.quote_plus('{"q": "10024"}')
urllib2.urlopen(url.format(q=query, key=your_api_key))
You could also use the requests library.
Example:
import requests
payload = {'q': '10024', 'apiKey': 'mykey'}
r = requests.get("https://api.mongolab.com/api/1/databases/db/collections/coll", params=payload)
print(r.url)
Output:
https://api.mongolab.com/api/1/databases/db/collections/coll?q=10024&apiKey=mykey

Categories

Resources