Yin Yang
Yin Yang

Reputation: 1806

Escaping backslash in Python requests

I'm trying to access an API where one of the parameter has a \ in it's name (Axwell /\ Ingrosso).

If I access the API using the website API panel directly, I get the results using Axwell /\\ Ingrosso.

The request URL then becomes https://oauth-api.beatport.com/catalog/3/tracks?facets=artistName%3AAxwell+%2F%5C%5C+Ingrosso&perPage=150

If I try to access the same API endpoint using Python request, I get an empty response.

This is what I'm trying

r = session.get('https://oauth-api.beatport.com/catalog/3/tracks', 
               params={'facets': 'artistName:Axwell /\\ Ingrosso', 
                       'perPage': 150})

I've also tried using it without the backslash in Python request but even that outputs an empty response. What am I missing here?

Upvotes: 2

Views: 8837

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124398

You need to double the backslashes:

'artistName:Axwell /\\\\ Ingrosso'

or use a raw string literal by prefixing the string literal with an r:

r'artistName:Axwell /\\ Ingrosso'

In Python string literals, backslashes start escape sequences, and \\ signifies an escaped escape sequence, e.g. a regular backslash character without specific meaning:

>>> print 'artistName:Axwell /\\ Ingrosso'
artistName:Axwell /\ Ingrosso
>>> print 'artistName:Axwell /\\\\ Ingrosso'
artistName:Axwell /\\ Ingrosso
>>> print r'artistName:Axwell /\\ Ingrosso'
artistName:Axwell /\\ Ingrosso

or as encoded URLs produced by requests:

>>> import requests
>>> requests.Request('GET',
...     'https://oauth-api.beatport.com/catalog/3/tracks',
...     params={'facets': 'artistName:Axwell /\\ Ingrosso',
...             'perPage': 150}).prepare().url
'https://oauth-api.beatport.com/catalog/3/tracks?facets=artistName%3AAxwell+%2F%5C+Ingrosso&perPage=150'
>>> requests.Request('GET',
...     'https://oauth-api.beatport.com/catalog/3/tracks',
...     params={'facets': 'artistName:Axwell /\\\\ Ingrosso',
...             'perPage': 150}).prepare().url
'https://oauth-api.beatport.com/catalog/3/tracks?facets=artistName%3AAxwell+%2F%5C%5C+Ingrosso&perPage=150'
>>> requests.Request('GET',
...     'https://oauth-api.beatport.com/catalog/3/tracks',
...     params={'facets': r'artistName:Axwell /\\ Ingrosso',
...             'perPage': 150}).prepare().url
'https://oauth-api.beatport.com/catalog/3/tracks?facets=artistName%3AAxwell+%2F%5C%5C+Ingrosso&perPage=150'

Upvotes: 4

Related Questions