Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send a GET request with a body

I'm using elasticsearch and the RESTful API supports supports reading bodies in GET requests for search criteria.

I'm currently doing

response = urllib.request.urlopen(url, data).read().decode("utf-8")

If data is present, it issues a POST, otherwise a GET. How can I force a GET despite the fact that I'm including data (which should be in the request body as per a POST)

Nb: I'm aware I can use a source property in the Url but the queries we're running are complex and the query definition is quite verbose resulting in extremely long urls (long enough that they can interfere with some older browsers and proxies).

like image 293
Basic Avatar asked Mar 20 '13 16:03

Basic


1 Answers

I'm not aware of a nice way to do this using urllib. However, requests makes it trivial (and, in fact, trivial with any arbitrary verb and request content) by using the requests.request* function:

requests.request(method='get', url='localhost/test', data='some data')

Constructing a small test web server will show that the data is indeed sent in the body of the request, and that the method perceived by the server is indeed a GET.

*note that I linked to the requests.api.requests code because that's where the actual function definition lives. You should call it using requests.request(...)

like image 62
Nisan.H Avatar answered Oct 11 '22 01:10

Nisan.H