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.Structwithfrozen=Trueandkw_only=Truefor immutability and explicitness - Enums: Python enums inheriting from
strfor 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 | Noneinstead ofOptional[str],list[Item]instead ofList[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:
String→strInt→intFloat→floatBoolean→boolID→str- Custom scalars →
str(unless defined in schema) - Nullable types →
T | None(e.g.,str | None) - List types →
list[T](e.g.,list[str]orlist[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 unionsGenerate resolver function stubs:
ⓘ
let code = generate_python_graphql(schema, "resolvers")?;
// Contains: async def resolve_* functions with type hints