[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7595Q7H1PDAC0C5DMXV9TTV":3,"skill-same:01M7595Q7H1PDAC0C5DMXV9TTV":64},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":41,"commitSha":42,"skillDirectory":43,"forksCount":44,"repositoryHtmlUrl":45,"repositoryHomepageUrl":46,"ownerHtmlUrl":47,"ownerBlogUrl":6,"ownerDescription":48,"updatedAt":49,"install":50,"resources":63},"01M7595Q7H1PDAC0C5DMXV9TTV","rest-graphql-debug",null,"Debug REST\u002FGraphQL APIs: status codes, auth, schemas, repro.","lukemcqueen\u002Fsteadfaste-fleet","lukemcqueen","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F405240?v=4","01M757MHPAGRXTJAT46SKZP98R","Luke McQueen","01M757MHPZ573KP8DT9GB8SBQ7",4,"MIT","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fsoftware-development\u002Frest-graphql-debug\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: rest-graphql-debug\ndescription: \"Debug REST\u002FGraphQL APIs: status codes, auth, schemas, repro.\"\nversion: 1.2.0\nauthor: eren-karakus0\nlicense: MIT\nmetadata:\n  hermes:\n    tags: [api, rest, graphql, http, debugging, testing, curl, integration]\n    category: software-development\n    related_skills: [root-cause-debugging, test-driven-development]\n---\n\n# API Testing & Debugging\n\nDrive REST and GraphQL diagnosis through Hermes tools — `terminal` for `curl`, `execute_code` for Python `requests`, `web_extract` for vendor docs. Isolate the failing layer before guessing at the fix.\n\n## When to Use\n\n- API returns unexpected status or body\n- Auth fails (401\u002F403 after token refresh, OAuth, API key)\n- Works in Postman but fails in code\n- Webhook \u002F callback integration debugging\n- Building or reviewing API integration tests\n- Rate limiting or pagination issues\n\nSkip for UI rendering, DB query tuning, or DNS\u002Ffirewall infra (escalate).\n\n## Core Principle\n\n**Isolate the layer, then fix.** A 200 OK can hide broken data. A 500 can mask a one-character auth typo. Walk the chain in order; never skip a step.\n\n```\n1. Connectivity   → can we reach the host at all?\n1.5 Timeouts      → connect-slow vs read-slow?\n2. TLS\u002FSSL        → cert valid and trusted?\n3. Auth           → credentials correct and unexpired?\n4. Request format → payload shape match server expectations?\n5. Response parse → does our code accept what came back?\n6. Semantics      → does the data mean what we assume?\n```\n\n## 5-Minute Quickstart\n\n### REST via terminal\n\n```python\n# Verbose request\u002Fresponse exchange\nterminal('curl -v https:\u002F\u002Fapi.example.com\u002Fusers\u002F1')\n\n# POST with JSON\nterminal(\"\"\"curl -X POST https:\u002F\u002Fapi.example.com\u002Fusers \\\\\n  -H 'Content-Type: application\u002Fjson' \\\\\n  -H \"Authorization: Bearer $TOKEN\" \\\\\n  -d '{\"name\":\"test\",\"email\":\"test@example.com\"}'\"\"\")\n\n# Headers only\nterminal('curl -sI https:\u002F\u002Fapi.example.com\u002Fhealth')\n\n# Pretty-print JSON\nterminal('curl -s https:\u002F\u002Fapi.example.com\u002Fusers | python3 -m json.tool')\n```\n\n### GraphQL via terminal\n\n```python\nterminal(\"\"\"curl -X POST https:\u002F\u002Fapi.example.com\u002Fgraphql \\\\\n  -H 'Content-Type: application\u002Fjson' \\\\\n  -H \"Authorization: Bearer $TOKEN\" \\\\\n  -d '{\"query\":\"{ user(id: 1) { name email } }\"}'\"\"\")\n```\n\n**GraphQL gotcha:** servers often return HTTP 200 even when the query failed. Always inspect the `errors` field regardless of status code:\n\n```python\nexecute_code('''\nimport os, requests\nresp = requests.post(\n    \"https:\u002F\u002Fapi.example.com\u002Fgraphql\",\n    json={\"query\": \"{ user(id: 1) { name email } }\"},\n    headers={\"Authorization\": f\"Bearer {os.environ['TOKEN']}\"},\n    timeout=10,\n)\ndata = resp.json()\nif data.get(\"errors\"):\n    for err in data[\"errors\"]:\n        print(f\"GraphQL error: {err['message']} (path: {err.get('path')})\")\nprint(data.get(\"data\"))\n''')\n```\n\n### Python (requests) via execute_code\n\n```python\nexecute_code('''\nimport requests\nresp = requests.get(\n    \"https:\u002F\u002Fapi.example.com\u002Fusers\u002F1\",\n    headers={\"Authorization\": \"Bearer \u003CTOKEN>\"},\n    timeout=(3.05, 30),  # (connect, read)\n)\nprint(resp.status_code, dict(resp.headers))\nprint(resp.text[:500])\n''')\n```\n\n## Layered Debug Flow\n\n### Step 1 — Connectivity\n\n```python\nterminal('nslookup api.example.com')\nterminal('curl -v --connect-timeout 5 https:\u002F\u002Fapi.example.com\u002Fhealth')\n```\n\nFailures: DNS not resolving, firewall, VPN required, proxy missing.\n\n### Step 1.5 — Timeouts\n\nDistinguish *can't reach* from *reaches but slow*:\n\n```python\nterminal('''curl -w \"dns:%{time_namelookup}s connect:%{time_connect}s tls:%{time_appconnect}s ttfb:%{time_starttransfer}s total:%{time_total}s\\\\n\" \\\\\n  -o \u002Fdev\u002Fnull -s https:\u002F\u002Fapi.example.com\u002Fendpoint''')\n```\n\nIn Python, always pass a tuple timeout — `requests` has no default and will hang forever:\n\n```python\nexecute_code('''\nimport requests\nfrom requests.exceptions import ConnectTimeout, ReadTimeout\ntry:\n    requests.get(url, timeout=(3.05, 30))\nexcept ConnectTimeout:\n    print(\"Cannot reach host — DNS, firewall, VPN\")\nexcept ReadTimeout:\n    print(\"Connected but server is slow\")\n''')\n```\n\nDiagnosis: high `time_connect` is network\u002Ffirewall; high `time_starttransfer` with low `time_connect` is a slow server.\n\n### Step 2 — TLS\u002FSSL\n\n```python\nterminal('curl -vI https:\u002F\u002Fapi.example.com 2>&1 | grep -E \"SSL|subject|expire|issuer\"')\n```\n\nFailures: expired cert, self-signed, hostname mismatch, missing CA bundle. Use `-k` only for ad-hoc debug, never in code.\n\n### Step 3 — Authentication\n\n```python\n# Token validity check\nterminal('curl -s -o \u002Fdev\u002Fnull -w \"%{http_code}\\\\n\" -H \"Authorization: Bearer $TOKEN\" https:\u002F\u002Fapi.example.com\u002Fme')\n\n# Decode JWT exp claim — handles base64url padding correctly\nexecute_code('''\nimport json, base64, os\ntok = os.environ[\"TOKEN\"]\npayload = tok.split(\".\")[1]\npayload += \"=\" * (-len(payload) % 4)\nprint(json.dumps(json.loads(base64.urlsafe_b64decode(payload)), indent=2))\n''')\n```\n\nChecklist:\n- Token expired? (`exp` claim in JWT)\n- Right scheme? Bearer vs Basic vs Token vs `X-Api-Key`\n- Right environment? Staging key on prod is a classic\n- API key in header vs query param (`?api_key=…`)?\n\n### Step 4 — Request Format\n\n```python\nterminal(\"\"\"curl -v -X POST https:\u002F\u002Fapi.example.com\u002Fendpoint \\\\\n  -H 'Content-Type: application\u002Fjson' \\\\\n  -d '{\"key\":\"value\"}' 2>&1\"\"\")\n```\n\n**Content-Type \u002F body mismatch — the silent 415\u002F400:**\n\n```python\n# WRONG — data= sends form-encoded, header lies\nrequests.post(url, data='{\"k\":\"v\"}', headers={\"Content-Type\": \"application\u002Fjson\"})\n\n# RIGHT — json= auto-sets header AND serializes\nrequests.post(url, json={\"k\": \"v\"})\n\n# WRONG — Accept says XML, code calls .json()\nrequests.get(url, headers={\"Accept\": \"text\u002Fxml\"})\n\n# RIGHT — let requests build multipart with boundary\nrequests.post(url, files={\"file\": open(\"doc.pdf\", \"rb\")})\n```\n\nCommon: form-encoded vs JSON, missing required fields, wrong HTTP method, unencoded query params.\n\n### Step 5 — Response Parsing\n\nAlways inspect content-type before calling `.json()`:\n\n```python\nexecute_code('''\nimport requests\nresp = requests.post(url, json=payload, timeout=10)\nprint(f\"status={resp.status_code}\")\nprint(f\"headers={dict(resp.headers)}\")\nct = resp.headers.get(\"Content-Type\", \"\")\nif \"application\u002Fjson\" in ct:\n    print(resp.json())\nelse:\n    print(f\"unexpected content-type {ct!r}, body={resp.text[:500]!r}\")\n''')\n```\n\nFailures: HTML error page where JSON expected, empty body, wrong charset.\n\n### Step 6 — Semantic Validation\n\nParsed cleanly — but is the data *correct*?\n\n- Does `\"status\": \"active\"` mean what your code thinks?\n- ID in response matches the one requested?\n- Timestamps in expected timezone?\n- Pagination returning all results, or just page 1?\n\n## HTTP Status Playbook\n\n### 401 Unauthorized — credentials missing or invalid\n\n1. `Authorization` header actually present? (`curl -v` to confirm)\n2. Token correct and unexpired?\n3. Right auth scheme? (`Bearer` vs `Basic` vs `Token`)\n4. Some APIs use query param (`?api_key=…`) instead of header.\n\n### 403 Forbidden — authenticated but not authorized\n\n1. Token has the required scopes\u002Fpermissions?\n2. Resource owned by a different account?\n3. IP allowlist blocking you?\n4. CORS in browser? (check `Access-Control-Allow-Origin`)\n\n### 404 Not Found — resource doesn't exist or URL is wrong\n\n1. Path correct? (trailing slash, typo, version prefix)\n2. Resource ID exists?\n3. Right API version (`\u002Fv1\u002F` vs `\u002Fv2\u002F`)?\n4. Right base URL (staging vs prod)?\n\n### 409 Conflict — state collision\n\n1. Resource already exists (duplicate create)?\n2. Stale `ETag` \u002F `If-Match`?\n3. Concurrent modification by another process?\n\n### 422 Unprocessable Entity — valid JSON, invalid data\n\nThe error body usually names the bad fields. Check:\n- Field types (string vs int, date format)\n- Required vs optional\n- Enum values inside the allowed set\n\n### 429 Too Many Requests — rate limited\n\nCheck `Retry-After` and `X-RateLimit-*` headers. Exponential backoff:\n\n```python\nexecute_code('''\nimport time, requests\n\ndef with_backoff(method, url, **kwargs):\n    for attempt in range(5):\n        resp = requests.request(method, url, **kwargs)\n        if resp.status_code != 429:\n            return resp\n        wait = int(resp.headers.get(\"Retry-After\", 2 ** attempt))\n        time.sleep(wait)\n    return resp\n''')\n```\n\n### 5xx — server-side, usually not your fault\n\n- **500** — server bug. Capture correlation ID, file with provider.\n- **502** — upstream down. Backoff + retry.\n- **503** — overloaded \u002F maintenance. Check status page.\n- **504** — upstream timeout. Reduce payload or raise timeout.\n\nFor all 5xx: backoff with jitter, alert on persistence.\n\n## Pagination & Idempotency\n\n**Pagination.** Verify you're getting *all* results. Look for `next_cursor`, `next_page`, `total_count`. Two patterns:\n- Offset (`?limit=100&offset=200`) — simple, can skip items if data shifts.\n- Cursor (`?cursor=abc123`) — preferred for live or large datasets.\n\n**Idempotency.** For non-idempotent operations (POST), send `Idempotency-Key: \u003Cuuid>` so retries don't double-charge \u002F double-create. Mandatory for payments and orders.\n\n## Contract Validation\n\nCatch schema drift before it hits production:\n\n```python\nexecute_code('''\nimport requests\n\ndef validate_user(data: dict) -> list[str]:\n    errors = []\n    required = {\"id\": int, \"email\": str, \"created_at\": str}\n    for field, expected in required.items():\n        if field not in data:\n            errors.append(f\"missing field: {field}\")\n        elif not isinstance(data[field], expected):\n            errors.append(f\"{field}: want {expected.__name__}, got {type(data[field]).__name__}\")\n    return errors\n\nresp = requests.get(f\"{BASE}\u002Fusers\u002F1\", headers=HEADERS, timeout=10)\nissues = validate_user(resp.json())\nif issues:\n    print(f\"contract violations: {issues}\")\n''')\n```\n\nRun after API upgrades, when integrating new third parties, or in CI smoke tests.\n\n## Correlation IDs\n\nAlways capture the provider's request ID — fastest path to vendor support:\n\n```python\nexecute_code('''\nimport requests\nresp = requests.post(url, json=payload, headers=headers, timeout=10)\nrequest_id = (\n    resp.headers.get(\"X-Request-Id\")\n    or resp.headers.get(\"X-Trace-Id\")\n    or resp.headers.get(\"CF-Ray\")  # Cloudflare\n)\nif resp.status_code >= 400:\n    print(f\"failed status={resp.status_code} req_id={request_id} ts={resp.headers.get('Date')}\")\n''')\n```\n\n**Vendor bug-report template:**\n\n```\nEndpoint:    POST \u002Fapi\u002Fv1\u002Forders\nRequest ID:  req_abc123xyz\nTimestamp:   2026-03-17T14:30:00Z\nStatus:      500\nExpected:    201 with order object\nActual:      500 {\"error\":\"internal server error\"}\nRepro:       curl -X POST … (auth: \u003CREDACTED>)\n```\n\n## Regression Test Template\n\nDrop this into `tests\u002F` and run via `terminal('pytest tests\u002Ftest_api_smoke.py -v')`:\n\n```python\nimport os, requests, pytest\n\nBASE_URL = os.environ.get(\"API_BASE_URL\", \"https:\u002F\u002Fapi.example.com\")\nTOKEN    = os.environ.get(\"API_TOKEN\", \"\")\nHEADERS  = {\"Authorization\": f\"Bearer {TOKEN}\"}\n\nclass TestAPISmoke:\n    def test_health(self):\n        resp = requests.get(f\"{BASE_URL}\u002Fhealth\", timeout=5)\n        assert resp.status_code == 200\n\n    def test_list_users_returns_array(self):\n        resp = requests.get(f\"{BASE_URL}\u002Fusers\", headers=HEADERS, timeout=10)\n        assert resp.status_code == 200\n        data = resp.json()\n        assert isinstance(data.get(\"data\", data), list)\n\n    def test_get_user_required_fields(self):\n        resp = requests.get(f\"{BASE_URL}\u002Fusers\u002F1\", headers=HEADERS, timeout=10)\n        assert resp.status_code in (200, 404)\n        if resp.status_code == 200:\n            user = resp.json()\n            assert \"id\" in user and \"email\" in user\n\n    def test_invalid_auth_returns_401(self):\n        resp = requests.get(\n            f\"{BASE_URL}\u002Fusers\",\n            headers={\"Authorization\": \"Bearer invalid-token\"},\n            timeout=10,\n        )\n        assert resp.status_code == 401\n```\n\n## Security\n\n### Token handling\n- Never log full tokens. Redact: `Bearer \u003CREDACTED>`.\n- Never hardcode tokens in scripts. Read from env (`os.environ[\"API_TOKEN\"]`) or `${HERMES_HOME:-~\u002F.hermes}\u002F.env`.\n- Rotate immediately if a token surfaces in logs, error messages, or git history.\n\n### Safe logging\n\n```python\ndef redact_auth(headers: dict) -> dict:\n    sensitive = {\"authorization\", \"x-api-key\", \"cookie\", \"set-cookie\"}\n    return {k: (\"\u003CREDACTED>\" if k.lower() in sensitive else v) for k, v in headers.items()}\n```\n\n### Leak checklist\n\n- [ ] **Credentials in URLs.** API keys in query strings end up in server logs, browser history, referrer headers — use headers.\n- [ ] **PII in error responses.** `404 on \u002Fusers\u002F123` shouldn't reveal whether the user exists (enumeration).\n- [ ] **Stack traces in prod.** 500s shouldn't leak file paths, framework versions.\n- [ ] **Internal hostnames\u002FIPs.** `10.x.x.x`, `internal-api.corp.local` in error bodies.\n- [ ] **Tokens echoed back.** Some APIs include the auth token in error details. Verify they don't.\n- [ ] **Verbose `Server` \u002F `X-Powered-By`.** Stack-info leaks. Note for security review.\n\n## Hermes Tool Patterns\n\n### terminal — for curl, dig, openssl\n\n```python\nterminal('curl -sI https:\u002F\u002Fapi.example.com')\nterminal('openssl s_client -connect api.example.com:443 -servername api.example.com \u003C\u002Fdev\u002Fnull 2>\u002Fdev\u002Fnull | openssl x509 -noout -dates')\n```\n\n### execute_code — for multi-step Python flows\n\nWhen debugging spans auth → fetch → paginate → validate, use `execute_code`. Variables persist for the script, results print to stdout, no risk of token spam in your context:\n\n```python\nexecute_code('''\nimport os, requests\n\ntoken = os.environ[\"API_TOKEN\"]\nbase  = \"https:\u002F\u002Fapi.example.com\"\nH     = {\"Authorization\": f\"Bearer {token}\"}\n\n# 1. auth\nme = requests.get(f\"{base}\u002Fme\", headers=H, timeout=10)\nprint(f\"auth {me.status_code}\")\n\n# 2. paginate\nall_users, cursor = [], None\nwhile True:\n    params = {\"cursor\": cursor} if cursor else {}\n    r = requests.get(f\"{base}\u002Fusers\", headers=H, params=params, timeout=10)\n    body = r.json()\n    all_users.extend(body[\"data\"])\n    cursor = body.get(\"next_cursor\")\n    if not cursor:\n        break\nprint(f\"users={len(all_users)}\")\n''')\n```\n\n### web_extract — for vendor API docs\n\nPull the spec for the endpoint you're debugging instead of guessing:\n\n```python\nweb_extract(urls=[\"https:\u002F\u002Fdocs.example.com\u002Fapi\u002Fv1\u002Fusers\"])\n```\n\n### delegate_task — for full CRUD test sweeps\n\n```python\ndelegate_task(\n    goal=\"Test all CRUD endpoints for \u002Fapi\u002Fv1\u002Fusers\",\n    context=\"\"\"\nFollow the rest-graphql-debug skill (optional-skills\u002Fsoftware-development\u002Frest-graphql-debug).\nBase URL: https:\u002F\u002Fapi.example.com\nAuth: Bearer token from API_TOKEN env var.\n\nFor each verb (POST, GET, PATCH, DELETE):\n  - happy path: assert status + response schema\n  - error cases: 400, 404, 422\n  - log a repro curl for any failure (redact tokens)\n\nOutput: pass\u002Ffail per endpoint + correlation IDs for failures.\n\"\"\",\n    toolsets=[\"terminal\", \"file\"],\n)\n```\n\n## Output Format\n\nWhen reporting findings:\n\n```\n## Finding\nEndpoint: POST \u002Fapi\u002Fv1\u002Fusers\nStatus:   422 Unprocessable Entity\nReq ID:   req_abc123xyz\n\n## Repro\ncurl -X POST https:\u002F\u002Fapi.example.com\u002Fapi\u002Fv1\u002Fusers \\\n  -H 'Content-Type: application\u002Fjson' \\\n  -H 'Authorization: Bearer \u003CREDACTED>' \\\n  -d '{\"name\":\"test\"}'\n\n## Root Cause\nMissing required field `email`. Server validation rejects before processing.\n\n## Fix\n-d '{\"name\":\"test\",\"email\":\"test@example.com\"}'\n```\n\n## Related\n\n- `root-cause-debugging` — once the failing API layer is isolated, root-cause your code\n- `test-driven-development` — write the regression test before shipping the fix\n","# API Testing & Debugging\n\nDrive REST and GraphQL diagnosis through Hermes tools — `terminal` for `curl`, `execute_code` for Python `requests`, `web_extract` for vendor docs. Isolate the failing layer before guessing at the fix.\n\n## When to Use\n\n- API returns unexpected status or body\n- Auth fails (401\u002F403 after token refresh, OAuth, API key)\n- Works in Postman but fails in code\n- Webhook \u002F callback integration debugging\n- Building or reviewing API integration tests\n- Rate limiting or pagination issues\n\nSkip for UI rendering, DB query tuning, or DNS\u002Ffirewall infra (escalate).\n\n## Core Principle\n\n**Isolate the layer, then fix.** A 200 OK can hide broken data. A 500 can mask a one-character auth typo. Walk the chain in order; never skip a step.\n\n```\n1. Connectivity   → can we reach the host at all?\n1.5 Timeouts      → connect-slow vs read-slow?\n2. TLS\u002FSSL        → cert valid and trusted?\n3. Auth           → credentials correct and unexpired?\n4. Request format → payload shape match server expectations?\n5. Response parse → does our code accept what came back?\n6. Semantics      → does the data mean what we assume?\n```\n\n## 5-Minute Quickstart\n\n### REST via terminal\n\n```python\n# Verbose request\u002Fresponse exchange\nterminal('curl -v https:\u002F\u002Fapi.example.com\u002Fusers\u002F1')\n\n# POST with JSON\nterminal(\"\"\"curl -X POST https:\u002F\u002Fapi.example.com\u002Fusers \\\\\n  -H 'Content-Type: application\u002Fjson' \\\\\n  -H \"Authorization: Bearer $TOKEN\" \\\\\n  -d '{\"name\":\"test\",\"email\":\"test@example.com\"}'\"\"\")\n\n# Headers only\nterminal('curl -sI https:\u002F\u002Fapi.example.com\u002Fhealth')\n\n# Pretty-print JSON\nterminal('curl -s https:\u002F\u002Fapi.example.com\u002Fusers | python3 -m json.tool')\n```\n\n### GraphQL via terminal\n\n```python\nterminal(\"\"\"curl -X POST https:\u002F\u002Fapi.example.com\u002Fgraphql \\\\\n  -H 'Content-Type: application\u002Fjson' \\\\\n  -H \"Authorization: Bearer $TOKEN\" \\\\\n  -d '{\"query\":\"{ user(id: 1) { name email } }\"}'\"\"\")\n```\n\n**GraphQL gotcha:** servers often return HTTP 200 even when the query failed. Always inspect the `errors` field regardless of status code:\n\n```python\nexecute_code('''\nimport os, requests\nresp = requests.post(\n    \"https:\u002F\u002Fapi.example.com\u002Fgraphql\",\n    json={\"query\": \"{ user(id: 1) { name email } }\"},\n    headers={\"Authorization\": f\"Bearer {os.environ['TOKEN']}\"},\n    timeout=10,\n)\ndata = resp.json()\nif data.get(\"errors\"):\n    for err in data[\"errors\"]:\n        print(f\"GraphQL error: {err['message']} (path: {err.get('path')})\")\nprint(data.get(\"data\"))\n''')\n```\n\n### Python (requests) via execute_code\n\n```python\nexecute_code('''\nimport requests\nresp = requests.get(\n    \"https:\u002F\u002Fapi.example.com\u002Fusers\u002F1\",\n    headers={\"Authorization\": \"Bearer \u003CTOKEN>\"},\n    timeout=(3.05, 30),  # (connect, read)\n)\nprint(resp.status_code, dict(resp.headers))\nprint(resp.text[:500])\n''')\n```\n\n## Layered Debug Flow\n\n### Step 1 — Connectivity\n\n```python\nterminal('nslookup api.example.com')\nterminal('curl -v --connect-timeout 5 https:\u002F\u002Fapi.example.com\u002Fhealth')\n```\n\nFailures: DNS not resolving, firewall, VPN required, proxy missing.\n\n### Step 1.5 — Timeouts\n\nDistinguish *can't reach* from *reaches but slow*:\n\n```python\nterminal('''curl -w \"dns:%{time_namelookup}s connect:%{time_connect}s tls:%{time_appconnect}s ttfb:%{time_starttransfer}s total:%{time_total}s\\\\n\" \\\\\n  -o \u002Fdev\u002Fnull -s https:\u002F\u002Fapi.example.com\u002Fendpoint''')\n```\n\nIn Python, always pass a tuple timeout — `requests` has no default and will hang forever:\n\n```python\nexecute_code('''\nimport requests\nfrom requests.exceptions import ConnectTimeout, ReadTimeout\ntry:\n    requests.get(url, timeout=(3.05, 30))\nexcept ConnectTimeout:\n    print(\"Cannot reach host — DNS, firewall, VPN\")\nexcept ReadTimeout:\n    print(\"Connected but server is slow\")\n''')\n```\n\nDiagnosis: high `time_connect` is network\u002Ffirewall; high `time_starttransfer` with low `time_connect` is a slow server.\n\n### Step 2 — TLS\u002FSSL\n\n```python\nterminal('curl -vI https:\u002F\u002Fapi.example.com 2>&1 | grep -E \"SSL|subject|expire|issuer\"')\n```\n\nFailures: expired cert, self-signed, hostname mismatch, missing CA bundle. Use `-k` only for ad-hoc debug, never in code.\n\n### Step 3 — Authentication\n\n```python\n# Token validity check\nterminal('curl -s -o \u002Fdev\u002Fnull -w \"%{http_code}\\\\n\" -H \"Authorization: Bearer $TOKEN\" https:\u002F\u002Fapi.example.com\u002Fme')\n\n# Decode JWT exp claim — handles base64url padding correctly\nexecute_code('''\nimport json, base64, os\ntok = os.environ[\"TOKEN\"]\npayload = tok.split(\".\")[1]\npayload += \"=\" * (-len(payload) % 4)\nprint(json.dumps(json.loads(base64.urlsafe_b64decode(payload)), indent=2))\n''')\n```\n\nChecklist:\n- Token expired? (`exp` claim in JWT)\n- Right scheme? Bearer vs Basic vs Token vs `X-Api-Key`\n- Right environment? Staging key on prod is a classic\n- API key in header vs query param (`?api_key=…`)?\n\n### Step 4 — Request Format\n\n```python\nterminal(\"\"\"curl -v -X POST https:\u002F\u002Fapi.example.com\u002Fendpoint \\\\\n  -H 'Content-Type: application\u002Fjson' \\\\\n  -d '{\"key\":\"value\"}' 2>&1\"\"\")\n```\n\n**Content-Type \u002F body mismatch — the silent 415\u002F400:**\n\n```python\n# WRONG — data= sends form-encoded, header lies\nrequests.post(url, data='{\"k\":\"v\"}', headers={\"Content-Type\": \"application\u002Fjson\"})\n\n# RIGHT — json= auto-sets header AND serializes\nrequests.post(url, json={\"k\": \"v\"})\n\n# WRONG — Accept says XML, code calls .json()\nrequests.get(url, headers={\"Accept\": \"text\u002Fxml\"})\n\n# RIGHT — let requests build multipart with boundary\nrequests.post(url, files={\"file\": open(\"doc.pdf\", \"rb\")})\n```\n\nCommon: form-encoded vs JSON, missing required fields, wrong HTTP method, unencoded query params.\n\n### Step 5 — Response Parsing\n\nAlways inspect content-type before calling `.json()`:\n\n```python\nexecute_code('''\nimport requests\nresp = requests.post(url, json=payload, timeout=10)\nprint(f\"status={resp.status_code}\")\nprint(f\"headers={dict(resp.headers)}\")\nct = resp.headers.get(\"Content-Type\", \"\")\nif \"application\u002Fjson\" in ct:\n    print(resp.json())\nelse:\n    print(f\"unexpected content-type {ct!r}, body={resp.text[:500]!r}\")\n''')\n```\n\nFailures: HTML error page where JSON expected, empty body, wrong charset.\n\n### Step 6 — Semantic Validation\n\nParsed cleanly — but is the data *correct*?\n\n- Does `\"status\": \"active\"` mean what your code thinks?\n- ID in response matches the one requested?\n- Timestamps in expected timezone?\n- Pagination returning all results, or just page 1?\n\n## HTTP Status Playbook\n\n### 401 Unauthorized — credentials missing or invalid\n\n1. `Authorization` header actually present? (`curl -v` to confirm)\n2. Token correct and unexpired?\n3. Right auth scheme? (`Bearer` vs `Basic` vs `Token`)\n4. Some APIs use query param (`?api_key=…`) instead of header.\n\n### 403 Forbidden — authenticated but not authorized\n\n1. Token has the required scopes\u002Fpermissions?\n2. Resource owned by a different account?\n3. IP allowlist blocking you?\n4. CORS in browser? (check `Access-Control-Allow-Origin`)\n\n### 404 Not Found — resource doesn't exist or URL is wrong\n\n1. Path correct? (trailing slash, typo, version prefix)\n2. Resource ID exists?\n3. Right API version (`\u002Fv1\u002F` vs `\u002Fv2\u002F`)?\n4. Right base URL (staging vs prod)?\n\n### 409 Conflict — state collision\n\n1. Resource already exists (duplicate create)?\n2. Stale `ETag` \u002F `If-Match`?\n3. Concurrent modification by another process?\n\n### 422 Unprocessable Entity — valid JSON, invalid data\n\nThe error body usually names the bad fields. Check:\n- Field types (string vs int, date format)\n- Required vs optional\n- Enum values inside the allowed set\n\n### 429 Too Many Requests — rate limited\n\nCheck `Retry-After` and `X-RateLimit-*` headers. Exponential backoff:\n\n```python\nexecute_code('''\nimport time, requests\n\ndef with_backoff(method, url, **kwargs):\n    for attempt in range(5):\n        resp = requests.request(method, url, **kwargs)\n        if resp.status_code != 429:\n            return resp\n        wait = int(resp.headers.get(\"Retry-After\", 2 ** attempt))\n        time.sleep(wait)\n    return resp\n''')\n```\n\n### 5xx — server-side, usually not your fault\n\n- **500** — server bug. Capture correlation ID, file with provider.\n- **502** — upstream down. Backoff + retry.\n- **503** — overloaded \u002F maintenance. Check status page.\n- **504** — upstream timeout. Reduce payload or raise timeout.\n\nFor all 5xx: backoff with jitter, alert on persistence.\n\n## Pagination & Idempotency\n\n**Pagination.** Verify you're getting *all* results. Look for `next_cursor`, `next_page`, `total_count`. Two patterns:\n- Offset (`?limit=100&offset=200`) — simple, can skip items if data shifts.\n- Cursor (`?cursor=abc123`) — preferred for live or large datasets.\n\n**Idempotency.** For non-idempotent operations (POST), send `Idempotency-Key: \u003Cuuid>` so retries don't double-charge \u002F double-create. Mandatory for payments and orders.\n\n## Contract Validation\n\nCatch schema drift before it hits production:\n\n```python\nexecute_code('''\nimport requests\n\ndef validate_user(data: dict) -> list[str]:\n    errors = []\n    required = {\"id\": int, \"email\": str, \"created_at\": str}\n    for field, expected in required.items():\n        if field not in data:\n            errors.append(f\"missing field: {field}\")\n        elif not isinstance(data[field], expected):\n            errors.append(f\"{field}: want {expected.__name__}, got {type(data[field]).__name__}\")\n    return errors\n\nresp = requests.get(f\"{BASE}\u002Fusers\u002F1\", headers=HEADERS, timeout=10)\nissues = validate_user(resp.json())\nif issues:\n    print(f\"contract violations: {issues}\")\n''')\n```\n\nRun after API upgrades, when integrating new third parties, or in CI smoke tests.\n\n## Correlation IDs\n\nAlways capture the provider's request ID — fastest path to vendor support:\n\n```python\nexecute_code('''\nimport requests\nresp = requests.post(url, json=payload, headers=headers, timeout=10)\nrequest_id = (\n    resp.headers.get(\"X-Request-Id\")\n    or resp.headers.get(\"X-Trace-Id\")\n    or resp.headers.get(\"CF-Ray\")  # Cloudflare\n)\nif resp.status_code >= 400:\n    print(f\"failed status={resp.status_code} req_id={request_id} ts={resp.headers.get('Date')}\")\n''')\n```\n\n**Vendor bug-report template:**\n\n```\nEndpoint:    POST \u002Fapi\u002Fv1\u002Forders\nRequest ID:  req_abc123xyz\nTimestamp:   2026-03-17T14:30:00Z\nStatus:      500\nExpected:    201 with order object\nActual:      500 {\"error\":\"internal server error\"}\nRepro:       curl -X POST … (auth: \u003CREDACTED>)\n```\n\n## Regression Test Template\n\nDrop this into `tests\u002F` and run via `terminal('pytest tests\u002Ftest_api_smoke.py -v')`:\n\n```python\nimport os, requests, pytest\n\nBASE_URL = os.environ.get(\"API_BASE_URL\", \"https:\u002F\u002Fapi.example.com\")\nTOKEN    = os.environ.get(\"API_TOKEN\", \"\")\nHEADERS  = {\"Authorization\": f\"Bearer {TOKEN}\"}\n\nclass TestAPISmoke:\n    def test_health(self):\n        resp = requests.get(f\"{BASE_URL}\u002Fhealth\", timeout=5)\n        assert resp.status_code == 200\n\n    def test_list_users_returns_array(self):\n        resp = requests.get(f\"{BASE_URL}\u002Fusers\", headers=HEADERS, timeout=10)\n        assert resp.status_code == 200\n        data = resp.json()\n        assert isinstance(data.get(\"data\", data), list)\n\n    def test_get_user_required_fields(self):\n        resp = requests.get(f\"{BASE_URL}\u002Fusers\u002F1\", headers=HEADERS, timeout=10)\n        assert resp.status_code in (200, 404)\n        if resp.status_code == 200:\n            user = resp.json()\n            assert \"id\" in user and \"email\" in user\n\n    def test_invalid_auth_returns_401(self):\n        resp = requests.get(\n            f\"{BASE_URL}\u002Fusers\",\n            headers={\"Authorization\": \"Bearer invalid-token\"},\n            timeout=10,\n        )\n        assert resp.status_code == 401\n```\n\n## Security\n\n### Token handling\n- Never log full tokens. Redact: `Bearer \u003CREDACTED>`.\n- Never hardcode tokens in scripts. Read from env (`os.environ[\"API_TOKEN\"]`) or `${HERMES_HOME:-~\u002F.hermes}\u002F.env`.\n- Rotate immediately if a token surfaces in logs, error messages, or git history.\n\n### Safe logging\n\n```python\ndef redact_auth(headers: dict) -> dict:\n    sensitive = {\"authorization\", \"x-api-key\", \"cookie\", \"set-cookie\"}\n    return {k: (\"\u003CREDACTED>\" if k.lower() in sensitive else v) for k, v in headers.items()}\n```\n\n### Leak checklist\n\n- [ ] **Credentials in URLs.** API keys in query strings end up in server logs, browser history, referrer headers — use headers.\n- [ ] **PII in error responses.** `404 on \u002Fusers\u002F123` shouldn't reveal whether the user exists (enumeration).\n- [ ] **Stack traces in prod.** 500s shouldn't leak file paths, framework versions.\n- [ ] **Internal hostnames\u002FIPs.** `10.x.x.x`, `internal-api.corp.local` in error bodies.\n- [ ] **Tokens echoed back.** Some APIs include the auth token in error details. Verify they don't.\n- [ ] **Verbose `Server` \u002F `X-Powered-By`.** Stack-info leaks. Note for security review.\n\n## Hermes Tool Patterns\n\n### terminal — for curl, dig, openssl\n\n```python\nterminal('curl -sI https:\u002F\u002Fapi.example.com')\nterminal('openssl s_client -connect api.example.com:443 -servername api.example.com \u003C\u002Fdev\u002Fnull 2>\u002Fdev\u002Fnull | openssl x509 -noout -dates')\n```\n\n### execute_code — for multi-step Python flows\n\nWhen debugging spans auth → fetch → paginate → validate, use `execute_code`. Variables persist for the script, results print to stdout, no risk of token spam in your context:\n\n```python\nexecute_code('''\nimport os, requests\n\ntoken = os.environ[\"API_TOKEN\"]\nbase  = \"https:\u002F\u002Fapi.example.com\"\nH     = {\"Authorization\": f\"Bearer {token}\"}\n\n# 1. auth\nme = requests.get(f\"{base}\u002Fme\", headers=H, timeout=10)\nprint(f\"auth {me.status_code}\")\n\n# 2. paginate\nall_users, cursor = [], None\nwhile True:\n    params = {\"cursor\": cursor} if cursor else {}\n    r = requests.get(f\"{base}\u002Fusers\", headers=H, params=params, timeout=10)\n    body = r.json()\n    all_users.extend(body[\"data\"])\n    cursor = body.get(\"next_cursor\")\n    if not cursor:\n        break\nprint(f\"users={len(all_users)}\")\n''')\n```\n\n### web_extract — for vendor API docs\n\nPull the spec for the endpoint you're debugging instead of guessing:\n\n```python\nweb_extract(urls=[\"https:\u002F\u002Fdocs.example.com\u002Fapi\u002Fv1\u002Fusers\"])\n```\n\n### delegate_task — for full CRUD test sweeps\n\n```python\ndelegate_task(\n    goal=\"Test all CRUD endpoints for \u002Fapi\u002Fv1\u002Fusers\",\n    context=\"\"\"\nFollow the rest-graphql-debug skill (optional-skills\u002Fsoftware-development\u002Frest-graphql-debug).\nBase URL: https:\u002F\u002Fapi.example.com\nAuth: Bearer token from API_TOKEN env var.\n\nFor each verb (POST, GET, PATCH, DELETE):\n  - happy path: assert status + response schema\n  - error cases: 400, 404, 422\n  - log a repro curl for any failure (redact tokens)\n\nOutput: pass\u002Ffail per endpoint + correlation IDs for failures.\n\"\"\",\n    toolsets=[\"terminal\", \"file\"],\n)\n```\n\n## Output Format\n\nWhen reporting findings:\n\n```\n## Finding\nEndpoint: POST \u002Fapi\u002Fv1\u002Fusers\nStatus:   422 Unprocessable Entity\nReq ID:   req_abc123xyz\n\n## Repro\ncurl -X POST https:\u002F\u002Fapi.example.com\u002Fapi\u002Fv1\u002Fusers \\\n  -H 'Content-Type: application\u002Fjson' \\\n  -H 'Authorization: Bearer \u003CREDACTED>' \\\n  -d '{\"name\":\"test\"}'\n\n## Root Cause\nMissing required field `email`. Server validation rejects before processing.\n\n## Fix\n-d '{\"name\":\"test\",\"email\":\"test@example.com\"}'\n```\n\n## Related\n\n- `root-cause-debugging` — once the failing API layer is isolated, root-cause your code\n- `test-driven-development` — write the regression test before shipping the fix\n",{"name":5,"author":24,"license":15,"version":25,"metadata":26,"description":7},"eren-karakus0","1.2.0",{"hermes":27},{"tags":28,"category":37,"related_skills":38},[29,30,31,32,33,34,35,36],"api","rest","graphql","http","debugging","testing","curl","integration","software-development",[39,40],"root-cause-debugging","test-driven-development","main","2e6aa8d15ab0a366c90be54f61bf9c6e97015e83","skills\u002Fsoftware-development\u002Frest-graphql-debug",1,"https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet","steadfaste.com","https:\u002F\u002Fgithub.com\u002Flukemcqueen","AI Architect | Building Hermes Cortex: governed multi-agent AI for autonomous software engineering | Enterprise Tech Consultant","2026-11-14 22:33:34",{"source":8,"skillName":5,"commands":51,"prompt":61,"zipAvailable":62},[52,55,58],{"tool":53,"command":54},"npx","npx skills add lukemcqueen\u002Fsteadfaste-fleet --skill rest-graphql-debug",{"tool":56,"command":57},"bunx","bunx skills add lukemcqueen\u002Fsteadfaste-fleet --skill rest-graphql-debug",{"tool":59,"command":60},"pnpm","pnpm dlx skills add lukemcqueen\u002Fsteadfaste-fleet --skill rest-graphql-debug","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fsoftware-development\u002Frest-graphql-debug\u002FSKILL.md",true,[],[65,73,80,87,94,101],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":72},"01M7DXY4G8NSVB59K8B6S2AQNP","macbook-linux-maintenance","Legacy MacBook Linux fixes: GPU wedge, reboot hang, thermal.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fmacbook-linux-maintenance\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":72},"01M7DXXYJCXFJ3TGB84ZQ8KFE6","governance-regression-triage","Triage a host's governance issues: what changed.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fgovernance-regression-triage\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":72},"01M7DXXSAP1G8FDRJAMXQGBBMK","enforcement-immutability","Use when enforcement files lose their immutable flag.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fenforcement-immutability\u002FSKILL.md",[],[],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":72},"01M78SSDQVRYX64Y16X32TC0NS","steadfaste-fleet-repo-deploy","Use when committing to the steadfaste-fleet repo.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fsteadfaste-fleet-repo-deploy\u002FSKILL.md",[],[],{"skillNo":95,"name":96,"nameZh":6,"description":97,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":72},"01M78SS928F3R2RJAYVW4E30CE","steadfaste-fleet-maintenance","Maintain an installed Steadfaste Fleet instance — update both the upstream Hermes Agent and the fleet repo layer, merge diverged histories, sync skills safely, and troubleshoot common issues. Covers the dual-update workflow (hermes update + fleet-update.sh), encrypted brain data backup, mycortex import, and recovery techniques.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fsteadfaste-fleet-maintenance\u002FSKILL.md",[],[],{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":105,"categories":106,"keywords":107,"publishedAt":72},"01M78SP1CHW0T0BWE5ZT6JBPX8","fleet-preflight","DEPRECATED alias — merged into survey-before-action (2026-08-20). Load survey-before-action instead; its \"Repo-Specific Pre-Flight\" section covers git search, Hermes boundary, and deployment verification.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Ffleet-preflight\u002FSKILL.md",[],[]]