Documentation Blog Free tools [email protected]Log in

How to use the Claude API: key, first call, tools and agents

Flow from an Anthropic Console API key through your app to the Messages API and out to MCP tools that fetch live web dataOne key, one endpoint, then tools on topAPI keyConsoleYour appSDK or curlMessages API/v1/messagesTool use + MCPlive web datastreamed tokens backsearchscrapecrawlkey and billing live in the Console; everything else is one HTTP POST plus tool definitions

Using the Claude API takes four steps: create an Anthropic Console account, generate an API key, load billing credit, then POST a message to https://api.anthropic.com/v1/messages with that key in the x-api-key header. Everything else — multi-turn chat, tool use, MCP servers, agents — layers onto that single endpoint.

What the Claude API actually is

There is one primary endpoint you will use for almost everything: the Messages API. You send a list of messages with roles (user, assistant), optionally a system string, a model ID and a max_tokens limit. You get back content blocks, a stop reason and a usage object with input and output token counts. Streaming, images, PDFs, extended thinking, tool calls and MCP connections are all parameters on that same request shape rather than separate products.

That matters for how you plan an integration. If you can make one clean call work, scaling to a document pipeline or an agent loop is mostly bookkeeping: managing conversation state, deciding when to hand the model a tool, and keeping token volume under control.

How to get a Claude API key in the Anthropic Console

API access is granted through a Console organisation, which is separate from the consumer Claude app. Anthropic's support docs are explicit that organisations wanting to build with the API should create a Console account, where keys, team members, billing and the Workbench all live, and that access is governed by the Commercial Terms of Service (Anthropic support).

  1. Sign in at the Claude Console (platform.claude.com) with a work email and create or join an organisation.
  2. Open the billing section and add a payment method, then purchase credit. Requests fail with a billing error until the organisation has funds.
  3. Go to API keys and create a key. Name it after the workload, not the person: etl-prod, agent-dev.
  4. Copy the value immediately. It is shown once; after that you can only see metadata about the key, not the secret.
  5. Store it as an environment variable, not in code: export ANTHROPIC_API_KEY=sk-ant-.... Add a separate key per environment so you can revoke one without breaking the others.
  6. Optionally set a spend limit or usage alert before you ship anything that loops.

Is there a free Claude API key?

There is no permanently free production tier. New organisations sometimes receive a small evaluation credit, and the Workbench inside the Console lets you test prompts against your own balance without writing code, but sustained API traffic is paid usage. Free-key offers found outside the Console are either resellers proxying someone else's key or scams; both put your data and your account in someone else's hands.

Does a Claude Pro or Max subscription include API access?

No. A Pro, Max, Team or Enterprise subscription covers the Claude apps; API and Console usage is billed separately, which Anthropic documents in its own help centre. Practically: your subscription login may work to sign in, but you still need an organisation with credit before a request to /v1/messages succeeds. Claude Code is the one place the boundary blurs, since it can authenticate against either a subscription or an API key.

Your first call: curl, then Python

Three headers matter: your key, the API version, and the content type. The version header is required and pinned, so upgrades never silently change response shapes.

curl https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-sonnet-4-5",
    "max_tokens": 512,
    "system": "You are a terse data analyst. Answer in JSON only.",
    "messages": [
      {"role": "user", "content": "Extract the plan names and prices from this text: ..."}
    ]
  }'

Two things trip people up on day one. max_tokens is mandatory and caps the output, so a truncated answer usually means you set it too low, not that the model gave up. And model IDs change: check the model overview page in the docs rather than copying an ID from an old tutorial, and prefer a dated ID in production so behaviour stays stable.

How to call the Claude API in Python

The official SDK reads ANTHROPIC_API_KEY from the environment, handles retries and gives you typed content blocks.

from anthropic import Anthropic

client = Anthropic()  # picks up ANTHROPIC_API_KEY

