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.
Python code
18 linesimport 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
{
"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
- Use dataclasses to define the response objects for stronger typing
- 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
More from API design & gRPC
- Build a Bulk Array POST Mock Server in Python medium
- Build a Mock REST API with PUT and GET in Python medium
- Convert Protobuf to JSON and Dict in Python easy
- Create a Data Helper in Python for gRPC-style APIs easy
- Format data in Python using dataclasses like gRPC messages easy
- Generate an OpenAPI Spec from Mock Routes in Python easy
Keep learning
Related tutorials and quizzes for this topic.