Python で Claude API を使い始めるガイド
KDnuggets は、開発者が Python を用いて Anthropic の Claude API に接続し、基本的な利用方法を習得するための具体的な手順を解説したガイド記事を公開しました。
キーポイント
Python 環境の構築とライブラリ導入
Claude API を利用するために必要な Python のセットアップ手順と、anthropic ライブラリのインストール方法を解説しています。
API キーの設定と認証プロセス
セキュリティを確保するための環境変数への API キー設定方法や、認証トークンの取得・管理のベストプラクティスを伝えています。
基本的なプロンプト送信の実装コード
Python スクリプト内で Claude モデルにテキストをリクエストし、レスポンスを取得する最小限の実装コードを示しています。
影響分析・編集コメントを表示
影響分析
この記事は、Claude API の導入障壁を下げる重要な役割を果たします。特に Python エコシステムを利用する開発者にとって、初期設定から動作確認までの具体的なステップを提供することで、実装スピードを向上させる効果が期待されます。
編集コメント
本記事は特定のモデルの初期利用に特化した実践的なチュートリアルであり、Claude API を活用したアプリケーション開発を始めるための最適な入り口となっています。
image**
# イントロダクション
Python アプリケーションに Claude を追加したいと考えている場合。アカウントの作成と最初の API 呼び出しは非常に簡単です。公式ドキュメントを使えば、数分でゼロから動作するリクエストまで到達できます。次に一般的に問われるのは、より実践的な質問です:
- レスポンスオブジェクトには何が含まれているのか?
- ユーザーが生成される出力をリアルタイムで確認できるようにするには、どのようにレスポンスをストリーミングすればよいのか?
- 本番環境のアプリケーションでプロンプトをどう構造化し、レスポンスをどう処理すべきか?
Claude Python SDK** は、基盤となる API 相互作用の多くを処理してくれます。型付きのレスポンスオブジェクトを提供し、組み込みのリトライハンドリング機能を持ち、Messages API を扱うためのシンプルなインターフェースを用意しています。
この記事では、セットアップ、最初の API 呼び出し、レスポンスの読み取り、システムプロンプト、ストリーミングについて順を追って解説します。最後まで読むと、すぐに使える基盤が整います。
# 前提条件とインストール
**
Python 3.9 以上が必要で、無料の Claude Console アカウント と、Console の「設定 > API キー」ページから取得した API キーが必要です。クレジットを$5 追加すれば、この記事の内容すべてを実行できます。
これらを用意したら、SDK をインストールします:
pip install anthropic
API キーをソースファイルにハードコードしてはいけません。代わりに環境変数として保存してください:
export ANTHROPIC_API_KEY="YOUR-API-KEY-HERE"
または、python-dotenv を使用している場合は、プロジェクトのルートディレクトリに .env ファイルを追加してください。SDK は環境変数から ANTHROPIC_API_KEY を読み取るため、コード内で明示的に指定する必要はありません。
# 最初の API コールの実行
**
すべての対話のエントリーポイントは client.messages.create() です。Claude にコンテキストウィンドウ(context window)が何かを説明させてみましょう。これは、API を使用する際に実際に理解しておく必要がある概念です。
あなたは 3 つのものを渡します:モデル ID、max_tokens の上限、そしてメッセージリストです。メッセージリストは常に辞書のリストであり、各辞書には "role" と "content" というキーが含まれます。
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-sonnet-5",
max_tokens=256,
messages=[
{
"role": "user",
"content": "コンテキストウィンドウとは、一言で何ですか?"
}
]
)
print(response.content[0].text)
model フィールドには正確なモデル ID の文字列を指定します。max_tokens は Claude が生成する出力トークンの絶対上限です。思考が完了していなくても、ここで応答は停止するため、自由形式の要求に対しては十分な高い値を設定してください。メッセージリストは常に "user" ターンから始まる必要があります。
サンプル出力:
コンテキストウィンドウとは、言語モデルが一度に処理し考慮できるテキストの最大量(トークン単位で測定)を指し、入力と出力の両方を含みます。
# レスポンスオブジェクトの理解
messages.create() からのレスポンスは 型付き Message オブジェクト です。その上に何かを構築する前に、完全な構造を確認しておく価値があります。
前回の例の print 行を以下のように置き換えてください:
print(response)
これを実行すると、完全なオブジェクトが得られます:
Message(
id='msg_01XFDUDYJgAACzvnptvVoYEL',
type='message',
role='assistant',
content=[TextBlock(text='A context window is...', type='text')],
model='claude-sonnet-5',
stop_reason='end_turn',
stop_sequence=None,
usage=Usage(input_tokens=19, output_tokens=42)
)
ここでいくつかのフィールドは、初見では思われる以上に重要です。stop_reason は Claude が生成を停止した理由を示します。end_turn とは、Claude が自らの条件で完了したことを意味します。もし max_tokens が見られた場合、レスポンスはあなたの設定した制限によって切り捨てられています。その場合は制限を引き上げるか、プロンプトを見直す必要があるかもしれません。
usage フィールドは、リクエストに対する入力トークンと出力トークンの両方を追跡します。これが Anthropic による請求計算の根拠であり、プロンプトがモデルのコンテキスト制限に近づきすぎたことを検出する方法でもあります。content はリストです(標準的なテキスト応答では常に 1 つの項目を持ち、TextBlock です)— そのため response.content[0].text がテキストを取り出すための慣用的な方法となります。
# システムプロンプトの使用
システムプロンプトを使用すると、Claude に永続的な役割を与えたり、制約を設定したり、会話全体に適用されるべきコンテキストを提供したりできます。これはメッセージリストとは別に、トップレベルのシステムパラメータとして渡します(メッセージ自体としては扱いません)。
ここでは、Claude を Python のコードのみで回答し、一般的な説明を避けるコードレビューアーとして動作するように設定します:
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-sonnet-5",
max_tokens=512,
system=(
"You are a Python code reviewer. "
"Respond only with corrected or improved Python code. "
"Do not explain changes unless the user explicitly asks."
),
messages=[
{
"role": "user",
"content": (
"def get_user(id):\n"
" db = connect()\n"
" return db.query('SELECT * FROM users WHERE id=' + id)"
)
}
]
)
print(response.content[0].text)
システムプロンプトは、Claude のコンテキスト内において会話の上に位置します。ここで行う役割指示、フォーマットルール、ドメイン制約は、すべてのターンを通じて同じ権限を持ち続けるため、各メッセージで繰り返し指定する必要はありません。
# ストリーミングレスポンス
Claude が応答に数秒を要する可能性があるリクエストでは、ストリーミングを使用することで、完全な応答が完了するのを待たずに、到着したテキストを逐次表示できます。SDK は client.messages.stream() をコンテキストマネージャーとして使用してこれを公開しています。
text_stream イテレータは、リアルタイムで個々のテキストチャンクを生成します。各チャンクは完全な文ではなく、文字列の断片です。出力がバッファリングされず連続して表示されるように、print() 関数に end="" と flush=True を渡します:
import anthropic
client = anthropic.Anthropic()
with client.messages.stream(
model="claude-sonnet-5",
max_tokens=512,
messages=[
{
"role": "user",
"content": "Python のリストが初期容量を超えて成長する際に何が起こるのか、順を追って説明してください。"
}
]
) as stream:
for chunk in stream.text_stream:
print(chunk, end="", flush=True)
print() # ストリーミング終了後に改行
コンテキストマネージャーは、ブロックから脱出する際、途中で例外が発生した場合でも HTTP 接続をきれいにクローズすることを保証します。ストリーミング後に完全な Message オブジェクト(トークン使用量カウントを含む)が必要であれば、ブロックが閉じる前に stream.get_final_message() を呼び出してください。
サンプル出力:
Python のリストは動的配列です。要素を追加した際にリストに空きがない場合、Python は新しいより大きなメモリブロックを割り当てます(通常は現在のサイズの 1.125 倍)、既存のすべての要素をそこにコピーし、古いブロックを解放します。この操作は最悪の場合 O(n) ですが、追加回数に対して頻繁には発生しないため、追加あたりの平均コストは O(1) のままです。最終サイズが事前にわかっている場合は、リスト内包表記を使用するか、list コンストラクタに反復可能オブジェクトを渡すことで容量を事前割り当てできます。
# 次のステップ
これで、リクエスト、構造化されたレスポンス、システムプロンプト、ストリーミングという中核的な構成要素が揃いました。
次に、エラーハンドリング、トークン使用量、多回対話について学ぶことができます。API はステートレスであるため、各リクエストで会話履歴を送信する必要があります。SDK ドキュメント に推奨アプローチが記載されています。
Bala Priya C はインド出身のエンジニア兼テクニカルライターです。数学、プログラミング、データサイエンス、コンテンツ制作が交差する領域での作業を好んでいます。彼女の専門分野や関心領域には、DevOps(開発運用)、データサイエンス、自然言語処理が含まれます。読書、執筆、コーディング、そしてコーヒーを楽しむのが好きです。現在、チュートリアル、ハウツーガイド、意見記事などを執筆することで、開発者コミュニティに知識を共有し、学びを広げる活動を行っています。また、魅力的なリソースの概要やコーディングチュートリアルも作成しています。
原文を表示

