BeClaude
GuideBeginnerAgents2026-05-16

Getting Started with the Claude API: A Practical Guide for Developers

Learn how to build with the Claude API from scratch. Covers setup, Messages API, model selection, key features like extended thinking and tool use, with code examples.

Quick Answer

This guide walks you through setting up the Claude API, making your first API call, understanding the Messages API structure, choosing the right model, and exploring key features like extended thinking, tool use, and structured outputs.

Claude APIMessages APIQuickstartTool UseExtended Thinking

Getting Started with the Claude API: A Practical Guide for Developers

Anthropic’s Claude API gives you direct access to the latest Claude models—Claude Opus 4.7, Sonnet 4.6, and Haiku 4.5—enabling you to build custom AI-powered applications. Whether you’re creating a chatbot, an agentic coding assistant, or an enterprise workflow, this guide covers everything you need to go from zero to a working integration.

What You’ll Learn

  • How to set up your environment and make your first API call
  • The structure of the Messages API for single and multi-turn conversations
  • How to choose the right Claude model for your use case
  • Key capabilities: extended thinking, tool use, structured outputs, and more

Prerequisites

  • An Anthropic Console account with an API key
  • Python 3.8+ or Node.js 18+ installed
  • Basic familiarity with REST APIs and JSON

Step 1: Make Your First API Call

Install the SDK

Python
pip install anthropic
TypeScript/JavaScript
npm install @anthropic-ai/sdk

Set Your API Key

Store your API key as an environment variable:

export ANTHROPIC_API_KEY="sk-ant-..."

Send Your First Message

Python
import anthropic

client = anthropic.Anthropic()

message = client.messages.create( model="claude-sonnet-4-20250514", max_tokens=1024, messages=[ {"role": "user", "content": "Hello, Claude!"} ] )

print(message.content[0].text)

TypeScript
import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic();

async function main() { const message = await client.messages.create({ model: 'claude-sonnet-4-20250514', max_tokens: 1024, messages: [{ role: 'user', content: 'Hello, Claude!' }], });

console.log(message.content[0].text); }

main();

If everything works, you’ll see Claude’s friendly greeting in your terminal.

Step 2: Understand the Messages API

The Messages API is the primary way to interact with Claude programmatically. Here’s the core structure:

Request Components

FieldDescription
modelThe model identifier (e.g., claude-sonnet-4-20250514)
max_tokensMaximum number of tokens in the response
messagesArray of message objects with role and content
system(Optional) System prompt to set context or behavior

Multi-Turn Conversations

To continue a conversation, include the full message history:

messages = [
    {"role": "user", "content": "What is the capital of France?"},
    {"role": "assistant", "content": "The capital of France is Paris."},
    {"role": "user", "content": "What is its population?"}
]

response = client.messages.create( model="claude-sonnet-4-20250514", max_tokens=512, messages=messages )

Handling Stop Reasons

The response includes a stop_reason field that tells you why Claude stopped:

  • "end_turn": Claude naturally finished its response
  • "max_tokens": The response hit the token limit
  • "stop_sequence": A custom stop sequence was encountered
  • "tool_use": Claude wants to call a tool (see Step 4)
response = client.messages.create(...)
print(f"Stop reason: {response.stop_reason}")

Step 3: Choose the Right Model

Claude offers three model families, each optimized for different needs:

ModelBest ForSpeedCost
Claude Opus 4.7Complex reasoning, agentic coding, researchSlowerHighest
Claude Sonnet 4.6General coding, agents, enterprise workflowsFastModerate
Claude Haiku 4.5High-throughput, real-time apps, simple tasksFastestLowest
Recommendation for new developers: Start with claude-sonnet-4-20250514. It offers frontier intelligence at scale and is the most versatile for prototyping.

Step 4: Explore Key Features

Extended Thinking

For complex reasoning tasks, enable extended thinking to let Claude "think" before responding:

response = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=4096,
    thinking={"type": "enabled", "budget_tokens": 2048},
    messages=[{"role": "user", "content": "Solve this complex math problem step by step..."}]
)

Tool Use (Function Calling)

Claude can call external tools. Define tools and let Claude decide when to use them:

tools = [
    {
        "name": "get_weather",
        "description": "Get the current weather for a city",
        "input_schema": {
            "type": "object",
            "properties": {
                "location": {"type": "string", "description": "City name"}
            },
            "required": ["location"]
        }
    }
]

response = client.messages.create( model="claude-sonnet-4-20250514", max_tokens=1024, tools=tools, messages=[{"role": "user", "content": "What's the weather in Tokyo?"}] )

When Claude decides to use a tool, the response will contain a tool_use content block with the tool name and input. You then execute the tool and return the result.

Structured Outputs

Force Claude to output valid JSON by specifying a structured schema:

response = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[{"role": "user", "content": "List three fruits with their colors"}],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "fruits",
            "schema": {
                "type": "object",
                "properties": {
                    "fruits": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {
                                "name": {"type": "string"},
                                "color": {"type": "string"}
                            },
                            "required": ["name", "color"]
                        }
                    }
                },
                "required": ["fruits"]
            }
        }
    }
)

Streaming Responses

For real-time applications, stream tokens as they’re generated:

stream = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Tell me a story"}],
    stream=True
)

for event in stream: if event.type == "content_block_delta": print(event.delta.text, end="")

Vision (Image Input)

Claude can analyze images. Pass base64-encoded image data:

import base64

with open("chart.png", "rb") as f: image_data = base64.b64encode(f.read()).decode("utf-8")

response = client.messages.create( model="claude-sonnet-4-20250514", max_tokens=1024, messages=[ { "role": "user", "content": [ {"type": "text", "text": "Describe this chart"}, {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": image_data}} ] } ] )

Developer Tools

Anthropic provides several tools to accelerate development:

  • Developer Console: Prototype prompts in your browser with the Workbench and prompt generator.
  • API Reference: Full documentation for all endpoints and SDKs.
  • Claude Cookbook: Interactive Jupyter notebooks covering PDF processing, embeddings, and more.

Best Practices

  • Start with Sonnet: It’s the best balance of capability, speed, and cost for most applications.
  • Use system prompts: Set the tone and constraints upfront.
  • Handle errors gracefully: Implement retry logic for rate limits and timeouts.
  • Monitor token usage: Use max_tokens and thinking.budget_tokens to control costs.
  • Test with streaming: It improves user experience for chat applications.

Key Takeaways

  • The Claude API is accessible via the Messages API, with official SDKs for Python and TypeScript.
  • Choose your model based on task complexity: Opus for hard reasoning, Sonnet for general use, Haiku for speed.
  • Key features include extended thinking, tool use, structured outputs, streaming, and vision.
  • Always handle stop_reason to understand why Claude stopped generating.
  • Use the Developer Console and Cookbook to prototype and learn faster.
Ready to build? Head to the Anthropic Console to get your API key and start coding.