Let Claude call an external API
Build the full tool_use → HTTP → tool_result loop with GitHub metadata.
Complete the first API request guide. Download client.mjs and external-tool.mjs to the same folder. This example reads public GitHub metadata without a GitHub token; it still makes paid Claude requests, and GitHub rate limits apply.
1. Define a narrow tool
Declare a name, description, and input_schema. The sample tool accepts owner and repo, not arbitrary URLs. Your code validates both values and always calls api.github.com. A schema guides generated arguments; your executor must still validate them. A tool definition does not execute an API by itself.
{
"name": "get_github_repository",
"description": "Read public repository metadata",
"input_schema": {
"type": "object",
"properties": {"owner": {"type": "string"}, "repo": {"type": "string"}},
"required": ["owner", "repo"],
"additionalProperties": false
}
}2. Execute the tool request in your application
Send the tool definition with the user message. When stop_reason is tool_use, inspect every tool_use block, check its name and input, and perform the HTTP request in your code. The sample returns only selected repository facts, the source URL, and a retrieval timestamp. open_issues_count includes pull requests; do not label it as issues alone.
3. Return matching tool results
Append the complete assistant content to history. Immediately follow it with a user message containing all tool_result blocks, each with the matching tool_use_id. Mark failures with is_error: true. Send the updated history and tool definitions again. Continue until end_turn, with a fixed round limit; do not assume one tool call always completes the task.
messages.push({role: "assistant", content: response.content});
messages.push({role: "user", content: [{
type: "tool_result", tool_use_id: call.id, content: result
}]});4. Run and verify the complete example
Run the downloaded script with your .env. Compare the returned URL and numbers to the original repository page; counts change over time. The sample caps rounds at five and tool calls at four per response, applies HTTP timeouts, and reports tool errors. Treat descriptions from external services as untrusted data. For write tools, add application-side authorization and confirmation before execution.
node --env-file=.env external-tool.mjsDownload the example files
Teaching examples; model behavior can vary. Follow the prerequisites and verify outputs. These pages do not send API requests.
Practice & self-check
Trace one successful tool call and one failed repository lookup. Confirm the failure returns is_error rather than invented repository facts.
When you’re done, take a moment to check:
Read the official sources
CLI instructions checked against official documentation; API examples tested with simulated responses. Product-account walkthroughs were not performed.