SSD Nodes Learn Hosting plans →
How to do am Matt ConnorBy Matt Connor

Claude API tutorial: build first app for VPS

Learn how to secure your Claude API key on Ubuntu 24.04 and build a Python log explainer with streaming, typed errors, and token spending control.

Wetin you dey build

Na command-line tool for fresh Ubuntu 24.04 VPS wey you fit pipe error message or part of log enter, then e go return plain-English diagnosis: journalctl -u nginx -n 50 | explain. E fit be around sixty lines of Python, and e go make you practise everything wey real Claude API application need: key wey you store properly, virtualenv, SDK response shapes, streaming, typed exception chain, and systemd unit so e fit run by itself.

I choose this project on purpose. Plenty “first API app” tutorials make you build chatbot wey you no go open again. Log explainer dey useful for server from the first day, and e force you learn the two things beginners dey usually get wrong: how to read response object correctly, and how to control spending. API billing dey based on token, with monthly spending caps for Start, Build, and Scale tiers, plus lower limits wey you fit set yourself. So cost control na part of the design here, no be something to think about later. Na the same discipline wey matter when you later start running Claude Code for this same VPS inside tmux.

Get API key from Console

API access dey managed for Anthropic Console at platform.claude.com. Sign up, then create key under Settings → API Keys (the docs link go straight to platform.claude.com/settings/keys). Console go ask you to name the key, choose when e go expire, and link am to yourself or service account. Anthropic recommend service account keys for production services and anything wey people share. Console go show the key once. E start with sk-ant-, and you no fit retrieve am again. Copy am immediately, or delete am and issue another one.

About money: as of October 2026, API no get ongoing free tier. Anthropic pricing docs talk say new users receive small free credits to test with. When the credits finish, you need purchased credits, eligible monthly plan credits, or invoicing arrangement to continue making requests. This one separate from claude.ai subscription, and API key no give you the chat app. Pro plan no include API credit, but Max, Ultra, and Team plans get am. As of October 31, 2026, Max get $100 per month and Ultra get $200. Team pools $20 for each Standard seat and $100 for each Premium seat, with $500 maximum. You claim the credit by linking a Console organization from your claude.ai billing settings after seven days on an eligible plan. Unused credit expires at the end of each billing cycle. E no cover interactive Claude Code. E covers claude -p and Claude Agent SDK when you run dem yourself with an API key from the linked Console organization. The details dey for how Max, Ultra, and Team monthly API credits work. If you dey compare subscription with API, that trade-off na separate topic: which Claude plan you actually need.

Create the key with scope for only one project's or server's workspace. When key leak, and if time dey go far enough, one go leak eventually. You want revoke am without breaking every other thing wey you own.

Key dey out of .bashrc

The first instinct na export ANTHROPIC_API_KEY=sk-ant-... for ~/.bashrc. No do am. Three different problems dey:

  • Every process dey inherit am. Environment variable wey you export for your login shell go pass to everything wey you start: the web app, the crash reporter wey helpfully dumps its environment into bug report, and the phpinfo() page wey person leave enabled. The key exposure surface become “everything wey this user ever run.”
  • Typing am dey enter ~/.bash_history. If you run the export by hand once, your key go sit for plaintext file forever, and e go sync into every backup of your home directory.
  • E no dey there when systemd need am. Services no read your .bashrc. So with the Python SDK wey this guide use, missing key plus no alternative credentials go produce local TypeError containing Could not resolve authentication method. before e send any HTTP request.

Dedicated environment file with 600 permissions go keep the key out of your login shell exported environment and load am only for the process wey need am:

sudo mkdir -p /opt/explain
sudo install -m 600 -o root -g root /dev/null /etc/claude-explain.env
IFS= read -r -s -p 'Claude API key: ' explain_api_key
printf '\n'
printf 'ANTHROPIC_API_KEY=%s\n' "$explain_api_key" | sudo tee /etc/claude-explain.env >/dev/null
unset explain_api_key

Use tee from a printf instead of editor if you want keep the key out of editor swap files. Anyhow, verify with ls -l /etc/claude-explain.env say e reads -rw------- and root own am. Interactive shells get the key per invocation through a wrapper (below), while systemd get am through EnvironmentFile=. Root reads the file before e drop privileges, so the service user no need read access to am. The prompt above keep the key out of shell history, code, git, and command-line arguments. But the running process still receive am for its environment.

Install SDK inside one venv

Ubuntu 24.04 dey release Python 3.12 with PEP 668 enforcement, so bare pip install anthropic against system interpreter go fail with error: externally-managed-environment. Na OS dey work as e suppose; use virtualenv:

sudo apt update && sudo apt install -y python3-venv
sudo python3 -m venv /opt/explain/venv
sudo /opt/explain/venv/bin/pip install anthropic

