Sending Your First Claude API Request
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
This lesson is hands-on. You will send the same request three ways (curl, Python and PHP), read every part of the response, and learn the checks that separate a request that "worked once" from one you can trust.
Learning objectives
- Send a Messages API request with curl, the Python SDK and the PHP SDK.
- Read
content, stop_reason and usage correctly.
- Diagnose the five most common first-request errors.
Prerequisites
Option 1: curl
curl shows the raw protocol with nothing hidden, which makes it the best tool for understanding the API:
curl https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2026-10-21" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-5-5",
"max_tokens": 300,
"messages": [
{"role": "user", "content": "Explain what an API key is in two sentences."}
]
}'
The reply is JSON like this (the text will differ):
{
"id": "msg_01XFDUDYJgAACzvnptvVoYEL",
"type": "message",
"role": "assistant",
"content": [{"type": "text", "text": "An API key is a secret string ..."}],
"model": "claude-sonnet-5-5",
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {"input_tokens": 18, "output_tokens": 42}
}
Option 2: Python
Install the SDK with pip install anthropic, then run this file. It prints each field you should learn to look at:
import anthropic
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=300,
messages=[{"role": "user", "content": "Explain what an API key is in two sentences."}],
)
print("id: ", message.id)
print("model: ", message.model)
print("stop_reason: ", message.stop_reason)
print("input_tokens:", message.usage.input_tokens)
print("output_tokens:", message.usage.output_tokens)
print("request id: ", message._request_id)
print()
for block in message.content:
if block.type == "text":
print(block.text)
Reading the output: stop_reason should be end_turn; input_tokens and output_tokens are what you are billed for; request id is what you quote to Anthropic support. The loop over message.content is deliberate. A response can contain several blocks, and only the ones with type == "text" carry text.
Option 3: PHP
The official PHP SDK needs PHP 8.1 or later. Anthropic recommends Guzzle, which it configures for streaming automatically:
composer require "anthropic-ai/sdk" "guzzlehttp/guzzle:^7"
<?php
require __DIR__.'/vendor/autoload.php';
use Anthropic\Client;
$client = new Client(); // reads ANTHROPIC_API_KEY from the environment
$message = $client->messages->create(
maxTokens: 300,
messages: [['role' => 'user', 'content' => 'Explain what an API key is in two sentences.']],
model: 'claude-sonnet-5-5',
);
echo 'id: ', $message->id, PHP_EOL;
echo 'stop_reason: ', $message->stopReason, PHP_EOL;
echo 'input_tokens: ', $message->usage->inputTokens, PHP_EOL;
echo 'output_tokens: ', $message->usage->outputTokens, PHP_EOL, PHP_EOL;
foreach ($message->content as $block) {
if ($block->type === 'text') {
echo $block->text, PHP_EOL;
}
}
PHP uses named arguments and camelCase properties (stopReason, usage->inputTokens). The client reads ANTHROPIC_API_KEY from the environment, exactly like the Python SDK.
How to check a response properly
- Did the call return without an exception? (Transport and HTTP errors raise.)
- Is
stop_reason end_turn? If it is max_tokens, the text is cut off. If it is refusal, Claude declined and the call still returned HTTP 200.
- Did you read only the text blocks?
- Did you record
usage and the request or message ID?
Make those four checks a habit now; they are the same in every later lesson.
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
A WordPress agency adds a "suggest meta description" button. The first version just printed the text. After a week, some suggestions ended mid-sentence: max_tokens had been set to 60. Checking stop_reason would have flagged it on day one; logging usage would have shown the outputs always ending at exactly 60 tokens.
Common errors and solutions
| Error | Likely cause | Fix |
401 authentication_error | Missing, wrong or expired key. | Check echo $ANTHROPIC_API_KEY; create a new key. |
404 not_found_error | Typo in the model ID or URL. | Copy the ID from the models overview. |
400 invalid_request_error | A missing required field, or an option the model rejects. | Read the message; it names the field. |
429 rate_limit_error | Rate or spend limit. | Wait for retry-after; see lesson 2.7. |
Class "Anthropic\Client" not found (PHP) | Composer autoload not required. | require 'vendor/autoload.php'; |
Security considerations
- Do not paste real keys into curl commands that end up in shell history on shared machines; use the environment variable as shown.
- Do not print full request or response bodies in production logs if they contain customer data.
Performance and cost considerations
Use a cheap, short test prompt and a small max_tokens while experimenting. Printing usage in every script is free insurance. Lesson 2.9 turns those numbers into a running cost.
Key takeaways
- The same request works with curl, the Python SDK and the PHP SDK; SDKs add typed responses, retries and the headers.
- Always read text blocks,
stop_reason and usage.
- Most first-request failures are a bad key, a bad model ID or a bad option.
Lesson recap: one request, three ways to send it, four checks on the reply.
Knowledge check
- Why loop over
message.content instead of reading the first block?
- What does
stop_reason: "max_tokens" mean for the text you received?
- Which usage fields are billed?
- What does the PHP SDK need besides Composer to stream correctly?
- A 404 on your first call: what do you check first?
Answers and explanations
- A response is a list of blocks, and non-text blocks can appear. Only blocks of type
text contain text.
- The model hit your token limit, so the text may be incomplete.
input_tokens and output_tokens (plus cache fields when caching is used).
- An HTTP client that returns the body incrementally. Guzzle works, and the SDK configures it for streaming.
- The model ID and the endpoint path.
Official references and further reading
Related tutorials