Type-hint a nested json api response

641 Views Asked by At

Let's say I have an api endpoint that returns a complex response.

data = requests.get("https://my.api/garbage").json()
# {
#     "a": 1,
#     "b": "asd",
#     "c": [1,2],
#     "d": {
#         "e": "dsa",
#         "f": 1,
#     },
#     "g": True
# }

I pass this response around various places in order to process it. What is the standard way to type-hint this data? I looked into TypedDict, but it does not seem to allow nested definitions without declaring multiple TypedDicts, which is undesiderable for very nested data, and inline declaration is also not allowed.

I similarly looked into attrs/cattrs to serialize this data, but those libraries do not seem to be able to handle nested dictionaries either without a lot of added complexity and declarations. I don't think it's reasonable to have to declare 10+ dataclasses for an api response that can be just summed as dict[str, dict[str, str | int]], for example.

Could someone provide a concrete example of how I would be able to pass around this data object (or any other complex api response, from any arbitrary endpoint) in python and allow mypy or other typing helpers to recognize the data correctly?

Ideally if I were to pass this object to a function, if properly typed, mypy or my IDE should be able to recognize that data["d"]["e"] (or data.d.e, if the response to this question provides a serialized object) is a string.

0

There are 0 best solutions below