-1

I have a function that accesses an API and returns its JSON:

def get_api():
    return requests.get(url).json()

Such response is of this type:

[{id: 3, name: 'X'},{id: 7, name: 'Y'},...]

I would like to declare the type of the return value so that the linting is aware of that, so when I write:

r=get_api()
for e in r:
    print(e["id"]) # linting ok
    print(e["something"]) # linting error, 'something' is not a valid key

The JSON is simple here, but can be nested of course.

I'm using Python 3.6.

How should I use the typings?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
edoedoedo
  • 1,469
  • 2
  • 21
  • 32
  • Did you look at https://docs.python.org/3/library/typing.html#typing.TypedDict? It's new in 3.8, so you may need to upgrade. – jonrsharpe May 26 '20 at 16:32
  • Yes, but unfortunately I cannot upgrade I have some packages which still have 3.6 as a dependency – edoedoedo May 26 '20 at 17:08

1 Answers1

-1

You can consider using a library for serialization and deserialization. i.e. Encoders and Decoders from the native python 3.x std library https://docs.python.org/3/library/json.html

A similar question was asked for python: What is the alternative of Jackson in python?

This is more common in typed languages (Java has a popular one called Jackson) since the key mapping is a harder requirement, but you can do this with a number of alternatives. The underlying idea is map a JSON blob to a class and parse it into/onto that object (vice versa for serializing).

dsiah
  • 1
  • 2
  • Nice idea, however I won't add more complexity to the actual code, I just wanted to improve the linting with a more robust structure so that If someone use my function he already knows what keys will be in the json (of course he can use them or use others, there is no guarantee, it's just a matter of linting for cleanliness) – edoedoedo May 26 '20 at 17:11