Maxcot
Maxcot

Reputation: 1617

Transforming queries in a URL

I'm trying to use a REST API apparently constructed with LoopBack and it requires that my filter parameters be encoded in a specific way.

What is this sort of transformation called?

# this is a JSON type encoding
...?filter={"where": {"StartDate": {"gte": "2021-01-01T00:00:00.000Z"}}, "offset": 0, "limit": 100, "order": "id DESC" }

which needs to be encoded as some sort of HTTP query string 

...?filter=%7B%22where%22%3A%20%7B%22StartDate%22%3A%20%7B%22gte%22%3A%20%222021-06-01T00%3A00%3A00.000Z%22%7D%7D%2C%20%22offset%22%3A%200%2C%20%22limit%22%3A%20100%2C%20%22order%22%3A%20%22id%20DESC%22%20%7D

Is there a python function to do this?

Upvotes: 0

Views: 277

Answers (2)

penguin359
penguin359

Reputation: 1489

You are looking for URL encoding. If you already have the JSON encoded in a variable as such, then just encode it to the filter parameter:

from urllib.parse import urlencode, quote

base_url = "..."
filter_string = """{"where": {"StartDate": {"gte": "2021-01-01T00:00:00.000Z"}}, "offset": 0, "limit": 100, "order": "id DESC" }"""
query = urlencode({"filter": filter_string}, quote_via=quote)
url = f"{base_url}?{query}"

Now, I expect that the JSON is probably coming from a Python data structure. You can use the dumps function from json to handle that encoding:

from urllib.parse import urlencode, quote
import json

base_url = "..."
data = {
    "where": {
        "StartDate": {
            "gte": "2021-01-01T00:00:00.000Z"
        }
    },
    "offset": 0,
    "limit": 100,
    "order": "id DESC"
}
filter_string = json.dumps(data)
query = urlencode({"filter": filter_string}, quote_via=quote)
url = f"{base_url}?{query}"

And you have the URL to call to in the variable url.

Upvotes: 1

Edo Akse
Edo Akse

Reputation: 4401

This is URL encoding.

URLs cannot contain a lot of different special characters, such as spaces (a space would be %20 in URL encoding).
Note that URL encoding is quite easy to recognize once you know it exists, due to the %xx pattern.

The urllib has functions to deal with encoding/decoding this.

To create an URL encoded string use urllib.parse.quote(string). Relevant docs here...

Example

from urllib.parse import quote
jsonstring = '{"where": {"StartDate": {"gte": "2021-01-01T00:00:00.000Z"}}, "offset": 0, "limit": 100, "order": "id DESC" }'
urlencoded = quote(jsonstring)

print(urlencoded)

# output
# %7B%22where%22%3A%20%7B%22StartDate%22%3A%20%7B%22gte%22%3A%20%222021-01-01T00%3A00%3A00.000Z%22%7D%7D%2C%20%22offset%22%3A%200%2C%20%22limit%22%3A%20100%2C%20%22order%22%3A%20%22id%20DESC%22%20%7D

Upvotes: 1

Related Questions