Claude Code से GitHub API को सुरक्षित तरीके से ऑटोमेट करें
Claude Code से सुरक्षित GitHub API automation बनाएं: permissions, pagination, rate limits, webhooks और Node examples.
GitHub API से आप code के जरिए issues, pull requests, releases, repository metadata, workflow status और webhooks पढ़ या अपडेट कर सकते हैं। Claude Code के साथ यह रोज के repetitive repository कामों को automate करने में उपयोगी है: नई issues की triage, stale PR report, release note draft, और daily repository health report।
लेकिन GitHub API automation गलत तरीके से बने तो नुकसान भी जल्दी कर सकता है। आम गलतियां हैं token को logs में छाप देना, classic token को बहुत बड़ा repo scope दे देना, सिर्फ पहली page पढ़कर सारे data मान लेना, rate limit पर infinite retry करना, Webhook signature verify न करना, या Claude Code से bulk destructive edits करवा देना। इसलिए लक्ष्य केवल “चलने वाला script” नहीं, बल्कि safe और reviewable automation होना चाहिए।
काम करते समय official docs देखें: GitHub REST API docs, REST API rate limits, Webhook delivery validation, और complex reports के लिए GitHub GraphQL API। Team workflow के लिए Git workflow guide और GitHub Actions advanced guide भी उपयोगी हैं।
Safe flow पहले बनाएं
पहला version read-only होना चाहिए। Script सिर्फ issues या PRs list करे, data दिखाए, और permissions सही हैं या नहीं यह साबित करे। फिर dry-run जोड़ें, यानी script बताए कि कौन से labels, comments या assignments करेगा, पर असल में कुछ बदले नहीं। Write operation तभी हो जब APPLY=true जैसा explicit flag हो और एक maximum item limit हो।
flowchart LR
A["Claude Code को goal और guardrails दें"] --> B["Minimum permissions से read करें"]
B --> C["Pagination और rate limits handle करें"]
C --> D["Dry-run output देखें"]
D --> E["Explicit approval के बाद write करें"]
E --> F["Schedule या Webhook से चलाएं"]
REST API शुरुआत के लिए बेहतर है। किसी PR को list करना, issue पर label लगाना, release बनाना या workflow run पढ़ना REST endpoint से सीधा समझ आता है। GraphQL API तब बेहतर है जब एक report में repository, PR, author, reviews, labels और milestones जैसे कई related fields चाहिए। Beginner के लिए पहले REST से safe base बनाना और बाद में GraphQL जोड़ना practical तरीका है।
| निर्णय | REST API | GraphQL API |
|---|---|---|
| सही उपयोग | Single resource action | Multi-resource report |
| सीखना | आसान, URL और HTTP method | कठिन, query design चाहिए |
| Claude Code prompt | Endpoint by endpoint | Fields और schema पहले तय करें |
| जोखिम | Pagination भूलना | Query बहुत बड़ी हो जाना |
Token और permissions कम रखें
GitHub token password जैसा है। उसे code, README, screenshot, test snapshot या log में न रखें। नीचे के examples GITHUB_TOKEN environment variable से token पढ़ते हैं और token value print नहीं करते।
जहां संभव हो fine-grained personal access token use करें। Token को specific repository और specific permission तक सीमित रखें। Issue triage bot को शायद Issues: Read and write चाहिए; stale PR reporter को अक्सर सिर्फ Pull requests: Read-only चाहिए; release note draft के लिए Contents: Read और Metadata: Read से शुरुआत हो सकती है। Classic token का repo scope आसान है, पर daily automation के लिए बहुत broad है।
GitHub Actions में भी permissions साफ लिखें। Daily report को write access नहीं चाहिए। Label लगाने वाले job को केवल वही write permission दें जो जरूरी है। Claude Code से YAML लिखवाने से पहले उससे function, endpoint और required permission की छोटी table बनवाएं।
GitHub REST API use करने वाला Node.js script बनाएं।
Requirements:
- Token process.env.GITHUB_TOKEN से पढ़ें।
- Token या full Authorization header print न करें।
- owner/repo environment variables से पढ़ें।
- First version read-only हो।
- fetch use करें और status code, pagination, rate-limit headers handle करें।
- README section में required GitHub permissions लिखें।
Run करने योग्य read-only script
यह example Node.js 18 या उससे नए version पर open issues list करता है। यह repository में कोई change नहीं करता।
export GITHUB_TOKEN="github_pat_xxx"
export GITHUB_OWNER="octocat"
export GITHUB_REPO="Hello-World"
node scripts/list-open-issues.mjs
// scripts/list-open-issues.mjs
const { GITHUB_TOKEN, GITHUB_OWNER, GITHUB_REPO } = process.env;
if (!GITHUB_TOKEN || !GITHUB_OWNER || !GITHUB_REPO) {
throw new Error("Set GITHUB_TOKEN, GITHUB_OWNER, and GITHUB_REPO.");
}
const apiVersion = "2026-03-10";
async function github(path, options = {}) {
const response = await fetch(`https://api.github.com${path}`, {
...options,
headers: {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${GITHUB_TOKEN}`,
"X-GitHub-Api-Version": apiVersion,
"User-Agent": "claudecodelab-safe-github-api-example",
...(options.headers ?? {}),
},
});
if (!response.ok) {
const body = await response.text();
throw new Error(`GitHub API ${response.status}: ${body.slice(0, 500)}`);
}
return response.json();
}
const issues = await github(
`/repos/${encodeURIComponent(GITHUB_OWNER)}/${encodeURIComponent(GITHUB_REPO)}/issues?state=open&per_page=10`,
);
const rows = issues
.filter((issue) => !issue.pull_request)
.map((issue) => ({
number: issue.number,
title: issue.title,
labels: issue.labels.map((label) => label.name).join(", "),
updated: issue.updated_at,
}));
console.table(rows);
इसके बाद सीधा issues close न करें। पहले script से suggestions निकलवाएं: label candidate, comment draft, या assignee। Real write के लिए explicit flag और count limit रखें।
Pagination और rate limit
GitHub list endpoints अक्सर paginated होते हैं। per_page=100 का मतलब सारी items नहीं, सिर्फ एक page है। Release note generator पहली page ही पढ़े तो पुराने merged PR छूट जाएंगे। Stale PR reporter भी गलत report दे सकता है।
Rate limit पर infinite retry नहीं करना चाहिए। 403 या 429 मिलने पर retry-after और x-ratelimit-reset headers पढ़ें, reasonable समय तक wait करें, और fixed retries के बाद fail करें।
// scripts/github-pages.mjs
const token = process.env.GITHUB_TOKEN;
if (!token) throw new Error("Set GITHUB_TOKEN.");
const apiBase = "https://api.github.com";
const apiVersion = "2026-03-10";
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function defaultHeaders() {
return {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${token}`,
"X-GitHub-Api-Version": apiVersion,
"User-Agent": "claudecodelab-pagination-example",
};
}
function parseNextLink(linkHeader) {
if (!linkHeader) return null;
for (const part of linkHeader.split(",")) {
const match = part.match(/<([^>]+)>;\s*rel="([^"]+)"/);
if (match && match[2] === "next") return match[1];
}
return null;
}
async function githubRequest(url, options = {}, attempt = 0) {
const response = await fetch(url, {
...options,
headers: {
...defaultHeaders(),
...(options.headers ?? {}),
},
});
if ((response.status === 403 || response.status === 429) && attempt < 2) {
const retryAfterSeconds = Number(response.headers.get("retry-after") ?? "0");
const resetSeconds = Number(response.headers.get("x-ratelimit-reset") ?? "0");
const resetDelayMs = resetSeconds > 0 ? resetSeconds * 1000 - Date.now() : 0;
const waitMs = Math.max(retryAfterSeconds * 1000, resetDelayMs, 0);
if (waitMs > 0 && waitMs <= 10 * 60 * 1000) {
await sleep(waitMs + 1000);
return githubRequest(url, options, attempt + 1);
}
}
if (!response.ok) {
const body = await response.text();
throw new Error(`GitHub API ${response.status}: ${body.slice(0, 500)}`);
}
return {
data: await response.json(),
nextUrl: parseNextLink(response.headers.get("link")),
};
}
export async function paginate(path) {
const items = [];
let url = path.startsWith("http") ? path : `${apiBase}${path}`;
while (url) {
const page = await githubRequest(url);
if (!Array.isArray(page.data)) {
throw new Error("paginate() expected an array response.");
}
items.push(...page.data);
url = page.nextUrl;
}
return items;
}
if (import.meta.url === `file://${process.argv[1]}`) {
const owner = process.env.GITHUB_OWNER;
const repo = process.env.GITHUB_REPO;
if (!owner || !repo) throw new Error("Set GITHUB_OWNER and GITHUB_REPO.");
const pulls = await paginate(
`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls?state=open&per_page=100`,
);
console.table(pulls.map((pr) => ({ number: pr.number, title: pr.title, updated: pr.updated_at })));
}
Helper बनने के बाद Claude Code से api.github.com direct calls search करवाएं और उन्हें इसी helper से route करें।
Webhook signature और idempotency
Webhook तब काम आता है जब polling के बजाय event पर react करना हो। PR open हुआ तो label suggestion बने, issue open हुई तो triage queue में जाए, release publish हुई तो notification भेजा जाए। Endpoint public होता है, इसलिए x-hub-signature-256 verify करना जरूरी है।
Idempotency का मतलब है कि वही delivery दो बार आए तो side effect दो बार न हो। x-github-delivery save करें और duplicate ignore करें। नीचे Set demo है; production में database या Redis use करें।
npm install express
export GITHUB_WEBHOOK_SECRET="your-webhook-secret"
node webhook-server.mjs
// webhook-server.mjs
import crypto from "node:crypto";
import express from "express";
const secret = process.env.GITHUB_WEBHOOK_SECRET;
if (!secret) throw new Error("Set GITHUB_WEBHOOK_SECRET.");
const app = express();
const seenDeliveries = new Set();
function verifySignature(payloadBuffer, signatureHeader) {
if (!signatureHeader) return false;
const expected = `sha256=${crypto
.createHmac("sha256", secret)
.update(payloadBuffer)
.digest("hex")}`;
const actual = Buffer.from(signatureHeader, "utf8");
const expectedBuffer = Buffer.from(expected, "utf8");
return actual.length === expectedBuffer.length && crypto.timingSafeEqual(actual, expectedBuffer);
}
app.post("/github/webhook", express.raw({ type: "application/json" }), (req, res) => {
const signature = req.get("x-hub-signature-256");
if (!verifySignature(req.body, signature)) {
return res.status(401).send("invalid signature");
}
const deliveryId = req.get("x-github-delivery");
if (!deliveryId) return res.status(400).send("missing delivery id");
if (seenDeliveries.has(deliveryId)) {
return res.status(202).send("duplicate ignored");
}
seenDeliveries.add(deliveryId);
const event = req.get("x-github-event");
const payload = JSON.parse(req.body.toString("utf8"));
console.log(
JSON.stringify({
event,
deliveryId,
repository: payload.repository?.full_name,
action: payload.action,
}),
);
return res.status(202).send("accepted");
});
app.listen(process.env.PORT ?? 3000, () => {
console.log("Listening for GitHub webhooks.");
});
Claude Code से handler बढ़वाते समय लिखें कि signature verification से पहले JSON process न हो, HTTP request के अंदर destructive काम न हो, और duplicate delivery ignore हो।
Practical use cases
Issue triage bot नई issues में reproduction steps, environment info और label candidates देखता है। पहले सिर्फ report बनाएं, automatic comment बाद में।
Stale PR reporter 30 दिन से update न हुए PRs, pending reviews और failed CI वाले PRs दिखाता है। Safe version PR close नहीं करता।
Release note generator दो tags के बीच merged PRs लेकर Added, Fixed, Changed groups बनाता है। Author और review data चाहिए तो GraphQL मदद करता है।
Daily repository health report open issues, old PRs, failing workflows, Dependabot alerts, recent releases और review backlog को एक जगह दिखाता है। यह Claude Code workflow automation और review workflow checklist से अच्छी तरह जुड़ता है।
बचने लायक failures
Classic token log में छपना सबसे बड़ा risk है। console.log(process.env), full request dump और CI debug headers से बचें। Broad permissions भी risk हैं: read-only report को write access नहीं चाहिए। Pagination न होना silent bug है। Rate-limit loop CI waste करता है। Webhook signature न verify करना external JSON पर भरोसा करना है। Bulk close, bulk relabel या release rewrite बिना dry-run, count limit, audit log और rollback plan के न करें।
Claude Code की भूमिका
Claude Code को API client, pagination helper, tests, README, GitHub Actions schedule और review checklist बनाने दें। Production token, permission approval और destructive changes का final decision इंसान रखे। इन rules को CLAUDE.md में लिखना team के लिए उपयोगी है।
ClaudeCodeLab teams को CLAUDE.md, permission design, GitHub Actions, review gates और Webhook operation सेट करने में मदद करता है। Team rollout के लिए Claude Code training and consultation देखें। Individual practice के लिए free cheatsheet और templates से शुरू करें।
नतीजा
GitHub API और Claude Code repository maintenance को तेज बना सकते हैं, अगर token, permissions, pagination, rate limits, Webhook verification और idempotency को शुरुआत से design किया जाए। Read-only, फिर dry-run, फिर limited write यही safest order है।
Masa के practical verification में इस article के read-only script, pagination helper और Webhook signature server को copy-paste runnable shape में रखा गया। Real repository में पहले daily report दिखाना और बाद में label write जोड़ना, पहले दिन से issue close करने वाले bot से ज्यादा भरोसेमंद निकला।
मुफ़्त PDF: Claude Code cheatsheet
Email डालें और commands, review habits तथा safe workflow वाली एक-page PDF पाएँ.
हम आपका data सुरक्षित रखते हैं और spam नहीं भेजते.
लेखक के बारे में
Masa
Claude Code workflow और team adoption पर काम करने वाला engineer.
संबंधित लेख
Claude Code Obsidian to CLAUDE.md workflow: context बार-बार न समझाएं
Obsidian notes को CLAUDE.md operating notes में बदलकर Claude Code sessions को resume करना आसान बनाएं.
Claude Code Revenue CTA Routing: article से PDF, Gumroad और consultation तक
Reader intent के आधार पर free PDF, Gumroad products और consultation तक CTA route करने वाला workflow.
Claude Code टीम हैंडऑफ नियम: review proof, permissions, rollback और revenue path
Claude Code टीम काम के लिए evidence, permission rules, rollback, free PDF, Gumroad और consultation path वाला handoff.