You no need activation ceremony for server: if you call /opt/explain/venv/bin/python directly, e go always use the packages wey dey inside venv.

First call, and how to read the response correctly

import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment

response = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=1000,
    messages=[{"role": "user", "content": "Explain what a systemd unit file is in three sentences."}],
)

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

Two things for those twelve lines carry most of the API mental model. First, anthropic.Anthropic() without arguments dey read the key from the environment; never pass am as string literal. Second, response.content na list of content blocks, no be string. If you print am directly, you go see the classic first-timer output:

[TextBlock(citations=None, text='A systemd unit file is...', type='text')]

No be bug; na the object's repr. Responses fit contain different block types (text, tool calls, thinking), so iterate through am and check block.type == "text" before you touch .text. For Opus 5.5, this matter from the very first call: thinking dey always on. So unless the model skip thinking for simple request, the list go start with thinking block wey thinking field empty by default, and response.content[0].text no be your answer. Wire that loop in from day one, and one whole class of "e print garbage" confusion no go happen.

Use the exact model ID claude-opus-5-5. From the 4.6 generation, model IDs no get dates, and the dateless ID na the pinned snapshot. So no follow the habit (or old blog post) wey tell you to add date suffix to current model; that one go produce a 404, as we explain below. Older models work the other way: Haiku 4.5 canonical ID na the dated claude-haiku-4-5-20251001.

Di actual tool: make we explain am

Na be the full program be this. E dey take stdin enter, e dey stream diagnosis come out, and e handle errors:

#!/usr/bin/env python3
"""explain: pipe an error or log excerpt in, get a diagnosis out."""
import sys
import anthropic

MODEL = "claude-opus-5-5"

def main() -> int:
    text = sys.stdin.read().strip()
    if not text:
        print("usage: journalctl -u nginx -n 50 | explain", file=sys.stderr)
        return 1

    client = anthropic.Anthropic()
    try:
        with client.messages.stream(
            model=MODEL,
            max_tokens=4096,
            system=(
                "You are a senior Linux sysadmin. The user pipes you server "
                "logs or error output. Name the most likely cause outright, "
                "then give the commands to confirm and fix it. Be terse."
            ),
            messages=[{"role": "user", "content": text}],
        ) as stream:
            for chunk in stream.text_stream:
                print(chunk, end="", flush=True)
        print()
    except anthropic.RateLimitError as e:
        retry_after = e.response.headers.get("retry-after")
        if retry_after is not None:
            print(f"rate limited; retry in {retry_after}s", file=sys.stderr)
        else:
            print(f"API limit reached: {e.message}", file=sys.stderr)
        return 2
    except anthropic.APIStatusError as e:
        print(f"API error {e.status_code}: {e.message}", file=sys.stderr)
        return 2
    except anthropic.APIConnectionError:
        print("network error reaching the API", file=sys.stderr)
        return 2
    return 0

if __name__ == "__main__":
    sys.exit(main())

Save am as /opt/explain/explain.py, then add wrapper wey go load the key for interactive use:

sudo tee /usr/local/bin/explain >/dev/null <<'EOF'
#!/bin/sh
set -a; . /etc/claude-explain.env; set +a
exec /opt/explain/venv/bin/python /opt/explain/explain.py "$@"
EOF
sudo chmod 755 /usr/local/bin/explain

(The wrapper need run through sudo, or the env file need get group wey your admin user belong to. Choose one deliberately instead of loosening the file permission to 644.)

Why streaming. client.messages.stream dey print tokens as dem dey arrive instead of staying silent until the full generation finish. E also avoid HTTP timeouts for long outputs. The SDK go actually reject very large max_tokens values for non-streaming calls for this same reason. text_stream dey return only the answer text. With the default thinking display for Opus 5.5, no thinking text dey stream at all, so the output stay clean. If you need the assembled object afterwards, call stream.get_final_message() inside the with block.

Why that exception order. The SDK dey raise typed exceptions, from the most specific one first. RateLimitError na 429. When e carry retry-after header, the header tell you how long to wait. But tier spend-cap 429 no get that header. APIStatusError cover other non-2xx responses. Check e.status_code >= 500 for server-side problems. APIConnectionError mean say the request never receive any response at all. Before you build retry loop, remember say the SDK already retries 429 and 5xx errors by itself. E retry twice by default with exponential backoff (max_retries for the client). By the time your except run, the retries don finish. So for CLI, the correct thing na to report the error and exit, not to sleep and keep hammering.

Kontrol cost

Dis one deserve im own section because Start, Build, and Scale tiers get built-in monthly spend caps, but dem caps no replace setting budget for dis tool, and every mistake for here dey add up silently.

