APIs·5 min read

How to use the Anthropic Claude API

The Anthropic API gives access to the Claude model family. This guide covers authentication, the Messages API, vision inputs, tool use, and the key differences from the OpenAI API format.

Get started with the Anthropic API

Create an account at console.anthropic.com. Generate an API key and store it as `ANTHROPIC_API_KEY` in your environment. Install the SDK: `pip install anthropic` (Python) or `npm install @anthropic-ai/sdk` (Node.js).

The Anthropic API uses a slightly different format from OpenAI. The key difference: system prompt is a top-level parameter, not a message with role 'system'. Max tokens is required, not optional.

Make your first call

Python: `import anthropic; client = anthropic.Anthropic(); message = client.messages.create(model='claude-sonnet-4-5', max_tokens=1024, messages=[{'role': 'user', 'content': 'Hello'}]); print(message.content[0].text)`.

The response `content` is a list — it can contain text blocks and tool_use blocks. Always access the first text block with `message.content[0].text` for simple text responses.

Use vision (image inputs)

Claude Sonnet and Opus support images in messages. Pass images as base64-encoded strings or URLs: `messages=[{'role': 'user', 'content': [{'type': 'image', 'source': {'type': 'url', 'url': 'https://...'}}, {'type': 'text', 'text': 'What is in this image?'}]}]`.

For base64, read the file and encode it: `import base64; with open('image.jpg', 'rb') as f: data = base64.standard_b64encode(f.read()).decode('utf-8')`. Use media_type `image/jpeg`, `image/png`, `image/gif`, or `image/webp`.

Tool use (function calling)

Anthropic's tool use format is clean and explicit. Define tools as a list of `{name, description, input_schema}` objects. Pass them to `client.messages.create(tools=[...])`. When the model wants to use a tool, it returns a message with `stop_reason: 'tool_use'` and a `tool_use` content block.

Extract the tool name and input: `tool_block = [b for b in message.content if b.type == 'tool_use'][0]; tool_name = tool_block.name; tool_input = tool_block.input`. Execute the tool, then send the result back as a `tool_result` content block in the next user message.