Your First AI API Call: curl for OpenAI and Anthropic Formats

Blog / Developer tools

Your First AI API Call: curl for OpenAI and Anthropic Formats

Your first AI API call needs just three things: a base URL, an API key, and a model name. Once you have them, a single curl command returns an answer. This article covers where each of the three comes from, then walks through a request in OpenAI format and one in Anthropic format, and ends with a table of common errors.

The base URLs and model names below are placeholders. Use the values from your provider's official documentation. Model names in particular change often, so don't copy old names from someone else's article.

What do you need before calling an API?

  1. Base URL. Official APIs, cloud-provider hosting, and aggregation gateways each have their own address. If you haven't decided which route to take, start with How to choose an AI API access route: official API, cloud hosting, or gateway.
  2. API key. Create it in the provider's console. It is shown only once, so save it right after copying. A key is as sensitive as a password: keep it out of your code repository and out of chat messages. If one leaks, see OpenAI API key leaked: revoke it, check usage, prevent a repeat.
  3. Model name. Look it up in the provider's model list and copy it exactly.

Put the key in an environment variable so it never appears in plain text in your commands:

export API_KEY="paste your key here"

Accounts, payment methods, and supported regions differ from service to service, so read each provider's official terms and supported-regions page before signing up. For the payment and network issues developers in China commonly run into, see Using AI APIs from China in 2026.

How do you send an OpenAI-format request with curl?

The OpenAI format is the most common, and many gateways and Chinese models are compatible with it. The core is a POST to /chat/completions, with the key in the Authorization header.

curl https://<base-url>/v1/chat/completions \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "<model-name>",
    "messages": [
      {"role": "user", "content": "Introduce yourself in one sentence"}
    ]
  }'

OpenAI's official endpoint is https://api.openai.com/v1/chat/completions. The request body fields may change as the official docs are updated, so treat the docs as authoritative.

How do you send an Anthropic-format request with curl?

The Anthropic format differs from the one above in three ways: the path is /v1/messages; the key goes in the x-api-key header; and you must include the anthropic-version header and a max_tokens field in the request body.

curl https://<base-url>/v1/messages \
  -H "x-api-key: $API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "<model-name>",
    "max_tokens": 256,
    "messages": [
      {"role": "user", "content": "Introduce yourself in one sentence"}
    ]
  }'

For the value of anthropic-version, follow what Anthropic's official docs currently say. For a full introduction to Claude, see How to use the Claude API: from getting a key to your first request.

How do you read the response?

A successful call returns JSON. Look at these fields first:

ItemOpenAI formatAnthropic format
Answer textchoices[0].message.contentcontent[0].text
Finish reasonchoices[0].finish_reasonstop_reason
UsageInput and output tokens in usageInput and output tokens in usage

If the finish reason indicates truncation due to length, the answer was cut off by max_tokens or the context limit. Raise the limit or shorten the input and try again. usage is what you are billed on. To see how a single call is priced, read How token billing works.

If raw JSON is hard to read in the terminal, pipe the output to jq:

... | jq '.choices[0].message.content'

How do you troubleshoot errors?

The table below gives the usual meaning of common status codes. For exact error messages, check your provider's docs.

SymptomCommon causeCheck first
401Wrong, expired, or revoked keyWhether the environment variable was actually set (run echo to see if it's empty), and whether there are stray spaces
403No permission, or region or account restrictionThe provider's supported regions and your account status; follow the official guidance
404Wrong path or model nameWhether the URL has an extra or missing /v1, and whether the model name was copied exactly
400Malformed request bodyJSON quoting and required fields (such as max_tokens for Anthropic)
429Requests too fast, or quota exhaustedBalance and rate limits; retry later
5xxServer-side problemThe provider's status page; retry later
Hangs or SSL errorsNetwork, proxy, or TLS handshakecurl SSL_ERROR_SYSCALL: what to do

When you get a 429 or 5xx, don't write an endless loop that hammers the API. For how to back off and set a retry budget, see How to write exponential backoff retries for LLM APIs.

If you suspect the problem is on the server side, check cdnping's OpenAI API status and Anthropic API status, which probe the official API entry points from the edge at fixed intervals. To measure your own network's first-connection and round-trip times to each provider's API, run a test from the cdnping home page.

What if you have no overseas account or overseas credit card?

Official APIs generally require you to register an official account and pay by a supported method. Supported regions and payment methods vary by provider, so go straight to the official documentation. If your account is restricted, use only the official appeal channel and don't try to work around the restriction.

If you just want to get a request working first, an aggregation gateway is another option. AGI Plan is a multi-provider LLM gateway and a commercial partner of cdnping. Its main features:

  • Monthly subscription, paid in RMB, no overseas credit card needed; one subscription can switch between multiple capability groups.
  • Compatible with both the OpenAI and Anthropic API formats, so for both curl commands in this article you just swap in its base URL and key. Get the exact URL from the console.
  • Tools such as Claude Code and Codex only need one base URL changed, and no account with the corresponding official provider.
  • The site states that it is not an officially authorized channel; some models are marked "overseas only", so check the models page for the current list.

For sign-up and setup steps, see the AGI Plan quick start: register with an emailed verification code, pick a plan and create a key, then change one setting. To judge whether it suits you, compare it with How to choose an AI coding tool subscription.

What should you do after your first call works?

  1. Set a spending limit in the provider's dashboard first, so a buggy script can't overspend. For OpenAI, see How to set a spending limit and usage alerts on the OpenAI API.
  2. Replace curl with an SDK or an HTTP library, and add timeouts and retries.
  3. Log the usage of every call; see How to track your AI API usage.

Getting one curl to succeed beats reading all the docs up front. If something fails, work through the table above one row at a time. Most problems come down to three things: the key, the path, and the model name.

Related articles

Keep reading