max_tokens na your output-token ceiling for each call. Dem bill input separately, so total request cost also depend on input size. Output tokens cost pass input tokens, and for Opus 5.5 dem cost five times the input price. max_tokens na hard cap for how many tokens model fit produce. Runaway prompt no fit cost more output than wetin you allow. For 5.5 models, dat cap include thinking too: thinking tokens count toward max_tokens and dem bill as output, even though dem no return the thinking text to you. Set the size based on the job: 4,096 give terse log diagnosis enough space for the thinking wey come before am; classification task need much less. If response stop early with stop_reason: "max_tokens", you set am too low. Raise am consciously, or reduce effort setting so model go think less, instead of using huge value by default.

Count before you send. Input cost money too, and logs dey bulky. The API get counting endpoint wey free to use, although e get separate rate limits from message creation:

count = client.messages.count_tokens(
    model="claude-opus-5-5",
    messages=[{"role": "user", "content": big_log_text}],
)
print(count.input_tokens)

Use am to stop accidental piping of 2 GB log through the tool, and pass the model wey you really go call. Claude 4.7 and later models use newer tokenizer wey produce roughly 30% more tokens for the same text than older Claude models. No use tiktoken for dis, because na OpenAI tokenizer, no be Claude own. Its counts no go match wetin dem bill you for.

Choose model based on task, no be loyalty. As of October 2026, Opus 5.5 (claude-opus-5-5) cost $4 per million input tokens and $20 per million output tokens. Haiku 5.5 (claude-haiku-5-5) cost $0.10/$0.50 for prompts up to 100,000 tokens, and $0.50/$2.50 above dat, with 1M context. Sonnet 5.5 (claude-sonnet-5-5) dey between dem at $2/$10. For example, 2,000-token log excerpt with 500-token answer cost about $0.018 on Opus and $0.00045 on Haiku, plus any thinking wey model do, because dem bill am as output. Start with Opus while you dey judge output quality. Then try the same prompts with Haiku. For high-volume, simple transformations, result often no different, while per-token price dey about one-fortieth. Confirm current figures for pricing page before you hard-code any of dis into budget.

Use Batches for anything wey fit wait. Batches API process requests asynchronously at 50% of standard prices, and most batches complete within one hour. Nightly digests, backfills, bulk classification, and anything wey no get person waiting for am belong there.

Use prompt caching for repeated context. If every call dey send the same big system prompt or runbook again, mark am cacheable:

response = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=1000,
    system=[{
        "type": "text",
        "text": RUNBOOK_TEXT,  # the same 30K tokens on every call
        "cache_control": {"type": "ephemeral"},
    }],
    messages=[{"role": "user", "content": question}],
)
print(response.usage.cache_read_input_tokens)  # non-zero from the second call on

Cache writes cost 1.25x the input price with 5-minute TTL. Cache reads cost 0.05x on Opus 5.5 and Sonnet 5.5, and 0.1x on most other models. So the second call inside the window don already pay for the first one. Two things fit cause problem. The cached prefix must reach per-model minimum of 512 tokens on Opus 5.5. So very short system prompt fit fail to cache without any clear error. Also, if cache_read_input_tokens remain zero across identical calls, check whether dem happen inside cache lifetime and whether prefix and caching configuration remain identical. Timestamp na the usual cause.

Remember wetin count as input. System prompts, tool definitions, and, for multi-turn conversations, the complete history wey you resend for every turn all count as input tokens and dem bill for dem. Chat loop wey never trim history dey increase cost quadratically. E good make you understand the complete accounting before you build any conversational system: how Claude token usage and billing really dey add up.

Run am under systemd

The benefit wey environment-file discipline dey give you: one timer wey dey summarize yesterday errors every morning.

# /etc/systemd/system/log-digest.service
[Unit]
Description=Daily error-log digest via the Claude API

[Service]
Type=oneshot
User=explain
Group=systemd-journal
EnvironmentFile=/etc/claude-explain.env
ExecStart=/bin/sh -c 'journalctl -p err --since yesterday --until today | /opt/explain/venv/bin/python /opt/explain/explain.py >> /var/log/log-digest.txt'
# /etc/systemd/system/log-digest.timer
[Unit]
Description=Run the log digest every morning

[Timer]
OnCalendar=06:15
Persistent=true

[Install]
WantedBy=timers.target
sudo useradd -r -s /usr/sbin/nologin explain
sudo touch /var/log/log-digest.txt && sudo chown explain /var/log/log-digest.txt
sudo systemctl daemon-reload
sudo systemctl enable --now log-digest.timer
sudo systemctl start log-digest.service   # test it once, right now

Notice wetin EnvironmentFile= dey help you do: systemd reads the root-owned, mode-600 file before e drop to the unprivileged explain user, so the process get the variable while the user no fit read the key file. The systemd-journal group dey grant log access. Test am with manual systemctl start and read journalctl -u log-digest.service; no wait reach 06:15 before you discover typo. When this pattern pass wetin shell pipeline fit handle, this same key-in-env-file approach fit enter Claude-powered n8n workflows directly for the same box.

