pythongraphqlcode-generationtype-hinting

GraphQL schema to python dataclasses codegen


I have a GraphQL schema defined from server and I'd like to write a nice Python GraphQL client for it. I'm looking for a way to transform my GraphQL schema into python classes with type hints such that I'll be able to see all available queries, mutations, their fields(names & types) and return vals.

I cannot write manually all python classes due to schema complexity, I have many filters on each field. see this example from ent on TodoWhereInput to understand how error prune this will be. I really enjoy using GraphQL playground with auto completion, I want that experience in my python client.

For example, given this schema as an input:

type Book {
  title: String
  year: Int
}

type Author {
  name: String
  books: [Book]
}

I'd like to generate this python code as an output:

from dataclasses import dataclass

@dataclass
class Book:
  title: str
  year: int

@dataclass
class Author:
  name: str
  books: list[Book]

same for Inputs in schema.

I already looked at:

  1. codegen which is awesome for typescript! but doesn't have python support :/

  2. gql_schema_codegen nice, but generating TypedDict which isn't dataclasses, I have to change each dict and pass total=False so it won't required all fields by default.

  3. sgqlc code-generator which doesn't allow type hints. writing queries is still dynamically and error prune.


Solution

  • Thanks for all the answers, but after revisiting this issue I found out Ariadne is the best solution for my case. Generating async / sync clients based on GraphQL schema + queries, highly configurable.

    You are welcome to try them yourself: https://github.com/mirumee/ariadne-codegen