Claude API Guide: Pricing, Setup, and Your First Request

claude-api-guide-hero

To make your first Claude API request, create a Claude Console key, keep it in an environment variable, call the Messages endpoint, read the returned использование fields, and calculate the token cost. This guide walks through that path with current model IDs and prices verified on September 8, 2026.

Once you understand the API path, the next question is how much of your day-to-day work actually needs custom integration. For research, writing, coding, and creative production, GlobalGPT offers a more economical way to use Claude alongside GPT-5.6 Sol, Gemini 3 Pro, Kimi K3, and other leading models. One subscription brings the models and a broad set of AI tools into one dashboard, so the work can move from idea to output without being split across separate services. When you do need to bring AI into your development setup, the GlobalGPT CLI connects that same workspace to your terminal and existing production tools.

What Is the Claude API?

The Claude API is Anthropic’s developer interface for sending structured requests to Claude models from an application, script, or backend service. You send messages to an HTTPS endpoint and receive a structured response containing generated content plus metadata such as the model, stop reason, and token usage.

Claude API vs. Claude.ai subscriptions

API access and Claude.ai subscriptions solve different jobs. A Claude.ai plan gives a person access to Anthropic’s chat product. The API is metered developer access through Claude Console, with separate billing based on usage. Anthropic’s Help Center states that Claude Pro does not include Console API usage.

If you need the wider distinction between consumer plans, Claude Code, and token billing, see our complete Руководство по ценам на Claude. For this tutorial, the important point is simple: create and fund the API account separately from any Claude.ai subscription.

The five-step path to a first request

  1. Create an API key in Claude Console.
  2. Store it in the ANTHROPIC_API_KEY environment variable.
  3. Send a request to https://api.anthropic.com/v1/messages.
  4. Read the returned content and использование object.
  5. Multiply each token category by its applicable per-million-token rate.

Claude API Pricing and Current Model IDs

Anthropic lists API prices in US dollars per million tokens, often abbreviated as MTok. Input and output are billed separately. Prompt caching adds distinct rates for five-minute writes, one-hour writes, and cache reads, so a reliable estimate keeps those categories separate.

Current models and exact API IDs

МодельИдентификатор APIВвод / MTokВыход / MTok
Claude Fable 5.1claude-fable-5-1$10$50
Claude Opus 5claude-opus-5$5$25
Клод, сонет № 5claude-sonnet-5$2$10
Клод Хайку 4.5claude-haiku-4-5-20251001$1$5
Base API rates verified against Anthropic’s official pricing and model documentation on September 8, 2026.
Anthropic model table showing current Claude model names and API IDs
Current Claude model IDs in Anthropic’s official documentation, verified September 8, 2026.

Which model should you use for this tutorial?

The official Quickstart used claude-opus-5 when this guide was verified, so the cURL and Python examples below use the same ID. Treat Opus as a starting point for the tutorial, then choose the production model by workload, quality needs, latency, and budget. Model IDs and lifecycle status can change, so recheck the Models and deprecations pages before shipping long-lived code.

Official Anthropic Claude API pricing table with token-category rates
Anthropic API prices are listed per million tokens and can change; rates shown were verified September 8, 2026.
Claude API base token prices

USD per million tokens. Bar length is normalized to the $50 output maximum.

ВходВыход
Claude Fable 5.1claude-fable-5-1
Вход $10
Выход $50
Claude Opus 5claude-opus-5
Вход $5
Выход $25
Клод, сонет № 5claude-sonnet-5
$2 input
$10 output
Клод Хайку 4.5claude-haiku-4-5-20251001
$1 input
Выход $5
Rates verified 2026-09-08. Cache, Batch, and US-only modifiers are not shown here.Official Anthropic pricing

What You Need Before Your First Request

Create a Claude Console account and API key

Open Claude Console, create or select the appropriate organization, and create an API key. Anthropic warns that a new key is displayed only once, so store it in an approved secret manager or another secure location when it appears. Do not put the key into a screenshot, shared document, public repository, or browser-side JavaScript.

Anthropic documentation warning that a new Claude API key must be stored securely
Store the API key securely when it is created; never place it in browser-side code or a screenshot.

Store the key in an environment variable

The examples expect the variable ANTHROPIC_API_KEY. Enter the real value only in your private terminal or secret-management system. The command below reads the value without echoing it to the screen, then exports it for the current shell session:

read -s ANTHROPIC_API_KEY
export ANTHROPIC_API_KEY

Environment variables reduce accidental exposure, but they are not a complete secret-management strategy. Production applications should follow the hosting platform’s secret-storage and access-control practices.