resp = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=800,
    system="You extract structured data. Output valid JSON, no prose.",
    messages=[{"role": "user", "content": page_text}],
)

print(resp.content[0].text)
print(resp.usage.input_tokens, resp.usage.output_tokens)

Log resp.usage from the first commit. It is the only honest input to cost forecasting, and it is what tells you whether your prompt bloat or your context bloat is the expensive half.

Multi-turn conversations, system prompts and streaming

The API is stateless. There is no conversation ID; you resend the whole history on every turn, appending the assistant's previous reply as an assistant message. That means context grows linearly and so does input cost, which is why long-running agents need a trimming or summarising strategy rather than an ever-growing array.

Put durable instructions in system, not in the first user message — it keeps the role separation clean and makes caching easier later. Set stream: true for anything a human waits on; you get server-sent events with incremental text deltas, and time-to-first-token drops dramatically even though total tokens are identical. Anthropic's own Academy guides and its free Building with the Claude API course walk the same ladder: single call, multi-turn, evals, tools, then agents.

Giving Claude access to the outside world: tool use vs MCP

A bare Messages call can only reason over text you paste in. To let the model act, you either define tools inline in the request, or you connect it to a Model Context Protocol server that advertises its own tools. MCP is an open protocol for exactly this handshake, so one server works across clients instead of being rewritten per app (MCP docs). If you want the deeper comparison, we wrote about whether an MCP server is like an API.

The tool-use loop: model requests a tool, your code runs it, the result goes back as a tool_result messageClaudestop_reason: tool_useYour handleror MCP serverWeb data APIsearch / scrape / crawltool_result block appended to the same message arrayloop repeats until stop_reason is end_turn
ApproachWhere the work runsBest for
Context stuffingNowhere — you paste text inOne-off analysis, fixed documents
Inline tool definitionsYour backend, per requestPrivate business logic, tight schemas
MCP server (local)A process next to the clientClaude Code, Cursor, developer workflows
MCP server (remote)A hosted service you point atShared capabilities across teams and apps

Feeding Claude live web data without writing a scraper

The most common reason a Claude integration underperforms is not the prompt — it is that the model has no current facts. Two patterns fix that. The explicit one: fetch first, then prompt. Our Web Scraping API returns a page as clean Markdown, which is far cheaper in tokens than raw HTML with its scripts and inline styles.

import os, requests
from anthropic import Anthropic

page = requests.post(
    "https://api.quanticdata.io/v1/scrape",
    headers={"Authorization": f"Bearer {os.environ['QD_API_KEY']}"},
    json={"url": "https://example.com/pricing"},
).json()

markdown = page["data"]["markdown"]
print(page["usage"]["cost_usd"])  # failed calls cost nothing

claude = Anthropic()
msg = claude.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=800,
    system="Return JSON only: [{plan, price, currency, period}]",
    messages=[{"role": "user", "content": markdown}],
)
print(msg.content[0].text)

The agentic pattern is to stop fetching yourself and let the model decide. Registering our web scraping MCP server gives Claude, Claude Code, Cursor or Cline eight tools — search, scrape, map, crawl, crawl_status, batch, batch_status and seo_audit — behind residential proxies, billed per success:

claude mcp add quantumproxies \
  -e QUANTUMPROXIES_API_KEY=qp_live_your_key_here \
  -- npx -y quantumproxies-mcp

Now "find the three cheapest competitors for X and table their plans" becomes a search call, a few scrapes and one synthesis step, with no glue code from you. The same tools are available as plain HTTP if you prefer orchestrating them yourself — see the web data API for AI and the API quickstart for the shared envelope. If your targets need judgement about what is fair to collect, our note on whether AI web scraping is legal is a starting point; none of it is legal advice.

Claude API billing and honest cost math

Anthropic bills per input and output token, per model, with cached input reads discounted and asynchronous batch jobs cheaper than real-time calls. Check the current per-million-token rates on Anthropic's pricing page — they change — and then do the arithmetic on your own volume, because token count is the variable you control.

