Claude API in GitHub Actions: CI/CD Pipeline Guide
If you're searching for how to wire the Claude API into a GitHub Actions workflow, you want one of two things: a working YAML example that calls Claude on every pull request, or a pattern for running Claude-powered checks (summaries, reviews, release notes) as part of your existing CI/CD pipeline without breaking builds or leaking API keys.
Both are straightforward. You store an API key as a GitHub secret, call the Claude messages endpoint from a small script step, and use the response to post a comment, fail/pass a check, or write a file that a later job consumes. The rest of this article walks through the actual workflow files, the gotchas specific to CI (timeouts, retries, non-interactive output), and where a gateway like SubToAPI simplifies key management across multiple repos and teams.
What Claude Actually Does Well in a Pipeline
Claude isn't a replacement for your test suite or linter — it's useful for the parts of CI/CD that are language tasks dressed up as engineering tasks:
- PR summaries — generate a plain-English description of a diff when the author didn't write one.
- Release notes — turn a list of merged commits into a changelog section.
- Code review comments — flag risky patterns (missing error handling, SQL built from string concatenation) as advisory, non-blocking comments.
- Test failure triage — summarize a long test log into "3 tests failed, likely cause: timezone handling in
date_utils.py." - Security/dependency report summarization — condense a verbose
npm auditorpip-auditoutput into a short actionable note.
None of these should gate a merge on their own — treat Claude's output as an annotation, not a gatekeeper, unless you've tested it extensively on your own codebase.
Basic Workflow Structure
The core pattern is always the same: checkout → gather context (diff, logs, commits) → call Claude → post result.
name: claude-pr-summary
on:
pull_request:
types: [opened, synchronize]
jobs:
summarize:
runs-on: ubuntu-latest
permissions:
pull-requests: write
contents: read
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Get diff
run: git diff origin/${{ github.base_ref }}...HEAD > diff.txt
- name: Call Claude
env:
SUBTOAPI_KEY: ${{ secrets.SUBTOAPI_KEY }}
run: node .github/scripts/summarize.js
- name: Comment on PR
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const body = fs.readFileSync('summary.md', 'utf8');
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body
});
And .github/scripts/summarize.js:
const fs = require('fs');
async function run() {
const diff = fs.readFileSync('diff.txt', 'utf8').slice(0, 20000);
const res = await fetch('https://api.subtoapi.app/v1/messages', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.SUBTOAPI_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'claude-sonnet-4',
max_tokens: 400,
messages: [{
role: 'user',
content: `Summarize this diff in 3-5 bullet points for a PR description. Be concise, note risk areas.\n\n${diff}`
}]
})
});
const data = await res.json();
const text = data.content?.[0]?.text ?? 'No summary generated.';
fs.writeFileSync('summary.md', `### Claude PR Summary\n\n${text}`);
}
run().catch(err => {
console.error(err);
fs.writeFileSync('summary.md', '_Claude summary unavailable this run._');
process.exit(0); // don't fail the build on a summarizer error
});
The key detail: the script exits 0 even on failure. A summarizer job should degrade gracefully, not block merges when an upstream API hiccups.
Managing the API Key Across Repos
If you run this pattern in one repo, a raw Anthropic key in a GitHub secret is fine. It gets harder once you have ten repos, several teams, and someone asking "how much did we spend on CI last month on the marketing-site repo versus the backend?"
This is the practical reason to put a gateway in front of the Claude API for CI/CD use:
- Issue a separate
sub_live_...key per repo or per team from one dashboard, instead of sharing one Anthropic key across every workflow file. - Revoke a single pipeline's access without rotating the key everywhere else.
- See usage metadata per key, so you know which workflow is actually driving cost.
- Keep the same HTTPS API shape (
/v1/messages) your scripts already expect, so no custom integration per gateway.
Setup is a signup, a key per project, and a drop-in Authorization: Bearer $SUBTOAPI_KEY — see the /docs/quickstart for the exact request format and /docs/messages for parameters like max_tokens and stop sequences.
Rate Limits, Timeouts, and Cost Control
A few things that bite people specifically in a CI context:
- Set explicit timeouts. CI runners don't wait forever gracefully — a hung
fetchcan eat your job's timeout budget. Wrap the call withAbortControllerand a 30-second limit. - Cap
max_tokens. CI summaries don't need 4000 tokens. Keep them short; it's faster and cheaper. - Don't run on every push to every branch. Trigger on PR open/sync, not on every commit to a feature branch — otherwise you're paying for summaries nobody reads.
- Truncate large inputs. A 50,000-line diff will blow your context budget and your bill. Truncate or diff only changed files, not full file contents.
- Retry once on 5xx, don't retry on 4xx. A malformed request won't fix itself on retry; a transient 503 might.
Streaming isn't useful here — CI jobs want a single final result to write to a file or post as a comment, so plain request/response (/docs/messages) is simpler than /docs/streaming for this use case. Tool calling (/docs/tools) becomes relevant if you want Claude to decide which files to inspect rather than feeding it a fixed diff, but for most pipelines a static context window is enough.
Beyond PR Summaries: Release Notes Job
A second common job runs on tag push, collects commit messages since the last tag, and asks Claude to draft release notes grouped by type (features, fixes, breaking changes). The script is nearly identical to the summarizer above — swap the diff for git log <last-tag>..HEAD --oneline output and adjust the prompt to ask for grouped markdown sections. Write the result to CHANGELOG.md via a PR instead of a comment, using peter-evans/create-pull-request so a human still approves the final wording before it ships.
questions
Do I need to use Anthropic's API directly, or can I go through a gateway in CI? Either works. Calling Anthropic directly is fine for a single repo. A gateway like SubToAPI (/pricing) helps once you have multiple repos or teams and want separate keys, revocation, and usage visibility per pipeline from one dashboard.
Will a failed Claude API call break my build? Only if you let it. Write your script to catch errors, write a fallback message, and exit with code 0 for non-critical jobs like summaries. Reserve non-zero exit codes for checks you actually want to block merges.
Should I use streaming responses in a GitHub Actions job? No — CI jobs need a complete result to write to a file or comment, so a standard request to /v1/messages (see /docs/messages) is simpler and more reliable than parsing a stream inside a short-lived runner process.