Schema Gen is a simple CLI tool that generates Python GraphQL implementations(using Graphene) from a Graphql Schema file.
pip install schemagenHere's the content of a sample input file(we will call it test.graphql)
typeUser {
id: ID!username: Stringfirst_name: Stringlast_name: Stringfull_name: Stringname: Stringname: String
}Now let's use SchemaGen to generate python code from it.
As a CLI tool:
schemagen parse test.graphql -o test.pyAs a Python Package:
fromschemagenimportSchemaGengen=SchemaGen(
input_file='test.graphql',
output_file='test.py'
)
# parse input filegen()Output(test.py):
# This file was generated by CodegenToolfromgrapheneimport*classUser(ObjectType):
id=Field(ID, required=True)
username=Field(String)
first_name=Field(String)
last_name=Field(String)
full_name=Field(String)
name=Field(String)Here are some things you should know about using SchemaGen:
SchemaGen is not guaranteed to catch errors in your GraphQL schema file.
SchemaGen will only catch a very small percentage of errors that might occur in defining a GraphQL schema. It is the developer's responsibility to ensure the GraphQL schema file is error-free.
SchemaGen will not install the graphene package on your local machine however it will import it in the generated python file.
You can easily install the package by running:
pip install graphene
GraphQL type declarations in your schema file must be ordered.
Because of the way Python and SchemaGen works, you cannot use a GraphQL type before declaring it. For example, the following graphql schema definition would be invalid because we are using the Url scalar in our User type before declaring it:
typeUser { id: ID!username: Stringavatar_url: Url } scalarUrl
The correct version of the above code is:
scalarUrltypeUser { id: ID!username: Stringavatar_url: Url }
Using a GraphQL SDL keyword as an object field name in your schema will throw an error.
For example, doing this:
enumUserType { Example } typeUser{ name: Stringtype: UserType }
will throw an error.
Do this instead:
enumUserType { Example } typeUser{ name: Stringuser_type: UserType }
I plan to fix the last two issues stated above in the future. Pull requests are welcome!