Your First LLM API Call: Send a Prompt from Code
Move from the chat window to code: install an SDK, keep your API key safe, send a message to an AI model from Python or JavaScript, read the reply and work out what it cost.
On this page 8 sections
Introduction
In Module 1 you wrote prompts in a chat window. Every AI feature you have seen inside real apps — the help bot on a shopping site, the “summarise this” button in an email client, the code suggestions in an editor — works the same way underneath: a program sends a prompt to a model over the internet and does something useful with the reply. In this module you will write that program yourself.
The examples use Claude, Anthropic’s model family, through its official SDKs for Python and JavaScript. Other providers work in a very similar way — a key, a model name, a list of messages, a reply with token counts — so what you learn here transfers directly. Use the tabs above each example to switch between Python and JavaScript; your choice is remembered for the rest of the module.
- What happens during an API call, step by step.
- How to keep an API key out of your code.
- How to send a prompt from Python or JavaScript and read the answer.
- How tokens turn into cost, so you can estimate a bill before it arrives.
How an API Call Works
An API (application programming interface) is a way for one program to ask another for something. When you call an AI model’s API, your code sends an HTTPS request containing your prompt and some settings, the provider runs the model on its servers, and a response comes back containing the generated text plus some information about the request.
You could build that HTTPS request by hand, but an SDK (software development kit) does the fiddly parts for you: it attaches your key, formats the request, retries when the service is briefly overloaded, and turns the response into objects you can use. Install the SDK for your language:
pip install anthropicYour API Key
An API key is a long secret string that identifies your account. Every request made with it is billed to you, so treat it like a password. You create one in the provider’s developer console (for Claude, that is the Claude Console at platform.claude.com), and you should never paste it directly into your source code: code gets committed to Git, shared and pushed to GitHub, where bots scan for leaked keys within minutes.
Instead, store the key in an environment variable — a named value that lives in your terminal session or server, outside your code. Both SDKs automatically read a variable called ANTHROPIC_API_KEY, so your code never has to mention the key at all.
# macOS / Linuxexport ANTHROPIC_API_KEY="your-key-here"
# Windows PowerShell$env:ANTHROPIC_API_KEY="your-key-here"Anything you send to a browser can be read by every visitor, including a key hidden in your JavaScript bundle. In a real web app the browser calls your own backend, and only the backend talks to the AI provider. The AI in Apps guide shows this architecture in detail.
A developer adds this to a React component so the website can call the model directly. What is the serious problem?
const client = new Anthropic({
apiKey: "sk-ant-api03-Xy7...",
dangerouslyAllowBrowser: true,
});Making the Call
Here is a complete program. It creates a client (which picks up your key from the environment), sends one message, and prints the answer. Save it as a file and run it with python first_call.py or node first-call.mjs — the .mjs extension lets Node use import and top-level await.
# first_call.pyimport anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
response = client.messages.create( model="claude-opus-5-5", max_tokens=16000, system="You are a friendly tutor. Answer in at most three sentences.", messages=[ {"role": "user", "content": "What is an API, in plain English?"}, ],)
# The reply is a list of content blocks; the answer is in the "text" blocks.answer = "".join(block.text for block in response.content if block.type == "text")print(answer)Each setting has a job. model picks which model runs — providers offer several sizes, from fast and cheap to slower and more capable, and model names change as new versions ship, so check the provider’s model list. max_tokens is a safety ceiling on how long the reply can get, not a target; modern models may also spend some of it thinking before they answer, so do not set it too low. system holds standing instructions — the role and rules from Module 1 — and messages holds the conversation itself.
Reading the Response
The response is more than a string. Printed as JSON, a simplified version looks like this:
{ "id": "msg_01AbC...", "model": "claude-opus-5-5", "role": "assistant", "content": [ { "type": "text", "text": "An API is a menu of requests one program can make to another..." } ], "stop_reason": "end_turn", "usage": { "input_tokens": 33, "output_tokens": 61 }}content is a list because a reply can contain several blocks of different types — for example a thinking block where the model reasoned before answering, followed by the text block with the answer. That is why the example code collects the text blocks instead of assuming the first block is the answer. stop_reason tells you why the model stopped:
end_turn— the model finished its answer normally.max_tokens— the reply hit your ceiling and was cut off; raisemax_tokensor ask for a shorter answer.refusal— the model declined the request; show the user a polite message instead of an empty reply.
Your app shows answers that stop mid-sentence. You log the response and see "stop_reason": "max_tokens". What is happening?
Tokens and Cost
Models read and write tokens — chunks of text that are often a whole short word or part of a longer one. In English, 100 tokens is very roughly 75 words. Providers bill per million tokens, with output tokens costing more than input tokens because generating text is more work than reading it. The usage part of every response tells you exactly how many of each you used, so you can calculate the cost of any call:
# Add to the end of first_call.py# US dollars per million tokens for claude-opus-5-5 at the time of writing.# Prices change, so check the provider's pricing page.INPUT_PRICE = 4.00OUTPUT_PRICE = 20.00
usage = response.usagecost = (usage.input_tokens * INPUT_PRICE + usage.output_tokens * OUTPUT_PRICE) / 1_000_000print(f"{usage.input_tokens} tokens in, {usage.output_tokens} tokens out = ${cost:.5f}")A single call costs a fraction of a cent, but apps make thousands of calls, and long inputs add up quickly — pasting a 50-page document into every request multiplies your input tokens. Logging usage from day one shows you where the money goes long before the monthly bill does.
A request uses 2,000 input tokens and 500 output tokens. Input costs $4 and output costs $20 per million tokens. What does it cost?
Key Takeaways
- An API call sends your model choice, settings and messages over HTTPS and returns the reply plus usage data.
- Keep API keys in environment variables on a server — never in source code or browser code.
- Read the answer from the
textblocks and always checkstop_reason. - Cost = input tokens × input price + output tokens × output price, per million tokens.
Summary
You have made the jump from chatting with a model to calling one from code. The same request shape — model, system, messages, max_tokens — sits under every AI feature you will build. Each call so far is a one-off question, though: ask a follow-up and the model will have no idea what you said before. In the next lesson you will fix that by building a chat program with memory.