Failure modes, and the strings wey you go see

401 for key wey dey work. The exception message na:

anthropic.AuthenticationError: Error code: 401 - {'type': 'error', 'error': {'type': 'authentication_error', 'message': 'invalid x-api-key'}, 'request_id': 'req_011CSHoEeqs5C35K2UUqR7Fy'}

If the key dey work for your shell but the service dey return 401, check which credential the service actually receive; missing key without alternative credentials go produce local TypeError wey contain Could not resolve authentication method., so check whether EnvironmentFile= dey point to the correct path. Other causes fit be literal quote characters wey enter the key value by mistake (ordinary ANTHROPIC_API_KEY="sk-ant-..." quoting dey remove dem for both systemd and shell), extra characters, key wey you revoke for Console last week, or key wey don reach the expiration date wey you choose when you create am.

404 from model typo. One way this fit happen na to add date suffix to model ID wey no get dated form:

anthropic.NotFoundError: Error code: 404 - {'type': 'error', 'error': {'type': 'not_found_error', 'message': 'model: claude-opus-5-5-20260922'}, 'request_id': 'req_011CSJqymAvNw4bT3qmDdMbA'}

Current-generation IDs dey exactly as dem write am, claude-opus-5-5, claude-sonnet-5-5, claude-haiku-5-5, claude-fable-5-1. Models from before the 4.6 generation na the exception: claude-haiku-4-5 na convenience alias for the dated ID claude-haiku-4-5-20251001, and both forms dey work. Copy IDs from the models documentation; no rely on memory or old tutorial.

429 rate_limit_error. The error type string na rate_limit_error; when response carry retry-after header, e show the seconds wey you suppose wait. The SDK don already retry twice with backoff before you see the exception, so persistent rate-limit 429s mean say you need batch the work or spread am out; no tighten the retry loop. Tier monthly spend-cap 429 no get retry-after header and e include error.details.error_code: "enforced_spend_limit_reached"; usage go pause until 00:00 UTC for the first day of the next month, unless your cap increase before then.

E dey print the object, no be the text. Output go look like [TextBlock(citations=None, text='...', type='text')]. You print response.content instead of iterating blocks and reading .text from the ones wey block.type == "text". Every SDK example above do am correctly; copy the loop.

error: externally-managed-environment. You run pip install against Ubuntu 24.04 system Python. Use the venv; never use --break-system-packages for server wey matter to you.

Answers wey cut short. response.stop_reason == "max_tokens" mean say the model reach your output cap halfway through the thought. This one dey work as designed; increase the cap deliberately, and remember say for the 5.5 models, thinking dey use the same cap.

After your first app don work, build an AI agent with Claude go turn those same API calls into an agent wey dey use tools.

FAQ

How much does the Claude API cost to try?

E genuinely cheap for tool like this. As of October 2026, Opus 5.5 cost $4 for every million input tokens and $20 for every million output tokens. So, normal log diagnosis wey get a few thousand input tokens and a few hundred output tokens go cost around two cents before thinking tokens, because dem dey bill am as output. For Haiku 5.5 ($0.10/$0.50), e go cost well below one-tenth of a cent. One month of daily digests cost less than one coffee. The real risk no be the price per request. Na unlimited loops and output caps wey too big. Na why this tool dey make one request and set max_tokens explicitly.

Is there a free tier for the Claude API?

No ongoing free tier dey as of October 2026. Anthropic pricing documentation talk say new users receive small free credits to test the API. Na one-time trial be that. After that, you need purchased credits, eligible monthly plan credits, or an invoicing arrangement. Max, Ultra, and Team subscribers na exception. Their plans include monthly API credits, as we cover above. If your goal na zero marginal cost per request instead of frontier quality, you fit self-host open-weight model with Ollama and pay with RAM instead of tokens.

How do I keep my API key safe on a server?

Never put am for code, never put am for git, never export am from .bashrc, and never type am for shell wey history fit keep am. Put am for root-owned file with 600 permissions. Load am per process: use wrapper script for interactive work and EnvironmentFile= for systemd. Use one key for each server or project, so if key leak, you fit revoke only that key instead of causing wider damage. If the key ever enter paste site or git commit, revoke am for Console immediately. Deleting the commit no go remove the leaked key.

Which Claude model should I start with?

Start with claude-opus-5-5 while you dey check whether the output good enough to build on. This one help you judge the idea with full quality, and for hobby usage, the cost difference na only cents. Once the prompt don settle, run your real inputs again with claude-haiku-5-5. For summarization, classification, and log triage, e often good enough at one-fortieth of the per-token price. Choose Haiku or Sonnet based on measurement, not by default.

Dis article help you?