Check billing and choose a safe test limit

API billing is separate from Claude.ai subscriptions. Anthropic says most organizations prepay usage credits, while organizations with monthly invoicing are an exception. Confirm that your Console account can make API requests, then keep the first request small with max_tokens: 128. That field limits generated output; it does not reserve or guarantee 128 billed output tokens.

Send Your First Claude API Request with cURL

cURL is useful for seeing the request contract directly. The example below uses the Messages endpoint, JSON content type, the API key header, Anthropic’s version header, the verified Quickstart model ID, and one user message.

Before you run either example, add your own API key and confirm that API billing is enabled for the organization. The code follows Anthropic’s documented request format and passed local syntax checks, but no live account response is included here.

First Claude API request with cURL
API сообщенийПеременная средыAdd your key to run
curl https://api.anthropic.com/v1/messages \
  --header "content-type: application/json" \
  --header "x-api-key: $ANTHROPIC_API_KEY" \
  --header "anthropic-version: 2023-06-01" \
  --data '{
    "model": "claude-opus-5",
    "max_tokens": 128,
    "messages": [{
      "role": "user",
      "content": "Reply with one sentence explaining what an API is."
    }]
  }'

Add your Claude Console key through the environment variable, keep the version header in place, and run the command from a private terminal.

What each header and JSON field does

PartЦель
content-typeTells the endpoint that the request body is JSON.
x-api-keyAuthenticates the request with the value stored in the environment variable.
anthropic-versionSelects the documented API contract used by the request.
модельChooses the exact Claude API model ID.
max_tokensSets the maximum number of tokens Claude may generate for this response.
сообщенияProvides the ordered conversation input, including each role and content value.

If the command returns an error, read the HTTP status and error type before changing the request. Authentication and billing errors need an account fix, while malformed JSON or an invalid model ID needs a request change.

Send the Same Request with the Python SDK

Install the official Anthropic SDK

python -m pip install anthropic

Use a virtual environment when that is part of your normal Python workflow. The SDK reads ANTHROPIC_API_KEY from the environment when anthropic.Anthropic() is created without an explicit key.

Run the equivalent Python request

First Claude API request with Python
Official SDKПеременная средыPrints usage
import anthropic

client = anthropic.Anthropic()

message = client.messages.create(
    model="claude-opus-5",
    max_tokens=128,
    messages=[
        {
            "role": "user",
            "content": "Reply with one sentence explaining what an API is.",
        }
    ],
)

for block in message.content:
    if block.type == "text":
        print(block.text)

print(message.usage)

The SDK reads the same environment variable, returns typed content blocks, and exposes usage data for cost tracking.

Official Anthropic Python SDK quickstart for sending a Claude API message
Anthropic’s Python quickstart sends a Messages API request through the official SDK.

Read the returned text safely

A Message response can contain more than one content block, so the example checks each block’s type before printing text. Real applications should also keep the request ID available for support and logging without exposing it publicly, record the returned model and stop reason, and handle API errors explicitly.

Keep the content-block check even when you expect a short text answer. It makes the example easier to extend when a response contains multiple blocks, and printing message.usage gives you the numbers needed for the cost calculation below.

How to Read Usage and Calculate Cost

Find the response text, model, stop reason, and request ID

The Messages API response contract includes generated content, the model that handled the request, and a stop reason. The HTTP response also carries a request identifier that can help Anthropic support trace a problem. Log identifiers carefully; do not publish them with customer content or credentials.

Find input, output, and cache token usage

Сайт использование object reports the token categories needed for cost analysis. At minimum, look for input and output tokens. When prompt caching is used, keep five-minute cache writes, one-hour cache writes, and cache reads separate because they have different rates. Anthropic’s Token Counting endpoint can estimate input tokens before a request, but the estimate can differ slightly from final input usage and has its own rate limits.

Convert token usage into an estimated cost

Calculate each category independently, then add the results. For a planning example using Claude Opus 5 at standard global rates, 1,000 uncached input tokens cost 1,000 x $5 / 1,000,000 = $0.005, while 300 output tokens cost 300 x $25 / 1,000,000 = $0.0075. The estimated total is $0.0125. Replace these illustrative token counts with the использование values from your own response.

Claude API Pricing Calculator

Use the calculator to vary the model, request count, token categories, billing mode, and inference geography. Batch processing prices eligible usage at 50% of standard rates. US-only inference applies a 1.1x factor to all token categories for eligible Claude 4.6+ models; Claude Haiku 4.5 is not eligible, so that combination returns an unsupported state.

