Connecting Claude to External APIs
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
Most useful tools are thin wrappers around someone else's API: a carrier, a payment provider, a CRM, a weather service. Wrapping an API for a model is different from wrapping it for your own code. The caller is a model that can't read your logs, might pass odd input, and will repeat whatever you return. This lesson shows how to build that wrapper well, with a tracking tool as the example.
What you'll learn
- How to keep credentials and configuration out of the model's reach.
- How to turn HTTP failures into messages Claude can act on.
- How to trim an API response down to what the model needs.
- How to test an API tool without calling the real service.
Before you start
The wrapper has five jobs
- Authenticate with a key from your configuration. The model never sees it and never supplies it.
- Re-validate the input. A value from a model becomes part of a URL. Check it before it does.
- Set timeouts, so a slow service can't hold up a conversation.
- Map errors to useful messages (not found, rate limited, down) instead of passing raw status codes through.
- Return only what Claude needs. Raw API payloads are full of fields you'd never want repeated to a customer.
A tracking tool
Here's the definition and function for a carrier tracking tool. Configuration comes from the environment. The model supplies one thing, the tracking number, and the function is careful about it:
import os
import httpx
from executor import ToolError
# Configuration comes from the environment, never from the model and never from source code.
BASE_URL = lambda: os.environ.get("CARRIER_API_URL", "https://api.carrier.example") # noqa: E731
API_KEY = lambda: os.environ.get("CARRIER_API_KEY", "") # noqa: E731
TRACK_PARCEL = {
"name": "shop_track_parcel",
"description": (
"Get the live delivery status of a parcel from the carrier, using its tracking number (for example JD0146). "
"Returns the current status, the last known location and the estimated delivery date. Use it after the order "
"lookup shows a tracking number and the customer asks where the parcel is. It cannot change a delivery."
),
"strict": True,
"input_schema": {
"type": "object",
"properties": {"tracking_number": {"type": "string", "description": "The carrier tracking number, such as JD0146."}},
"required": ["tracking_number"],
"additionalProperties": False,
},
}
def track_parcel(tracking_number: str) -> dict:
# Validate again here: the value will become part of a URL.
if not tracking_number.isalnum() or len(tracking_number) > 30:
raise ToolError("That does not look like a tracking number. Ask the customer to check it (letters and digits only).")
try:
response = httpx.get(
f"{BASE_URL()}/v1/parcels/{tracking_number}",
headers={"Authorization": f"Bearer {API_KEY()}"},
timeout=httpx.Timeout(3.0),
)
except httpx.TimeoutException:
raise ToolError("The carrier service did not answer in time. Tell the customer tracking is temporarily unavailable.")
except httpx.TransportError:
raise ToolError("The carrier service could not be reached. Tell the customer tracking is temporarily unavailable.")
if response.status_code == 404:
raise ToolError(f"The carrier has no parcel with tracking number {tracking_number}. Ask the customer to check the number.")
if response.status_code == 429:
wait = response.headers.get("Retry-After", "a minute")
raise ToolError(f"The carrier service is busy. Retry after {wait} seconds or tell the customer to try later.")
if response.status_code >= 500:
raise ToolError("The carrier service has a problem right now. Tell the customer tracking is temporarily unavailable.")
response.raise_for_status() # anything else unexpected becomes an internal error in the executor
data = response.json()
# Return only what Claude needs. The raw payload has addresses, driver names and internal ids it should never see.
return {
"status": data["status"],
"last_location": data.get("last_scan", {}).get("city"),
"last_update": data.get("last_scan", {}).get("time"),
"estimated_delivery": data.get("eta"),
}
Take the pieces in turn.
Input check. isalnum() and a length cap run before any request. A tracking number like ../etc/passwd or JD0146?admin=1 never becomes part of a URL. Even with a strict schema, this belongs in the function, because the schema says "a string" and the function knows what kind of string is acceptable.
Timeouts and failures. The 3-second timeout is inside the HTTP call, which is where a real timeout belongs (lesson 4.4 explained why). Then each outcome gets a message with a next step. A 404 says the carrier has no such parcel and tells the model to ask the customer to check the number. A 429 passes along the Retry-After value. A 5xx or a network failure says tracking is temporarily unavailable. None of these mention URLs, keys or status codes.
Shaping. The carrier's response in our test included the recipient's name and address and an internal driver id. The function returns four fields: status, last location, last update and estimated delivery. The rest never reaches the model, so it can't leak, be repeated by an overeager answer, or take up context.
Testing without the real API
You shouldn't call a live carrier from your test suite. Two options work well. In Python, run a tiny fake server on a local port and point CARRIER_API_URL at it. That also lets you test timeouts for real. In Laravel, use Http::fake(). We did the first for the Python version, with a fake that returned a normal parcel, a 404, a 429 with Retry-After: 30, a 500 and a deliberately slow response, and these were the results:
- The normal parcel came back as exactly four fields, and the recipient's name and address never appeared in the result.
- A 404, 429 and 500 each produced the matching instructive message; the 429 message included "Retry after 30".
- Malformed tracking numbers (path traversal, spaces, a query string, a 40-character string) were rejected without any request being made.
- The slow response timed out inside the HTTP call in under 4.5 seconds, and an unreachable server gave the "could not be reached" message.
- Run through the registry, an extra property in the input was rejected as invalid.
The Laravel version
The same tool using Laravel's HTTP client. Configuration goes in config/services.php (a carrier entry with url and key read from .env), never in the tool or the prompt:
<?php
namespace App\Support\Tools;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;
final class CarrierTool
{
public static function definition(): array
{
return [
'name' => 'shop_track_parcel',
'description' => 'Get the live delivery status of a parcel from the carrier, using its tracking number (for example JD0146). '
.'Returns the current status, the last known location and the estimated delivery date. Use it after the order lookup '
.'shows a tracking number and the customer asks where the parcel is. It cannot change a delivery.',
'strict' => true,
'input_schema' => [
'type' => 'object',
'properties' => ['tracking_number' => ['type' => 'string', 'description' => 'The carrier tracking number, such as JD0146.']],
'required' => ['tracking_number'],
'additionalProperties' => false,
],
];
}
public function __invoke(string $tracking_number): array
{
// The value becomes part of a URL, so check it again here.
if (! ctype_alnum($tracking_number) || strlen($tracking_number) > 30) {
throw new ToolError('That does not look like a tracking number. Ask the customer to check it (letters and digits only).');
}
try {
$response = Http::withToken((string) config('services.carrier.key'))
->timeout(3)
->get(rtrim((string) config('services.carrier.url'), '/')."/v1/parcels/{$tracking_number}");
} catch (ConnectionException) {
throw new ToolError('The carrier service could not be reached or did not answer in time. Tell the customer tracking is temporarily unavailable.');
}
if ($response->status() === 404) {
throw new ToolError("The carrier has no parcel with tracking number {$tracking_number}. Ask the customer to check the number.");
}
if ($response->status() === 429) {
$wait = $response->header('Retry-After') ?: 'a minute';
throw new ToolError("The carrier service is busy. Retry after {$wait} seconds or tell the customer to try later.");
}
if ($response->serverError()) {
throw new ToolError('The carrier service has a problem right now. Tell the customer tracking is temporarily unavailable.');
}
$response->throw(); // anything else unexpected becomes an internal error in the registry
// Only what Claude needs. The raw payload has an address and a driver id it should never see.
return [
'status' => $response->json('status'),
'last_location' => $response->json('last_scan.city'),
'last_update' => $response->json('last_scan.time'),
'estimated_delivery' => $response->json('eta'),
];
}
}
Laravel's Http::fake() makes this easy to test. We tested that the successful response was reduced to four fields and the authorisation header was sent; that 404, 429 and 503 each gave the right message; that a malformed number sent nothing at all (Http::assertNothingSent()); and that a timeout, which Laravel reports as a ConnectionException, became a tool error.
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
A shop connects its assistant to a shipping provider's tracking API. In week one a customer pastes a tracking number with a space in it, the provider returns a 400, and the raw error text goes to Claude, which tells the customer "the API returned 400 Bad Request". After adding input checks and error mapping, the same input produces "That doesn't look like a tracking number, please check it", and the customer fixes it in one message. The upstream API didn't change, only the wrapper did.
Mistakes to avoid
- Passing the model's value straight into a URL, query or path.
- Returning the entire API response.
- No timeout, or a timeout of 30 seconds in a chat.
- Putting the API key in the tool description, system prompt or tool input.
- Exposing HTTP status codes and URLs in error messages.
- Letting the model retry a rate-limited API in a tight loop.
Security notes
- Credentials live in environment variables or a secrets manager. They're used by your code, never mentioned to the model.
- A tool that takes a URL from the model is a server-side request forgery hole. If you must fetch URLs, use an allow-list of hosts, block private network ranges and never let redirects leave the list.
- External responses are untrusted. A parcel's "notes" field can contain text aimed at the model. Return only fields you chose, and keep results inside
tool_result, as Anthropic advises, rather than in the system prompt.
- Use the least-privileged key the API offers. A read-only key for a read-only tool.
Cost and speed
An external call is often the slowest part of a turn, and it's followed by a second model request. Keep timeouts short, cache stable data where it's safe (a parcel status that changes hourly can be cached for a few minutes), and respect the provider's rate limits. If the API is slow by nature, consider telling the user "checking the carrier..." by streaming the first part of the reply.
Key takeaways
- Wrap external APIs so the model never handles credentials and can only supply narrow, validated input.
- Put timeouts in the HTTP call and map every failure to a message with a next step.
- Return only the fields Claude needs; leave addresses, ids and internals behind.
- Test with a fake server or
Http::fake(), including failures and slow responses.
Lesson recap: the wrapper is the boundary between the model and a real service.
Quick quiz
- Why validate a tracking number inside the function when the schema already says it's a string?
- Where should the API key live?
- What should the tool do on a 429 response?
- Why return four fields instead of the whole carrier response?
- How can you test timeout behaviour without waiting on a real service?
Answers and explanations
- A schema says "a string", not "a safe string". The value is about to become part of a URL, so the function must check it.
- In environment configuration or a secrets manager, read by your code. Never in the prompt, the tool definition or the tool input.
- Return a message that includes the retry delay and tells the model to wait or tell the customer to try later; don't loop.
- The rest may include private data, wastes context and tokens, and gives the model more to repeat.
- Point the tool at a local fake server that sleeps, or fake the HTTP layer to throw a timeout.
Official references and further reading
Related tutorials