Claude API Quick Start
The Messages API accepts conversation messages and returns typed content blocks. This example makes one request; it does not create a persistent chat session.
#Prepare the environment
bashpython -m venv .venv source .venv/bin/activate python -m pip install anthropic
On Windows PowerShell, activate with .venv\Scripts\Activate.ps1. Configure ANTHROPIC_API_KEY and ANTHROPIC_MODEL in your server environment. Select an available model from your account; a product subscription does not automatically include API billing. Never put the key in frontend code.
#Send a message
The following Python example requires an authorized API account and may incur usage charges when run.
pythonimport os from anthropic import Anthropic client = Anthropic() response = client.messages.create( model=os.environ["ANTHROPIC_MODEL"], max_tokens=512, system="Explain Python concepts with one short example.", messages=[{"role": "user", "content": "What does a decorator do?"}], ) for block in response.content: if block.type == "text": print(block.text) print(response.stop_reason) print(response.usage)
Read all text blocks rather than assuming the first block is always text. A max_tokens stop can mean the answer is incomplete. Usage and response identifiers are useful for diagnostics; avoid logging private prompts by default.
#Continue the conversation
Keep a server-owned history. After a successful response, append its assistant content, then append the next user message and send the history again. The system instruction is a separate top-level field. Enforce a context budget and preserve tool-use/result pairs when trimming.
At the HTTP level, Messages uses POST /v1/messages, the x-api-key header and an anthropic-version header. Prefer the maintained SDK for timeout and response handling. Investigate authentication failures, unsupported model IDs and rate limits separately; retries do not fix invalid credentials.