← Blog

Build a Claude API Code Review Assistant

2026-11-13 · 5 min read · SubToAPI Team

What you're actually building

A Claude API code review assistant is a script or CI step that sends a diff (or full file) to Claude, gets back structured feedback — bugs, style issues, security concerns, suggested fixes — and posts it as a comment on a pull request. This guide walks through the full build: pulling the diff, structuring the prompt, parsing the response into something a PR comment can use, and wiring it into GitHub Actions or GitLab CI.

If you want this working today rather than over a weekend, the core logic is the same whether you call Anthropic directly or go through SubToAPI — the difference is just the auth header and endpoint. We'll use the standard Messages API shape throughout, with notes on where SubToAPI simplifies things.

Step 1: Get the diff

Most review assistants work on diffs, not whole repos — it's cheaper, faster, and keeps feedback focused on what actually changed.

git diff origin/main...HEAD > diff.patch

In CI, this is usually available as an environment variable or you generate it explicitly:

# GitHub Actions example
git fetch origin ${{ github.base_ref }}
git diff origin/${{ github.base_ref }}...HEAD > diff.patch

Keep an eye on size. Large diffs can blow past context limits or just produce noisy, unfocused reviews. A practical cap is 2,000–4,000 lines per request; split larger diffs into chunks per file or per directory.

Step 2: Design the prompt

The quality of your code review assistant lives almost entirely in the prompt. Vague prompts get vague reviews. Be explicit about what you want checked and in what format.

const systemPrompt = `You are a senior code reviewer. Review the given diff for:
1. Bugs and logic errors
2. Security vulnerabilities (injection, auth, secrets in code)
3. Performance issues
4. Style violations against common conventions for the language
5. Missing error handling or edge cases

For each issue found, respond with a JSON array of objects:
{ "file": string, "line": number, "severity": "high"|"medium"|"low", "comment": string }

If there are no issues, return an empty array. Do not comment on formatting that a linter would catch.`;

Pinning the output to JSON is the single biggest lever for making this useful — it lets you post inline PR comments instead of dumping a wall of text.

Step 3: Call the API

const response = 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-opus-4",
    max_tokens: 2048,
    system: systemPrompt,
    messages: [
      { role: "user", content: `Review this diff:\n\n${diffText}` }
    ]
  })
});

const data = await response.json();
const reviewText = data.content[0].text;

Swap the base URL and key for Anthropic's direct endpoint if you're not using SubToAPI — the request/response shape is identical, since SubToAPI is a thin layer on top of your existing Claude access. See /docs/quickstart if you're setting this up for the first time, and /docs/messages for the full request reference.

Parsing the response reliably

Claude generally follows JSON instructions well, but production code should never assume a perfect response. Wrap parsing defensively:

function parseReview(text) {
  const match = text.match(/\[[\s\S]*\]/);
  if (!match) return [];
  try {
    return JSON.parse(match[0]);
  } catch {
    return [];
  }
}

If you need stricter guarantees, use Claude's tool use feature to force a structured output instead of relying on the model to emit clean JSON in prose — see /docs/tools.

Step 4: Post comments back to the PR

With GitHub, use the Checks or Reviews API to attach comments to specific lines:

await octokit.pulls.createReviewComment({
  owner, repo, pull_number: prNumber,
  commit_id: headSha,
  path: issue.file,
  line: issue.line,
  body: `**${issue.severity.toUpperCase()}**: ${issue.comment}`
});

For a simpler first version, just post a single summary comment with all issues grouped by file — it's less code and easier to debug before you move to inline comments.

Step 5: Wire it into CI

A minimal GitHub Actions job:

name: claude-review
on: pull_request

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - run: git diff origin/${{ github.base_ref }}...HEAD > diff.patch
      - run: node scripts/claude-review.js
        env:
          SUBTOAPI_KEY: ${{ secrets.SUBTOAPI_KEY }}
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

Run this on every pull_request event, or gate it to a label like needs-review if you want contributors to trigger it manually rather than on every push.

Handling scale and cost

A few practical tips once this is running on a real team's PR volume:

Where this fits with SubToAPI

If you're running this inside a company with more than one or two engineers touching it, the practical friction isn't the Claude API itself — it's key management, rate limits, and knowing who's using what. SubToAPI gives you application-scoped keys (sub_live_...), per-key usage metadata, and team seats, so you can issue a separate key for your review bot, see exactly how much it's costing, and rotate it without touching anyone else's access. Plans start at €9/month for solo use, €19/seat for teams, with a free trial at /signup.

FAQ

Does Claude need the full repo to review a PR well?

No. Diffs with a few lines of surrounding context are usually enough. Full-file review helps for logic that depends on code outside the diff, but it costs more tokens and isn't necessary for most PRs.

How do I stop the assistant from flagging things a linter already catches?

Say so explicitly in the system prompt, as shown above. Claude follows explicit scoping instructions well — "don't comment on formatting a linter would catch" meaningfully reduces noise.

Can I use this with GitLab or Bitbucket instead of GitHub?

Yes — the review logic (diff in, structured feedback out) is platform-agnostic. Only the comment-posting step changes, since each platform has its own API for attaching review comments to a merge request.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →