How to get request parameters from an encoded URL in Django?
The Django request.GET
object, and the request.query_params
alias that Django REST adds, can only parse application/x-www-form-urlencoded
query strings, the type encoded by using a HTML form. This format can only encode key-value pairs. There is no standard for encoding JSON into a query string, partly because URLs have a rather limited amount of space.
If you must use JSON in a query string, it'd be much easier for you if you prefixed the JSON data with a key name, so you can at least have Django handle the URL percent encoding for you.
E.g.
/endpoint?json=%7B%0D%0A++%22foo%22%3A%5B%22bar%22%2C%22baz%22%5D%0D%0A%7D
can be accessed and decoded with:
import jsonjson_string = request.query_params['json']data = json.loads(json_string)
If you can't add the json=
prefix, you need to decode the URL percent encoding yourself with urllib.parse.unquote_plus()
, from the request.META['QUERY_STRING']
value:
from urllib.parse import unquote_plusimport jsonjson_string = unquote_plus(request.META['QUERY_STRING'])data = json.loads(json_string)
urllib
ought to do it:
from urllib.parse import unquoteurl = "endpoint?%7B%0D%0A++%22foo%22%3A%5B%22bar%22%2C%22baz%22%5D%0D%0A%7D"url = unquote(url)print(url)
The above almost works, but the encoding might be incorrect, not sure:
endpoint?{++"foo":["bar","baz"]}