**
# Introduction
You want to add Claude to a Python application. Creating an account and making your first API call is straightforward. The official documentation can get you from zero to a working request in a few minutes. The next questions are usually more practical:
- What does the response object contain?
- How do you stream responses so users can see output as it's generated?
- How do you structure prompts and handle responses in a production application?
The Claude Python SDK** takes care of much of the underlying API interaction. It provides typed response objects, built-in retry handling, and a simple interface for working with the Messages API.
This article walks you through setup, your first API call, reading the response, system prompts, and streaming. By the end, you'll have a working foundation.
# Prerequisites and Installation
**
You need Python 3.9 or higher, a free Claude Console account, and an API key from the Console's Settings > API Keys** page. You can add $5 in credits and work through everything in this article.
With those in place, install the SDK:
pip install anthropicNever hardcode your API key in source files. Store it as an environment variable instead:
export ANTHROPIC_API_KEY="YOUR-API-KEY-HERE"Or add it to a .env file at the project root if you're using python-dotenv. The SDK reads the ANTHROPIC_API_KEY from your environment, so you don't need to pass it anywhere in your code.
# Making Your First API Call
**
The entry point for every interaction is client.messages.create(). Let's ask Claude to explain what a context window is, something you'll actually need to understand as you use the API.
You pass three things: the model ID, a max_tokens limit, and a messages list. The messages list is always a list of dicts, each with a "role" and "content" key.
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-sonnet-5",
max_tokens=256,
messages=[
{
"role": "user",
"content": "In one sentence, what is a context window?"
}
]
)
print(response.content[0].text)The model field takes the exact model ID string. max_tokens is a hard ceiling on how many output tokens Claude will produce; the response stops there even if the thought isn't complete, so set it high enough for open-ended requests. The messages list must always start with a "user" turn.
Sample output:
A context window is the maximum amount of text (measured in tokens) that a language
model can process and consider at one time, encompassing both your input and its output.# Understanding the Response Object
The response from messages.create() is a typed Message object. It's worth inspecting the full structure before building anything on top of it.
Replace the print line in the previous example with:
print(response)Running that gives you the full object:
Message(
id='msg_01XFDUDYJgAACzvnptvVoYEL',
type='message',
role='assistant',
content=[TextBlock(text='A context window is...', type='text')],
model='claude-sonnet-5',
stop_reason='end_turn',
stop_sequence=None,
usage=Usage(input_tokens=19, output_tokens=42)
)A few fields here matter more than they first appear. stop_reason tells you why Claude stopped generating. end_turn means Claude finished on its own terms. If you see max_tokens, the response was cut off by your limit, and you may need to raise it or rethink the prompt.
The usage field tracks both input and output tokens for the request. This is how Anthropic calculates billing, and it's also how you detect when a prompt is creeping too close to the model's context limit. content is a list — in standard text responses it always has one item, a TextBlock — so response.content[0].text is the idiomatic way to pull the text out.
# Using System Prompts
A system prompt lets you give Claude a persistent role, set constraints, or provide context that should apply across the entire conversation. You pass it as a top-level system parameter — separate from the messages list, not as a message itself.
Here we configure Claude to act as a code reviewer who only responds in Python and avoids general explanations:
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-sonnet-5",
max_tokens=512,
system=(
"You are a Python code reviewer. "
"Respond only with corrected or improved Python code. "
"Do not explain changes unless the user explicitly asks."
),
messages=[
{
"role": "user",
"content": (
"def get_user(id):\n"
" db = connect()\n"
" return db.query('SELECT * FROM users WHERE id=' + id)"
)
}
]
)
print(response.content[0].text)The system prompt sits above the conversation in Claude's context. It carries the same authority throughout all turns, so role instructions, formatting rules, and domain constraints you set here persist without you repeating them in every message.
# Streaming Responses
For requests where Claude may take a few seconds to respond, streaming lets you display text as it arrives instead of waiting for the full response. The SDK exposes this through client.messages.stream(), used as a context manager.
The text_stream iterator yields individual text chunks in real time. Each chunk is a string fragment, not a full sentence. You pass end="" and flush=True to print() so output appears continuously rather than buffering:
import anthropic
client = anthropic.Anthropic()
with client.messages.stream(
model="claude-sonnet-5",
max_tokens=512,
messages=[
{
"role": "user",
"content": "Walk me through what happens when a Python list grows beyond its initial capacity."
}
]
) as stream:
for chunk in stream.text_stream:
print(chunk, end="", flush=True)
print() # newline after stream endsThe context manager ensures the HTTP connection is closed cleanly when the block exits, even if an exception is raised mid-stream. If you need the complete Message object after streaming — including token usage counts — call stream.get_final_message() before the block closes.
Sample output:
Python lists are dynamic arrays. When you append an element and the list has no
room, Python allocates a new, larger block of memory — typically 1.125x the current
size — copies all existing elements into it, and releases the old block. This
operation is O(n) in the worst case, but because it happens infrequently relative to
the number of appends, the amortized cost per append stays O(1). You can pre-allocate
capacity with a list comprehension or by passing an iterable to the list constructor
if you know the final size upfront.# Next Steps
You now have the core building blocks: requests, structured responses, system prompts, and streaming.
Next, you can learn about error handling, token usage, and multi-turn conversations. Because the API is stateless, you need to send the conversation history with each request. The SDK documentation shows the recommended approach.
Bala Priya C** is a developer and technical writer from India. She likes working at the intersection of math, programming, data science, and content creation. Her areas of interest and expertise include DevOps, data science, and natural language processing. She enjoys reading, writing, coding, and coffee! Currently, she's working on learning and sharing her knowledge with the developer community by authoring tutorials, how-to guides, opinion pieces, and more. Bala also creates engaging resource overviews and coding tutorials.
関連記事
今日のまとめ
AI日報で今日の重要ニュースをまとめ読み