Home > Software engineering >  Python requests doesn't add query string via params in get method
Python requests doesn't add query string via params in get method

Time:06-25

When I try to send GET request to a specific URL with python requests library, I get an error because requests lib does not make query string from params parameter in requests.get method and does not add that query string to the URL. But when I do exactly the same thing to another URL and put to params anything else, everything works as expected.

There is my code and output:

In [1]: import requests

In [2]: r = requests.get('https://bitmex.com/api/v1/user/margin', params={'currency': 'all'})

In [3]: r.request.url
Out[3]: 'https://www.bitmex.com:443/api/v1/user/margin'

In [4]: r = requests.get('https://google.com/bla/bla', params={'a': 1})

In [5]: r.request.url
Out[5]: 'https://google.com/bla/bla?a=1'

CodePudding user response:

$ curl --head https://bitmex.com/api/v1/user/margin?currency=all
HTTP/2 301 
content-length: 0
location: http://www.bitmex.com/api/v1/user/margin
date: Fri, 24 Jun 2022 15:27:21 GMT
server: AmazonS3
x-cache: Miss from cloudfront
via: 1.1 67b828898c2b34a7518c5b13dd7321c0.cloudfront.net (CloudFront)
x-amz-cf-pop: TXL50-P3
x-amz-cf-id: 6Hrqwnw253x10GHPdtl9rF2PcJmDOiJHVPEuQ_qS8twOVHVR1Vfx3Q==

What you're seeing is the result of a redirect. Have a look at the Redirection and History chapter from the requests documentation. If you want the original URL, use either the allow_redirects parameter or r.history

CodePudding user response:

In [1]: import requests

In [2]: r = requests.get('https://bitmex.com/api/v1/user/margin', params={'currency': 'all'})

In [3]: r.history[0].request.url
Out[3]: 'https://bitmex.com/api/v1/user/margin?currency=all'
  • Related