Skip to content

Improve Python requests GraphQL codegen readability and fix missing json import #813

@Dev22603

Description

@Dev22603

Summary

I’ve been using the python-requests code generator for GraphQL requests and ran into two issues:

  1. The generated Python snippet makes the GraphQL query and variables hard to read, because they effectively end up in a single JSON string.
  2. In some GraphQL cases, the snippet uses json.dumps(...) but does not always import json, which leads to a runtime error.

This issue describes the current behavior, why it’s problematic, and a proposed improvement. I’ve also implemented a small change set that I can open as a PR.


Current behavior

1. GraphQL query and variables are not clearly separated

For GraphQL requests, the generated Python code:

  • Builds payload in a way that makes the GraphQL query and variables live inside one opaque JSON string.
  • Does not expose query and variables as separate Python variables.
  • As a result, when I copy the generated code into my editor, it’s hard to:
    • See the actual GraphQL query at a glance.
    • Inspect and tweak the variables without digging into a long JSON string.

From a user perspective, I want to think about GraphQL as “query” + “variables,” but the current codegen doesn’t reflect that structure clearly.

2. json.dumps used without guaranteed import json

In some GraphQL scenarios, the generated Python snippet:

  • Calls json.dumps(...) to build the request body.
  • But import json is only added when the Content-Type header is explicitly JSON (e.g. application/json or something ending in +json).

If the GraphQL request doesn’t have a JSON Content-Type header (or has a non-standard one), the snippet can end up using json.dumps without importing json, causing:

NameError: name 'json' is not defined

This breaks the “copy and run” experience for the generated snippet.


User story

As a developer using Postman’s Python requests code generator for GraphQL:

  • I want the generated snippet to show:
    • A clear, readable GraphQL query as a Python string.
    • A clear, readable variables object as a Python dictionary or similar structure.
  • I also want the snippet to:
    • Run without modification (no NameError from missing imports).

Right now, the generated code makes it hard to read and edit the query and variables separately, and it may fail at runtime if json wasn’t imported.


Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions