Make a small Claude Messages request from Python, inspect typed content blocks and record returned usage. The script also includes an explicit wrong-model path for testing your error handling.

What you’ll build

This script uses the official Anthropic Python client and the native Messages interface. Official documentation.

The useful result is a working request path with visible diagnostics, not a guaranteed sentence from the model.

The exercise has a deliberately small acceptance target: load the intended Claude credential, send a native Messages request, print its text content and retain the returned usage. It does not add tools, media or a conversation store. Keeping those features out of the first program makes an access or SDK problem easier to isolate.

Before running it, decide what would count as success. An accepted request establishes the connection and model access; an understandable short explanation establishes that you interpreted text content. Neither result proves that Claude can handle your application’s real task. Keep that broader evaluation as the next step rather than treating this demonstration as a production benchmark.

Prerequisites

Complete the Claude API-key guide and configure the authorized credential in the environment. Confirm the live model record is available to your account before running a paid request.

Create a dedicated project directory and use the Python environment intended for the experiment. Check that your editor and terminal run the same interpreter. Save the script as a clearly named file rather than pasting fragments into different sessions whose imports and environment variables may differ.

Set the secret through your operating system’s environment controls or the application’s existing secret mechanism. Confirm that the variable exists without printing its value. Record which Claude workspace owns the credential and verify the selected model in the current catalog. If the account has no authorized billing arrangement for inference, finish the local preparation and obtain that arrangement before running the request.

Install SDK

python -m pip install --upgrade anthropic

Install the official package in the environment that will run the script. If an import fails afterward, inspect the interpreter and package location before reinstalling repeatedly. Avoid naming your own script anthropic.py, because that can shadow the package you intend to import and produce confusing errors unrelated to the API.

Once the example works, record the package version used for the result. For an application you maintain, make dependency updates reviewable and rerun the relevant examples after an update. The tutorial’s installation command is a starting point for a fresh experiment, not a substitute for your project’s reproducible dependency policy.

Full script

import os
import sys
import anthropic

model = os.environ.get("ANTHROPIC_MODEL", "claude-opus-5")
if "--bad-model" in sys.argv:
    model = "ai-api-hub-invalid-model"
client = anthropic.Anthropic(
    api_key=os.environ["ANTHROPIC_API_KEY"], timeout=30.0, max_retries=0
)
try:
    message = client.messages.create(
        model=model, max_tokens=256,
        messages=[{"role": "user", "content": "Explain prompt caching in a short sentence."}],
    )
    for block in message.content:
        if block.type == "text":
            print(block.text)
    print(message.usage.model_dump_json())
except anthropic.APIStatusError as exc:
    print(f"HTTP {exc.status_code}")
    print(exc.response.text)
    raise SystemExit(1)

Read the configuration at the top before executing the program. The model can be selected through a separate environment variable, while the API secret is required explicitly. The invalid-model branch changes only the identifier, which makes the intended error easy to distinguish from a missing credential or malformed payload. The client also has a timeout and disables automatic retries for this first diagnostic exercise.

The response loop checks each content block’s type before printing text. Keep that pattern when extending the program: a future request may introduce content that your application must handle differently. The example prints usage separately from the answer so you can copy it into an evaluation record without assuming the visible text accounts for the entire request.

Expected output

Schematic output follows. This is an explanatory example, not an observed provider response; wording and usage depend on your actual request.

A short explanation of prompt caching.
{"input_tokens": 12, "output_tokens": 18}

Your real result will contain model-generated wording and service-generated metadata. Compare its structure with the schematic example, but do not write a test that expects the exact illustrative sentence. Instead, check that the application received the expected kind of content and that your chosen task criterion was met.

Record the model identifier, prompt revision, SDK version and returned usage with the outcome. Keep the API key out of that record. If the program exits before printing an answer, inspect the error rather than changing the acceptance criterion to count any output as success. An exception message is diagnostic evidence, not a completed model response.

One deliberate error and its fix

python first_anthropic.py --bad-model

The branch sends ai-api-hub-invalid-model instead of the normal model identifier. Keep the credential configured so the request reaches model validation. The script exposes the returned rejection and stops; restore the ordinary command to use the supported model again.

The following error-field excerpt was captured on 2026-09-12 15:53 UTC from an authorized HTTP request to the same provider interface. It used harmless connection-validation input and small output settings. This records the provider’s rejection; it does not claim that the Python SDK example itself was executed.

These are normalized captured fields with the message preserved verbatim. They are not a reconstructed full provider response envelope. Empty fields and request identifiers are omitted.

{
  "http_status": 404,
  "type": "not_found_error",
  "message": "model: ai-api-hub-invalid-model"
}

Fix the deliberate error by restoring a current accessible model identifier. Do not resend the invalid identifier in a retry loop. If the ordinary request also fails, inspect that response independently because permission, funding and request validation can fail at different stages. Official error reference.

Keep the missing-key startup check as an additional local configuration guard. It tests whether the process can read its environment; it does not establish that the provider accepted the key or evaluated the requested model.

What this request costs

Interactive tool

Estimate your API costs

Your text and estimates stay in this browser. No API requests are sent to model providers.

Loading verified model records…

Copy the returned usage into the workload calculator instead of guessing from visible character length.

Use the returned usage as the starting point for the estimate. Keep the model identifier attached to those counts, because a value measured against one model should not silently become the assumed count for every other model. Record whether the example used only the simple text path shown here or whether you added features that need additional charge categories.

Do not multiply a single friendly example into a confident production forecast. Collect representative inputs and accepted outputs from the application’s real task. Compare the distribution of request shapes and keep conservative assumptions for cases not yet measured. The calculator helps you explain those assumptions; it does not turn an untested workload into observed billing evidence.

Next steps

Add application-specific evaluation cases, then read Claude errors before enabling retries. Introduce tools or attachments only after the basic path is reliable.

Turn the demonstration into an application gradually. Add a saved evaluation pack first, then introduce the content type or tool behavior the task actually needs. Keep the original text-only request as a diagnostic baseline so a later failure can be narrowed to access, model selection or the newly added feature.

Before running unattended, add protected diagnostics, deliberate retry ownership and a clear stop condition. Document who owns the credential and how to rotate it. Review the result-handling code when enabling streaming or non-text content. The program is ready to grow when another developer can reproduce its successful path, explain its deliberate failure and identify what remains untested.

Last verified · Source ↗

Frequently asked questions

Which endpoint should a new Claude integration use?
Begin with the native Messages API and preserve its content-block response structure. Official documentation.
Where are the current Claude model identifiers?
Use the Models API or the official catalog, then copy the identifier for the direct Claude API. Official documentation.
Can I compare cached and uncached requests?
Yes. Separate initial cache writes, cache reads and ordinary input before comparing the workload. Official documentation.
Does a successful key test prove production capacity?
No. Check the organization and workspace limits as well as your application’s expected traffic pattern. Official documentation.
What should I retain when a request fails?
Keep the request identifier, error type, timestamp and a redacted reproduction. Remove credentials before sharing it. Official documentation.

Sources

Last verified · Source ↗