Снять GraphQL-схему через introspection
Отправляет introspection-запрос и сохраняет схему GraphQL в JSON.
Что делает скрипт
Скрипт делает POST-запрос к GraphQL-эндпоинту с типовым introspection-запросом и печатает список типов, query и mutation. Токен при необходимости берётся из API_TOKEN и не выводится. Результат можно сохранить в JSON для сравнения версий схемы.
- Introspection может быть отключён на production, это нормально.
Быстрый старт
python graphql_introspection.py http://127.0.0.1:8000/graphql
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python graphql_introspection.py http://127.0.0.1:8000/graphql --output schema.jsonpython graphql_introspection.py https://example.com/graphql --json
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
graphql_introspection.py
#!/usr/bin/env python3
"""GraphQL introspection в JSON-файл."""
from __future__ import annotations
import argparse
import json
import os
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
QUERY = """
query Introspection {
__schema {
queryType { name }
mutationType { name }
subscriptionType { name }
types {
kind
name
description
fields { name type { kind name ofType { kind name } } }
}
}
}
"""
def main() -> int:
parser = argparse.ArgumentParser(description="Снять GraphQL-схему")
parser.add_argument("url", help="GraphQL-эндпоинт")
parser.add_argument("--output", type=Path, default=Path("graphql-schema.json"))
parser.add_argument("--timeout", type=float, default=20.0)
args = parser.parse_args()
headers = {"Content-Type": "application/json", "Accept": "application/json", "User-Agent": "popovdev-scriptdock/1.0"}
token = os.environ.get("API_TOKEN", "")
if token:
headers["Authorization"] = f"Bearer {token}"
body = json.dumps({"query": QUERY, "operationName": "Introspection"}).encode("utf-8")
request = Request(args.url, data=body, headers=headers, method="POST")
try:
with urlopen(request, timeout=args.timeout) as response:
payload = json.loads(response.read(10_000_000).decode("utf-8"))
except HTTPError as error:
print(f"HTTP-ошибка: {error.code} {error.reason}")
print(error.read(2000).decode("utf-8", errors="replace"))
return 1
except URLError as error:
print(f"Не удалось подключиться: {error.reason}")
return 2
except json.JSONDecodeError as error:
print(f"Ответ не JSON: {error}")
return 1
if not isinstance(payload, dict):
print("Ответ GraphQL не является JSON-объектом")
return 1
if payload.get("errors"):
print("GraphQL вернул ошибки:")
for error in payload["errors"]:
print(f" {error.get('message', error)}")
return 1
schema = (payload.get("data") or {}).get("__schema")
if not schema:
print("В ответе нет __schema, introspection может быть отключён")
return 1
args.output.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
query_type = (schema.get("queryType") or {}).get("name", "?")
mutation_type = (schema.get("mutationType") or {}).get("name", "нет")
types = [item.get("name") for item in schema.get("types", []) if item.get("name")]
print(f"Query: {query_type}")
print(f"Mutation: {mutation_type}")
print(f"Типов: {len(types)}")
print("Первые типы: " + ", ".join(types[:15]))
print(f"Схема сохранена: {args.output}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.