Introducing a new way to review your PRs.

Read the announcement

strawberry-graphql / strawberry

A GraphQL library for Python that leverages type annotations 🍓

View on GitHub

21 documents · Updated Nov 18, 2026

docs / cli-and-code-generation

CLI and code generation

Strawberry's command-line tools turn a Python schema or a GraphQL document into useful developer artifacts. They load a schema from the application, then either expose its SDL, map schema definitions back to source code, create Python code from SDL, or create client types and query text from named operations. This page gives the working model for those flows; see Developer tooling for the wider tooling map.

CLI entry point

Command dispatch

The strawberry executable starts one Typer application. The CLI package imports the command modules and registers their functions on that application. This makes each command a separate entry into a shared command surface while keeping schema loading and code generation in reusable library parts. strawberry is available when the package script points to strawberry.cli:run.

The command surface includes these main developer workflows:

  • export-schema publishes a runtime schema as GraphQL SDL.
  • locate-definition maps a schema type or field to its Python source location.
  • schema-codegen turns an SDL file into Strawberry Python definitions.
  • codegen turns one or more named operations into client-facing output through plugins.
  • dev validates a schema reference, then starts a reloadable development server.

The CLI treats missing command-only packages as an installation problem. The package raises a focused optional-dependency error instead of making the base Strawberry import fail for every user.

References: strawberry/…/__init__.py• L1-20 strawberry/…/app.py• L1-3 strawberry/…/dev.py• L23-72 pyproject.toml• L36-37

Schema loading and inspection

Schema loading

Schema-based commands accept a Python import selector. A selector names a module and may name a symbol after :; when the symbol is omitted, the loader looks for schema. The symbol may be a strawberry.Schema instance or a callable that creates one. The --app-dir option adds the application directory to the import path so the same selector works from outside the project directory.

The loader is the shared boundary for export, source inspection, query code generation, and the development server. The dev command validates the loaded schema before it starts the server, then passes the selector to the server and watches the application directory for changes. The loader reports import, symbol, factory, and type errors as CLI failures. Downstream commands therefore receive a real runtime schema rather than handling several forms of application setup themselves.

The following flow shows how a command turns an application selector into the schema used by the rest of the tool.

flowchart LR
    A[CLI command] --> B[Module and symbol selector]
    B --> C[Application directory on import path]
    C --> D[Import schema or factory]
    D --> E[Create or validate strawberry.Schema]
    E --> F[Export, inspect, serve, or generate]

References: strawberry/…/__init__.py• L10-32 strawberry/…/importer.py• L4-20 strawberry/…/export_schema.py• L11-32 strawberry/…/dev.py• L46-72

Schema export

export-schema presents the executable schema as GraphQL SDL. It uses the runtime schema's printer, so the result is the public contract that other GraphQL tools can consume rather than a copy of the Python declarations. The command prints SDL to the terminal by default or writes it to the requested output file.

This export is useful as a hand-off point to IDE tools, schema checks, documentation systems, and external code generators. The printer includes the schema's defined types and relevant directives while preserving custom schema details that affect the GraphQL contract.

References: strawberry/…/export_schema.py• L9-38 strawberry/…/printer.py• L595-665 docs/…/schema-export.md• L7-38

Definition inspection

locate-definition connects a GraphQL name to the Python source that defines it. It accepts a type name or a type-and-field name, resolves that name through the loaded schema, and returns a path with line and column information. This gives editors and debugging tools a source link that follows GraphQL names through naming conversion such as automatic camel casing.

The command uses the same schema loading boundary as export. A missing type or field is a normal inspection miss and produces a clear failure rather than an ambiguous import result.

References: strawberry/…/locate_definition.py• L15-36 strawberry/…/locate_definition.py• L14-46 tests/…/test_locate_definition.py• L20-62

GraphQL schema generation

SDL-to-Strawberry generation

schema-codegen starts with a GraphQL SDL file and creates Python source that defines the corresponding Strawberry schema. It is intended for teams that receive or maintain a schema in GraphQL form but want Python types and a Strawberry Schema object as the next working representation.

