URL encoding data Etsy-style in Python

The Etsy API has quite specific requirements for how data should be encoded in requests.

With a bit of trial and error making test requests, I ended up with these Python functions to encode data in the way the Etsy API requires:

from typing import Union, Dict, List
from urllib import parse

def etsy_urlencoded(data: Dict):
    return parse.urlencode({k: etsy_urlencoded_value(v) for k, v in data.items()})


def etsy_urlencoded_value(value: Union[Dict, List, str, bool, int, float]):
    if type(value) is dict:
        return json.dumps({k: etsy_urlencoded_value(v) for k, v in value.items()})
    if type(value) is list or type(value) is tuple:
        return ",".join([etsy_urlencoded_value(i) for i in value])
    if type(value) is bool:
        return int(value)
    return str(value)

This lets us automate some of the management of our wall art prints in our Etsy shop.


Tech mentioned