Claude Code SDK for Python: Installation, Quick Start, and API Reference

6月16日 Published inDeveloper Tools

The Claude Code SDK for Python allows developers to integrate Claude Code directly into their Python applications. It provides a streamlined interface for sending queries and managing tool calls, removing the need to interact manually with low-level APIs.

Installation

Requirements

  • Python 3.10 or higher
  • Node.js
  • Claude Code: Install the CLI via npm: npm install -g @anthropic-ai/claude-code

Install the SDK

Install the package using pip:

pip install claude-code-sdk

Quick Start

The following example demonstrates how to send a simple query to Claude and print the output.

import anyio
from claude_code_sdk import query

async def main():
    async for message in query(prompt="What is 2 + 2?"):
        print(message)

anyio.run(main)

Usage

Basic Queries

Simple query implementation:

from claude_code_sdk import query, ClaudeCodeOptions, AssistantMessage, TextBlock

async for message in query(prompt="Hello Claude"):
    if isinstance(message, AssistantMessage):
        for block in message.content:
            if isinstance(block, TextBlock):
                print(block.text)

Query with configuration options:

options = ClaudeCodeOptions(
    system_prompt="You are a helpful assistant",
    max_turns=1
)

async for message in query(prompt="Tell me a joke", options=options):
    print(message)

Tool Calling

Grant Claude permission to read files, write data, or execute shell commands.

options = ClaudeCodeOptions(
    allowed_tools=["Read", "Write", "Bash"],
    permission_mode='acceptEdits'  # Automatically approve file modifications
)

async for message in query(
    prompt="Create a hello.py file",
    options=options
):
    # Handle tool usage and resulting output
    pass

Setting the Working Directory

You can define the project directory where the SDK should operate.

from pathlib import Path

options = ClaudeCodeOptions(
    cwd="/path/to/project"  # Accepts strings or Path objects
)

API Reference

query function

Signature: query(prompt, options=None)

Parameters:

  • prompt (str): The text prompt to send to Claude.
  • options (ClaudeCodeOptions): An optional configuration object.

Returns: AsyncIterator[Message] – An asynchronous stream of response messages.

Type Definitions

Comprehensive type definitions are located in src/claude_code_sdk/types.py:

  • ClaudeCodeOptions: Configuration settings for the SDK.
  • AssistantMessage, UserMessage, SystemMessage, ResultMessage: Various message types.
  • TextBlock, ToolUseBlock, ToolResultBlock: Types for different content blocks.

Error Handling

The SDK includes several exception types to help manage specific failure states:

from claude_code_sdk import (
    ClaudeSDKError,      # Base error for the SDK
    CLINotFoundError,    # Claude Code CLI is not installed
    CLIConnectionError,  # Issue connecting to the CLI
    ProcessError,        # The process failed during execution
    CLIJSONDecodeError,  # Error parsing JSON response
)

try:
    async for message in query(prompt="Hello"):
        pass
except CLINotFoundError:
    print("Error: Please install the Claude Code CLI.")
except ProcessError as e:
    print(f"Process failed with exit code: {e.exit_code}")
except CLIJSONDecodeError as e:
    print(f"Failed to parse the CLI response: {e}")

For a complete list of error types, refer to src/claude_code_sdk/_errors.py.