#!/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())