How to Mock a GraphQL Query Type in Python

Create a lightweight mock of a GraphQL Query type to simulate repository lookups without a server.

Easy Python 3.9+ Aug 9, 2026 API design & gRPC 14 views 0 copies

Python code

18 lines
Python 3.9+
import json

class Query:
    def __init__(self):
        self.starred_repos = [
            {"id": 1, "name": "graphql", "owner": "graphql"}
        ]

    def repository(self, name):
        if name == "graphql":
            return {"id": 1, "name": "graphql", "stargazerCount": 85000}
        return None


if __name__ == "__main__":
    query = Query()
    result = query.repository("graphql")
    print(json.dumps(result, indent=2))

Output

stdout
{
  "id": 1,
  "name": "graphql",
  "stargazerCount": 85000
}

How it works

This code defines a Query class that mimics the root resolver of a GraphQL schema. The repository method acts as a resolver returning a dict-shaped object when the queried name matches, otherwise returning None to simulate a null response. Using a Python class for the schema allows you to test resolver logic or build a simple mock server without heavyweight dependencies. The json.dumps call formats the result nicely when run as a script for quick verification.

Common mistakes

  • Returning the wrong key names compared to the GraphQL schema contract
  • Forgetting to handle the None case when the requested resource doesn't exist
  • Hardcoding data instead of using a small dataset or fixture for more realistic tests

Variations

  1. Use dataclasses to define the response objects for stronger typing
  2. Wrap the mock in a callable handler for use with a WSGI mock server library

Real-world use cases

  • Unit-testing resolver logic before wiring up a real GraphQL server
  • Providing a local stub for frontend development against a not-yet-built API
  • Simulating schema behavior in integration tests that don't need a network call

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from API design & gRPC

Related tutorials and quizzes for this topic.