strawberry-graphql / strawberry

A GraphQL library for Python that leverages type annotations 🍓
https://strawberry.rocks
MIT License
3.93k stars 519 forks source link

support JSON type hints #2513

Open beasteers opened 1 year ago

beasteers commented 1 year ago

Right now you can accept arbitrary metadata using the JSON scalar, which is great. But sometimes the json has a specific structure, for example: JSON[dict[str, int]] and it would be great if you could add type hints like that to validate the incoming data.

This could hopefully also get around the linting errors like

Expression of type "dict[str, str]" cannot be assigned to declared type "JSON"

and

Expected mapping for dictionary unpack operator

(when trying to do {**some_json_input})

Upvote & Fund

Fund with Polar

hlop3z commented 1 week ago

I encountered a similar error when using pyright:

error: Type "dict[str, int]" is not assignable to return type "JSON" (reportReturnType)

Possible Solutions

To fix this, one way is to modify the JSON type definition in strawberry/scalars.py.

Option 1: Use Any

To completely bypass type checks for JSON, you can use Any. Making it flexible but losing some type safety.

from typing import Any

JSON: Any = scalar(
    NewType("JSON", object),  # mypy doesn't like `NewType("name", Any)`
    ...
)

Option 2: Define JSON as a dict | list

If you want more specific typing while still accommodating common JSON data types (dict or list).

from typing import Union, Dict, List

JSON: Union[Dict, List] = scalar(...)

I hope this proves helpful and works as expected.