Basic
Basic

Reputation: 26756

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).

Upvotes: 19

Views: 29797

Answers (1)

Nisan.H
Nisan.H

Reputation: 6352

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(...)

Upvotes: 28

Related Questions