A GraphQL mocking solution using mitmproxy to intercept and replace GraphQL responses with predefined mock data.
This repository uses mitmproxy to intercept GraphQL requests and return mock responses from JSON files. This is useful for:
- Frontend development when backend APIs are unavailable
- Testing with consistent, controlled data
- Simulating different response scenarios
# Using pip
pip install mitmproxy
# Using homebrew (macOS)
brew install mitmproxy
# Using apt (Ubuntu/Debian)
sudo apt install mitmproxyTo intercept HTTPS traffic, you need to install mitmproxy's certificate:
-
Start mitmproxy (this generates the certificate):
mitmproxy
-
Configure your browser to use the proxy:
Launch Chrome with proxy settings:
"C:\Program Files\Google\Chrome\Application\chrome.exe" --proxy-server=http://127.0.0.1:8080 -
Install the certificate:
Navigate to http://mitm.it/ and follow the instructions there to download and install the certificate for your operating system
Add your GraphQL mock responses to the mocks/ directory:
// mocks/get_tokens_response.json
{
"data": {
"tokens": [
{ "id": "1", "name": "Token 1" },
{ "id": "2", "name": "Token 2" }
]
}
}Edit graphql_replace_file.py to map GraphQL operation names to mock files:
RESPONSE_MAP = {
"GetTokens": "get_tokens_response.json",
"GetUsers": "get_users_response.json"
}mitmproxy -s graphql_replace_file.pyLaunch Chrome with proxy settings (see chrome.md for details):
"C:\Program Files\Google\Chrome\Application\chrome.exe" --proxy-server=http://127.0.0.1:8080Navigate to your application in the proxied browser. GraphQL requests matching the configured operations will be intercepted and replaced with your mock responses.
graphql_replace_file.py- Main mitmproxy script that intercepts GraphQL requestsmocks/- Directory containing JSON mock response fileschrome.md- Instructions for running Chrome with proxy configuration
The script intercepts requests to /graphql by default. To change this, modify the GRAPHQL_ENDPOINT variable in graphql_replace_file.py.