3

I'm doing a requests.get call with the following url:

https://api.datasource.com/apps/ios/ranking?countries=NL&categories=Overall > Kids > 5 & Under&device=ios&ranks=1000

I get an error message with "categories" has an illegal value "Overall which is due to the & sign in Overall > Kids > 5 & Under

What's the best approach for escaping this character?

user3642173
  • 1,225
  • 5
  • 19
  • 42
  • 3
    Possible duplicate of [escaping ampersand in url](https://stackoverflow.com/questions/16622504/escaping-ampersand-in-url) – Gannon Jun 01 '17 at 12:47

1 Answers1

6

Instead of passing the query parameters directly in the URL, requests lets you pass them in a dictionary params and will handle the URL encoding. (In this case, you need to escape the ampersand.)

In [15]: params = dict(countries='NL', categories='Overall > Kids > 5 & Under', device='ios', ranks=1000)

In [16]: requests.get("http://www.example.com", params=params)
Out[16]: <Response [200]>
Katriel
  • 120,462
  • 19
  • 136
  • 170