basforge

Search titles, text and the “If it doesn’t work” cases.

    RU
    ManualAIModel APIs

    First API request: a key that stays out of history, curl, the response and the bill

    Get an API key, put it in an environment variable without it landing in shell history, send a curl request to the cheapest model, and read the response: the text, the stop reason and the token bill. You need curl, jq and an account with a card attached or prepaid credit.

    What you end up with

    provider console ──► key sk-ant-… (shown once)
                              │
                 read -rs ──► ANTHROPIC_API_KEY in the current shell, not in history
                              │
    curl ─ POST /v1/messages ─► JSON: content · stop_reason · usage

    OpenAI and Google work the same way: a key in the console, an environment variable, a POST with JSON. The URL, the headers and the response shape differ.

    Steps

    1. Create a key and set a spending limit

      In the Claude Platform console (platform.claude.com), go to API keys and create one. The key is shown once: copy it straight into your password manager. In billing, set a monthly spending limit — $10 is plenty for experiments, and it keeps a bug in a loop from turning into a bill in the hundreds.

      The key gives access to the money on the account. One key per program or per computer: if one leaks, you revoke only that one (Each key and token grants one access).

    2. Put the key in the environment, not in history

      read -rs -p 'API key: ' ANTHROPIC_API_KEY && export ANTHROPIC_API_KEY
      echo ${#ANTHROPIC_API_KEY}
      # the key's length: anything but 0 means the variable is set

      read -s doesn’t echo the input, and the key stays out of ~/.bash_history: only the read command is recorded. echo ${#…} prints the length, not the key — that’s how you check the variable is set. export ANTHROPIC_API_KEY=sk-ant-… typed on the command line leaves the key in history (Keep passwords out of command arguments).

      So you don’t have to type it every time — a file only you can read:

      install -m 600 /dev/null ~/.config/anthropic-key
      read -rs k && printf '%s' "$k" > ~/.config/anthropic-key && unset k
      export ANTHROPIC_API_KEY="$(cat ~/.config/anthropic-key)"

      The key never goes into a repository: it lives in .env, which is in .gitignore (Secrets in Docker stacks, A secret in a commit).

    3. Send the request

      The cheapest model is Haiku 5.5, $0.10 per million input tokens. Reasoning is on by default; for a simple question, set low:

      curl -s 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-haiku-5-5",
          "max_tokens": 1024,
          "output_config": {"effort": "low"},
          "messages": [{"role": "user", "content": "How does docker compose down differ from stop? Two lines."}]
        }' > answer.json

      anthropic-version is the API format version, not the model’s; 2023-06-01 is still current. Save the response to a file: you can parse it as many times as you like and pay for the request once.

    4. Read the response

      jq -r '.content[] | select(.type == "text") | .text' answer.json   # the answer text
      jq -r '.stop_reason' answer.json                                    # end_turn — finished on its own
      jq '.usage' answer.json                                             # the bill in tokens

      The price comes from usage (Tokens): input_tokens × $0.10 + output_tokens × $0.50, divided by a million. A 30-token question and an 80-token answer come to about $0.00004. All of the day’s requests are in the console’s usage section.

      stop_reason: "max_tokens" means the answer was cut off — raise max_tokens. The other values are in A model request, block by block.

    5. A long answer — stream it

      For an answer over a few thousand tokens, add "stream": true: the text arrives in chunks as it’s generated, and the connection doesn’t time out. The response is content_block_delta events with pieces of text; assembling them by hand is awkward, so from here move to an SDK.

    6. Next — an SDK instead of curl

      npm i @anthropic-ai/sdk        # TypeScript and JavaScript
      pip install anthropic          # Python

      The SDK takes the key from ANTHROPIC_API_KEY, retries on 429 and 5xx by itself (twice by default, with a growing pause), assembles the stream into a finished response, and gives you types for every field.

    Error codes

    Code Type What it means Retry?
    400 invalid_request_error a mistake in the request: a field, the model, the format; or no money on the balance no, fix the request
    401 authentication_error the key is wrong or empty no
    402 billing_error a payment problem no
    403 permission_error the key has no access to the model or feature no
    413 request_too_large the request is over the limit, e.g. a PDF over 32 MB no, split it
    429 rate_limit_error the account’s per-minute limit yes, after retry-after
    500 api_error an error on the service side yes
    529 overloaded_error the service is overloaded yes, with a growing pause

    How to check

    Send the same request through count_tokens (Tokens, step 2): its input_tokens should match usage.input_tokens in answer.json. If they match, you know what you’re paying for. The request itself shows up in the console’s usage section.

    If it doesn’t work

    401 and authentication_error — invalid x-api-key

    Cause
    The variable is empty (the key was set in another shell), the key was copied with a space, or it was revoked.
    Fix
    echo ${#ANTHROPIC_API_KEY} prints the length without the key; 0 means the variable isn’t set in this shell. Revoked — create a new one in the console.

    400 with a message about a low credit balance

    Cause
    There’s no money on the account: the API runs on prepaid credit or a card, and a claude.ai subscription doesn’t count.
    Fix
    Top up in the console’s billing section; set a spending limit and optional auto-reload there too.

    429 and rate_limit_error

    Cause
    The account tier’s requests or tokens per minute limit was exceeded; new accounts have low limits.
    Fix
    Wait as many seconds as the retry-after header says and retry; limits grow with the total you’ve paid.

    529 and overloaded_error

    Cause
    The service itself is overloaded, not your account.
    Fix
    Retry after a few seconds with a growing pause; the SDK does this itself, 2 retries by default.

    jq prints null instead of the answer text

    Cause
    The first block in content is thinking, which has no text field.
    Fix
    Select blocks by type: jq -r '.content[] | select(.type == "text") | .text'.