Claude API Pricing Calculator

Base token estimate in USD. Account-specific charges are excluded.

Rates verified 2026-09-08
Billing mode
1 to 1,000,000

Default estimate: Claude Opus 5, Standard, Global.
По запросу$0.012500
Total workload$0.012500

claude-opus-5 | Standard | Global

КатегорияTokens/requestEffective $/MTokВсего

The estimate is a planning aid, not an invoice. It excludes taxes, currency conversion, negotiated terms, Fast Mode, server-tool charges, and account-specific conditions. Prices and eligibility can change, so recheck the official pricing page before making a purchasing or architecture decision.

The calculator above shows the cost shape of programmable, metered Claude API calls. For everyday work that spans several models and AI capabilities, GlobalGPT offers a different kind of value: one subscription brings multiple mainstream models and tools into one dashboard, making costs easier to anticipate while keeping research, writing, coding, and creative work out of separate subscriptions and scattered interfaces. Its CLI carries the same platform into terminal-based development and the production tools you already use. Our guide to working with multiple AI models in one place shows how the wider platform fits together.

Common Claude API Errors and Fixes

Start with the HTTP status and Anthropic error type, then inspect the request without exposing the key. The official meaning narrows the search; the likely cause still depends on your account, selected model, request shape, and traffic.

Anthropic API documentation for 400 through 413 client errors
Anthropic separates malformed requests, authentication, credit, permission, missing-resource, conflict, and request-size errors.
СтатусOfficial boundaryWhat to check nextRetry?
400Invalid requestValidate JSON, field names, roles, model ID, and parameter combinations.Only after correcting the request.
401Authentication errorConfirm the key exists, is active, and reaches the server through x-api-key. Never print it.No blind retry; fix authentication first.
402Billing or credit requirementCheck the organization’s API billing and available usage credits in Console.After the billing condition is resolved.
403Permission errorCheck whether the key and organization can use the requested resource or model.No blind retry; correct access first.
404Resource not foundCheck the endpoint, resource identifier, model lifecycle, and spelling.Only after correcting the target.
413Request too largeReduce request size or split the input; do not merely increase max_tokens.After reducing the request.
429Превышен лимит скоростиInspect rate-limit headers and your Console tier, reduce concurrency, and back off.Yes, with controlled backoff.
500Internal API errorRecord the request ID, preserve idempotency, and check Anthropic status information.Usually, with bounded backoff.
504Gateway timeoutCheck whether the request was unusually long and whether retrying could duplicate work.Often, if the operation is safe to retry.
529API temporarily overloadedReduce bursts and retry after backoff; do not treat overload as an authentication failure.Yes, with bounded backoff.
Anthropic API documentation for 429 through 529 limit and server errors
Rate limits, server failures, timeouts, and overloaded responses need different retry decisions.

A safe debugging order

  1. Record the status, error type, timestamp, and request ID without recording the API key.
  2. Check the endpoint, headers, JSON syntax, model ID, and request-size boundary.
  3. Check organization billing, permissions, rate-limit headers, and current model lifecycle.
  4. Retry only errors that can reasonably be temporary, using bounded exponential backoff and jitter.
  5. If the error persists, reduce the request to the smallest reproducible case before contacting support.

Anthropic’s official SDKs retry connection errors, 429 responses, and 5xx responses twice by default. Application-level retry logic still needs limits and idempotency awareness, especially when a request can trigger tools or another external action.

How to Control Claude API Costs

Set conservative output limits

Start with the smallest max_tokens value that can still produce a useful answer. Measure actual output usage before increasing it. Shorter prompts can help, but removing instructions that prevent retries, errors, or unusable output can cost more overall.

Use prompt caching and Batch only when they fit

  • Use prompt caching when a substantial prompt prefix repeats and the cache lifetime matches the workflow.
  • Use Batch for work that can complete asynchronously; eligible Batch usage is priced at 50% of standard rates.
  • Keep cache writes and reads separate in reporting so the saving is visible rather than assumed.
  • Use US-only inference only when the residency requirement justifies its 1.1x token-price factor and the selected model is eligible.

Monitor usage, rate limits, and spend limits

Track request count, model ID, input and output usage, cache categories, retries, and errors. Set alerts or spend controls available to your organization, but do not assume that another account’s tier or limit applies to yours. Our deeper guide to Claude plans, API costs, and limits covers the wider billing routes.

Next Steps After Your First Request

Choose the right path for your next project

For an application, continue with Anthropic’s official Messages API reference, streaming guidance, tool-use documentation, model lifecycle pages, and your own logging and evaluation plan. Pin a model strategy deliberately, handle errors before adding traffic, and calculate costs from observed usage rather than prompt length alone.