The generator maps GraphQL object, interface, input, enum, union, scalar, and root operation definitions to Strawberry-oriented Python declarations. It adds imports and orders definitions so referenced types exist before the schema is assembled. Nullable input values retain the distinction between an omitted value and an explicit null, and SDL default values become Python defaults. Federation link directives produce federation-aware schema and field declarations when the input describes a federation schema.

The generated source is a starting point for an executable schema. It carries useful SDL information such as descriptions, aliases, default values, and supported federation directives where the input expresses them, but it does not replace application resolver behavior.

The flow is intentionally one-way: SDL describes the shape, the generator creates Python declarations, and application code supplies behavior around those declarations.

flowchart LR
    A[GraphQL SDL file] --> B[Parse type and root definitions]
    B --> C[Create Strawberry Python declarations]
    C --> D[Order dependent definitions]
    D --> E[Emit Python module]
    E --> F[Application adds resolver behavior]

References: strawberry/…/schema_codegen.py• L9-31 strawberry/…/__init__.py• L189-229 strawberry/…/__init__.py• L335-426 strawberry/…/__init__.py• L540-731 strawberry/…/__init__.py• L741-989 docs/…/schema-codegen.md• L7-46

Operation generation

Query-to-client generation

codegen creates client-side types or query artifacts from GraphQL operation files. It loads the server schema first, then reads each query file and resolves its selections against that schema. The result contains only the types needed by the selected operation, including nested selections, variables, fragments, aliases, arguments, directives, enums, scalars, and unions.

Each query file must contain one named operation. The operation name becomes the stable root for generated result and variable types. The generator follows field relationships to build the operation model, then sends the model and its dependent types to the selected plugins.

The command can process several query files in one run. A shared console plugin reports the run and persists the files returned by each query plugin in the output directory.

sequenceDiagram
    participant E as CLI
    participant S as Runtime schema
    participant Q as QueryCodegen
    participant P as Selected plugins
    participant O as Output directory
    E->>S: Load schema selector
    E->>Q: Provide query document
    Q->>Q: Parse one named operation
    Q->>S: Resolve fields, fragments, and types
    Q->>P: Send operation model and dependent types
    P-->>Q: Return generated files
    Q->>O: Write files and report results

References: strawberry/…/codegen.py• L92-143 strawberry/…/query_codegen.py• L344-382 strawberry/…/query_codegen.py• L281-341

Operation model

The operation generator separates GraphQL meaning from output language. It represents an operation as a named query, mutation, or subscription with selections and variables. It represents selected result shapes as object, enum, scalar, optional, list, and union types. Plugins can therefore render the same schema-aware operation in different formats without parsing the query again.

The model keeps the schema's GraphQL field name separate from a query alias. This lets generated output describe the response name while still resolving the selected field against the schema. The type set is ordered by dependency before plugins receive it, so a nested result type is emitted before the object that refers to it.

The model also keeps GraphQL nullability distinct from a Python type wrapper. When a Strawberry type already represents a nullable value, the generator does not add a second optional layer. This keeps a strawberry.Maybe[X | None] input as one nullable GraphQL type rather than changing the generated client shape through double wrapping.

References: strawberry/…/types.py• L14-87 strawberry/…/types.py• L90-197 strawberry/…/query_codegen.py• L127-134 strawberry/…/query_codegen.py• L605-649 strawberry/…/query_codegen.py• L290-324

Built-in generation plugins

Plugin selection and lifecycle

The codegen command selects one or more query plugins with -p and may select a separate console plugin. A plugin name can be a full Python module path, a module:symbol path, or a short name resolved from Strawberry's built-in plugin package. This lets a project use built-in output or load a project-specific renderer without changing the command.

Each query plugin receives the source query path when it starts. It can prepare state, create one or more named output files from the operation model, and post-process the complete result. The console plugin handles run-level messages and writes the returned files. Multiple query plugins can run for the same operation, so one query can produce several client representations.

References: strawberry/…/codegen.py• L17-89 strawberry/…/codegen.py• L118-143 strawberry/…/query_codegen.py• L136-187 strawberry/…/query_codegen.py• L281-341

Python plugin

The Python plugin renders operation-specific result types as Python classes. It maps common GraphQL scalars to Python types and represents enums, unions, optional values, lists, custom scalars, and selected object shapes in a single module named from the query file.

This output is useful when a Python client needs typed access to the response shape of a particular operation. It follows aliases and default values from the operation model so the generated declarations describe the requested response rather than the full server schema.