A worked example. Suppose you analyse 1,000 product pages. As Markdown, a page is roughly 3,000 to 5,000 tokens; as raw HTML it can be five to ten times that. At 4,000 tokens per page you are sending about 4 million input tokens: multiply by your model's input rate to get the model line item. The retrieval side is the small half — 1,000 scrapes at $0.0002 per page is $0.20, or $0.0003 per page via crawl with unfetched pages refunded, and pay-per-success means blocked fetches are not billed. Three levers, in order of impact:

  • Send less. Markdown over HTML, smart content mode over full-page dumps, CSS or AI extraction when you only need four fields.
  • Cache the stable part. Long system prompts, schemas and reference documents are prime prompt-caching candidates when they repeat across calls.
  • Right-size the model and the mode. Classification and extraction rarely need your largest model; overnight backfills belong in the batch API, not a live loop.

Errors you will hit in the first hour

Most early failures are boring and diagnosable from the status code alone:

  • 401 — wrong or revoked key, or the key belongs to a different organisation. Echo the first six characters of the env var to confirm the process actually sees it.
  • 400 with an invalid_request_error — usually a missing max_tokens, a bad model ID, or an assistant message that is not preceded by a user message.
  • 403 or a region message — the Console and API are not available in every country; check Anthropic's supported-countries list before blaming your code.
  • 429 — you crossed a rate or token-per-minute limit for your usage tier. Back off exponentially and respect the retry headers rather than hammering.
  • 529 overloaded — transient capacity. Retry with jitter; do not treat it as a permanent failure.

Wrap every call in a retry with jitter, log usage and the request ID, and put a hard cap on agent loop iterations before you let anything run unattended. That combination — one key, one endpoint, metered tools, capped loops — is the whole discipline of building on Claude reliably.

Sources & further reading

FAQ

Quick answers on how to claude api.

Something else? Ask us →

How do I get a Claude API key?

Create an organisation in the Claude Console at platform.claude.com, add a payment method and credit, then open the API keys section and create a key. The secret is displayed once, so copy it into an environment variable straight away. Anthropic's support docs confirm keys, users and billing are all managed from the Console.

Is there a free Claude API key?

Not as an ongoing tier. New Console organisations may get a small evaluation credit, and the Workbench lets you test prompts without writing code, but production traffic is paid per token. Any third-party site offering a free Claude API key is proxying someone else's account, which risks both your data and their key.

Does my Claude Pro subscription give me an API key?

No. Pro, Max, Team and Enterprise subscriptions cover the Claude apps; API and Console usage is billed separately by Anthropic. You can often sign in to the Console with the same identity, but you still need an organisation with credit before any request to the Messages API will succeed.

What is the Claude API base URL?

The direct endpoint is https://api.anthropic.com/v1, with messages at /v1/messages. Requests need an x-api-key header and an anthropic-version header such as 2023-06-01. If you run Claude through Amazon Bedrock or Google Vertex AI, the base URL and authentication are those platforms' instead.

How do I use the Claude API in Python?

Install the official SDK, export ANTHROPIC_API_KEY, then call client.messages.create() with a model ID, max_tokens, an optional system string and a list of messages. Read text from resp.content[0].text and log resp.usage for token counts. Set stream=True for anything a user waits on.

How does Claude API billing work?

You prepay or attach a card in the Console and are charged per input and output token at model-specific rates, with cached prompt reads and batch jobs priced lower than standard real-time calls. Because history is resent on every turn, long conversations increase input cost, so trim context and set spend alerts early.

Give Claude live web data in one command

QuanticData's MCP server exposes search, scrape, map, crawl, batch and SEO audit as native tools for Claude, Claude Code and Cursor, with residential proxies underneath and pay-per-success billing. Start with $2 of free usage every month, no card required.

Related reading