If coding is your main use case, our guide to Использование искусственного интеллекта Клода для кодирования covers practical ways to move from an interactive coding task to a repeatable developer workflow.

When a multi-model workspace is the better tool

Direct API access is the right route when you need code-level integration, developer billing, request metadata, or official platform controls. If your goal is interactive writing, research, planning, or comparing outputs across providers without building an application, a multi-model workspace may be more practical.

Часто задаваемые вопросы

Is the Claude API free?

No universal free API allowance is promised here. Claude API usage is billed separately through Claude Console, and Anthropic says most organizations fund usage with prepaid credits, while monthly-invoiced organizations are an exception. Check the current Console and official pricing information for your organization before sending requests.

How do I get a Claude API key?

Create a key in Claude Console for the appropriate organization. Anthropic warns that the new key is displayed only once, so store it securely when it appears. Load it through a server-side environment variable or secret manager, and never expose it in browser code, screenshots, or a public repository.

Which Claude model ID should I use?

This tutorial uses claude-opus-5 because that was the model in Anthropic’s official Quickstart when verified on September 8, 2026. Choose the model that fits your workload and budget, and recheck Anthropic’s Models and deprecations pages because model IDs, aliases, and lifecycle status can change.

What endpoint does the Claude API use?

The first request in this guide uses the Messages endpoint at https://api.anthropic.com/v1/messages. It sends JSON with content-type, x-api-key, and anthropic-version headers. Anthropic provides other API capabilities too, so use the reference page for the operation you are implementing.

Does Claude Pro include API credits?

No. Anthropic’s Help Center states that Claude Pro does not include usage through Claude Console. A Claude.ai subscription and API billing are separate products. Set up API billing in Console for developer requests, and use our Руководство по ценам на Claude for the wider plan comparison.

How much does one Claude API request cost?

Cost depends on the selected model, input tokens, output tokens, cache writes, cache reads, Batch mode, and eligible inference geography. Calculate each category as requests multiplied by tokens multiplied by its effective per-million-token rate, divided by one million, then add the categories. Use the calculator above for an estimate.

Why am I getting a 401 error?

A 401 is an authentication error. Confirm that the API key exists, remains active, belongs to the intended organization, and reaches the server in the x-api-key header. Do not print or share the key while debugging. Repeated retries will not repair a missing or invalid credential.

Why am I getting a 429 error?

A 429 means the request exceeded a rate limit. Limits can vary by organization and usage tier, so inspect the returned rate-limit headers and current Console or documentation. Reduce concurrency, respect retry timing, and use bounded exponential backoff with jitter instead of immediately repeating the same burst.


Source and freshness note: Model IDs, prices, API behavior, and support policies were checked against Anthropic’s official documentation on September 8, 2026. Review the current model and pricing pages before production use, then run the examples with your own Claude Console key, billing setup, and account access.

Поделиться сообщением:

Похожие посты

claude-сравнение-моделей-герой

Сравнение моделей серии Claude: Haiku, Sonnet и Opus, а также место модели Fable в этой линейке

Сравните Claude Haiku 4.5, Sonnet 5 и Opus 5 по скорости, стоимости API, контексту и риску сбоев, а также ознакомьтесь с практическим руководством о том, какое место занимает Fable 5.1 на сегодняшний день.

Читать далее

Создание видео с помощью ИИ на основе модели ChatGPT: практический рабочий процесс

Создавайте видео с помощью ИИ на основе модели ChatGPT, следуя четкому пятиэтапному алгоритму, используя готовые подсказки и отдельную проверку стоимости инструментов. Спланируйте свой первый ролик и избегайте типичных ошибок.

Читать далее

От фотографии к видео с помощью ИИ: практическое руководство по созданию более динамичных видеороликов

Превратите фотографию в видео с помощью ИИ, следуя шести шагам рабочего процесса и трем подсказкам по анимации. Узнайте, на что следует обратить внимание при работе с лицами, продуктами и экспортом, прежде чем тратить деньги снова.

Читать далее
Краткий обзор Hunyuan3D 3.1: быстрое и недорогое преобразование изображений в 3D

Краткий обзор Hunyuan3D 3.1: быстрое и недорогое преобразование изображений в 3D

Нужен 3D-объект на основе одного изображения? Перед тем как выбрать следующий 3D-генератор, ознакомьтесь с нашими тестами Hunyuan3D 3.1: быстрые тесты, проверки реального экспорта, скорость и цены поставщиков.

Читать далее