References: strawberry/…/python.py• L37-64 strawberry/…/python.py• L74-110 strawberry/…/python.py• L157-212

TypeScript plugin

The TypeScript plugin renders the same operation-specific shapes as TypeScript types and enums. It maps standard and known custom scalars to TypeScript primitives, expresses nullable values as undefined, and represents GraphQL unions as TypeScript unions.

The output file uses the query file's name with a TypeScript extension. This makes it possible to generate Python and TypeScript client types from the same operation in one command while keeping each language's type rules in its own plugin.

References: strawberry/…/typescript.py• L22-47 strawberry/…/typescript.py• L49-70 strawberry/…/typescript.py• L83-124

The print-operation plugin turns the parsed operation model back into a GraphQL document. It includes named fragments, variables, arguments, directives, aliases, nested selections, and inline fragments, then writes the result as query.graphql.

This plugin is useful when a tool needs a normalized or reconstructed operation after Strawberry has checked it against the schema. It is an output plugin rather than a type mapper, so it can run beside the Python or TypeScript plugins.

References: strawberry/…/print_operation.py• L36-58 strawberry/…/print_operation.py• L84-109 strawberry/…/print_operation.py• L142-212

Change checklist

When these files or sections are changed, remember to consider these:

  • If the CLI entry point or command registration changes, keep the executable name, command names, and optional CLI dependency behavior aligned.
  • If schema selector or --app-dir rules change, check export, definition inspection, development-server startup, and operation codegen together.
  • If schema printing or schema type lookup changes, check both exported SDL and query type resolution because they expose the same runtime schema through different paths.
  • If the operation model changes, review every built-in plugin and the custom plugin contract for new type, selection, variable, or file-output cases.
  • If generated file names or output-directory behavior changes, check multi-query runs and collisions between plugins that write related artifacts.
  • If Strawberry optional type handling changes, check generated input types for Maybe values and other nested nullable forms so one GraphQL nullable value does not become multiple client wrappers.

Important failure modes

TriggerConsequenceGuard
The schema selector names a missing module, symbol, factory, or non-Schema value.Schema-based commands stop before export, inspection, or generation.Use a module selector with a valid schema symbol or schema factory and set --app-dir to the import root.
The development server dependencies are not installed.dev exits before it validates the schema or starts the server.Install the CLI extras that provide the development server packages.
A query file has no operation, more than one operation, or no operation name.Query code generation cannot choose a stable result type.Put one named operation in each query file.
A query field, fragment type condition, or variable type is not present in the loaded schema.Type collection fails while building the operation model.Generate against the same schema version that validates the client document.
A selected plugin cannot be imported or does not expose a supported plugin class.The codegen command exits before producing output.Use a built-in plugin name or a valid module and symbol path.
Two outputs target the same path in one run.A later plugin or query can replace earlier generated content.Give plugins distinct output paths and use distinct query file names for multi-query runs.
A nullable Strawberry input is wrapped again while the operation model is built.Generated client input types show an incorrect extra nullable layer.Preserve the single GraphQL nullability represented by nested optional types.

Key files

FileWhy to read it
strawberry/…/__init__.pyShows the executable entry point and command registration boundary.
strawberry/…/__init__.pyDefines the shared application schema loading contract.
strawberry/…/dev.pyShows schema validation and development-server startup.
strawberry/…/export_schema.pyShows how a runtime schema becomes printed SDL.
strawberry/…/locate_definition.pyShows the source inspection path for schema types and fields.
strawberry/…/schema_codegen.pyShows the SDL-to-Python command boundary.
strawberry/…/__init__.pyDefines the GraphQL SDL to Strawberry source transformation.
strawberry/…/codegen.pyShows query command options, plugin loading, and multi-file dispatch.
strawberry/…/query_codegen.pyDefines operation parsing, schema-aware type collection, nullability handling, plugin coordination, and output persistence.
strawberry/…/types.pyDefines the shared operation and type model used by output plugins.
strawberry/…/python.pyShows the built-in Python client type renderer.
strawberry/…/typescript.pyShows the built-in TypeScript client type renderer.
strawberry/…/print_operation.pyShows the built-in GraphQL operation renderer.