Skip to main content

generate_python_graphql

Function generate_python_graphql 

Source
pub fn generate_python_graphql(schema: &str, target: &str) -> Result<String>
Expand description

Generate Python GraphQL code from a schema

Parses the GraphQL schema string and generates complete Python code with type definitions, resolver implementations, and schema configuration based on the target specification. Generated code follows Python 3.10+ conventions using msgspec for type-safe data serialization and Ariadne for GraphQL schema binding.

§Generated Code Features

  • Type Definitions: Python dataclasses using msgspec.Struct with frozen=True and kw_only=True for immutability and explicitness
  • Enums: Python enums inheriting from str for GraphQL enum types
  • Input Objects: msgspec Structs for GraphQL input types
  • Union Types: Python type aliases (e.g., User | Post | Any)
  • Type Hints: Full type annotations using Python 3.10+ syntax (e.g., str | None instead of Optional[str], list[Item] instead of List[Item])
  • Resolvers: Async resolver functions with proper type hints and parameter handling
  • Schema Definition: Ariadne-compatible schema with embedded SDL and resolver setup
  • Docstrings: NumPy-style docstrings extracted from GraphQL descriptions

§Arguments

  • schema - GraphQL schema as a string (SDL format)
  • target - Generation target specifying what to generate:
    • "all" - Complete code: types, resolvers, and schema definition
    • "types" - Type definitions and enums only
    • "resolvers" - Async resolver function stubs with type hints
    • "schema" - Ariadne schema definition with embedded SDL
    • Any other value defaults to “all”

§Returns

Generated Python code as a String, or an anyhow::Error if parsing or generation fails (e.g., invalid GraphQL SDL syntax).

§Type Mapping

GraphQL types are mapped to Python as follows:

  • Stringstr
  • Intint
  • Floatfloat
  • Booleanbool
  • IDstr
  • Custom scalars → str (unless defined in schema)
  • Nullable types → T | None (e.g., str | None)
  • List types → list[T] (e.g., list[str] or list[str | None])
  • Union types → Type1 | Type2 | ... | Any

§Examples

Generate all Python code for a simple query:

let schema = r#"
type Query {
  hello: String!
  user(id: ID!): User
}

type User {
  id: ID!
  name: String!
  email: String
}
"#;

let code = generate_python_graphql(schema, "all")?;
println!("{}", code);

Generate only type definitions:

let code = generate_python_graphql(schema, "types")?;
// Contains: msgspec Structs, Enums, type unions

Generate resolver function stubs:

let code = generate_python_graphql(schema, "resolvers")?;
// Contains: async def resolve_* functions with type hints