Hands-On: Build an AI App with Claude on AWS
A step-by-step tutorial: call Claude from Python, deploy it behind AWS Lambda, and keep costs under control.
Key takeaways
- Call Claude with the official Anthropic Python SDK in a few lines; keep API keys out of code.
- Deploy the same logic as an AWS Lambda function, reading the key from AWS Secrets Manager.
- Alternatively call Claude through Amazon Bedrock using your AWS credentials and IAM — no Anthropic key needed.
- Always check the stop reason before reading the response, and set effort to match the task.
- Control cost with the right model tier, prompt caching, batch processing and usage alerts.
Reading about AI is useful; building with it is better. In this tutorial you'll call Claude from Python, turn it into a serverless API on AWS Lambda, and learn the cost and security practices that matter in production. You need Python 3.10+ and an AWS account. Commands assume macOS or Linux.
Step 1 — Your first Claude call
Create an API key in the Claude Console, then install the SDK and export the key as an environment variable. Never paste keys into source code or commit them to git.
python3 -m venv .venv && source .venv/bin/activate
pip install anthropic
export ANTHROPIC_API_KEY="sk-ant-..." # set in your shell, not in code
import anthropic
client = anthropic.Anthropic() # picks up ANTHROPIC_API_KEY automatically
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
output_config={"effort": "medium"},
system="You are a concise technical explainer.",
messages=[{"role": "user", "content": "Explain HBM memory in three sentences."}],
)
if response.stop_reason == "refusal":
print("The request was declined.")
else:
for block in response.content:
if block.type == "text":
print(block.text)
print(response.usage.input_tokens, "in /", response.usage.output_tokens, "out")
A few things to notice:
- The response is a list of content blocks. Besides text, it may contain thinking or tool-use blocks, so check
block.type. effortcontrols how much the model reasons. Uselowfor simple, high-volume tasks andhighor above for hard coding and analysis.usagereports tokens so you can track cost per request.
Step 2 — Store the key in Secrets Manager
In the cloud, keep the API key in AWS Secrets Manager rather than in plain environment variables:
aws secretsmanager create-secret \
--name okindu/anthropic-api-key \
--secret-string "sk-ant-..."
Step 3 — Write the Lambda handler
The handler fetches the key once per container (cold start), then reuses the client across invocations. It uses a server-side fallback so that if the primary model declines a request, the API can retry it on a fallback model within the same call.
# app.py
import json
import boto3
import anthropic
_secret = boto3.client("secretsmanager").get_secret_value(SecretId="okindu/anthropic-api-key")
client = anthropic.Anthropic(api_key=_secret["SecretString"])
def handler(event, context):
body = json.loads(event.get("body") or "{}")
question = (body.get("question") or "").strip()[:4000]
if not question:
return {"statusCode": 400, "body": json.dumps({"error": "question is required"})}
response = client.beta.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
output_config={"effort": "medium"},
betas=["server-side-fallback-2026-07-01"],
fallbacks="default",
system="You answer questions about AI infrastructure clearly and accurately.",
messages=[{"role": "user", "content": question}],
)
if response.stop_reason == "refusal":
return {"statusCode": 200, "body": json.dumps({"answer": None, "declined": True})}
answer = "".join(b.text for b in response.content if b.type == "text")
return {
"statusCode": 200,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({"answer": answer, "model": response.model,
"usage": {"in": response.usage.input_tokens,
"out": response.usage.output_tokens}}),
}
Step 4 — Package and deploy
Create an execution role, bundle the SDK with your code, and create the function. The role needs basic Lambda logging plus permission to read the one secret.
# 1. execution role
aws iam create-role --role-name okindu-ask-role \
--assume-role-policy-document '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}'
aws iam attach-role-policy --role-name okindu-ask-role \
--policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
aws iam put-role-policy --role-name okindu-ask-role --policy-name read-anthropic-secret \
--policy-document '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"secretsmanager:GetSecretValue","Resource":"arn:aws:secretsmanager:*:*:secret:okindu/anthropic-api-key-*"}]}'
# 2. package
mkdir -p build && pip install anthropic -t build/ && cp app.py build/
cd build && zip -qr ../function.zip . && cd ..
# 3. create the function (replace ACCOUNT_ID)
aws lambda create-function --function-name okindu-ask \
--runtime python3.12 --handler app.handler --timeout 120 --memory-size 512 \
--role arn:aws:iam::ACCOUNT_ID:role/okindu-ask-role \
--zip-file fileb://function.zip
# 4. test it
aws lambda invoke --function-name okindu-ask \
--cli-binary-format raw-in-base64-out \
--payload '{"body": "{\"question\": \"What is a KV cache?\"}"}' out.json && cat out.json
Option B — Use Claude through Amazon Bedrock
If your organization prefers to keep everything inside AWS — IAM permissions, AWS billing, private networking — call Claude through Amazon Bedrock instead. There's no Anthropic API key: the SDK's Bedrock client signs requests with your AWS credentials (in Lambda, the execution role). First enable access to the Claude model in the Bedrock console for your region, and grant the function's role permission to invoke it.
from anthropic import AnthropicBedrockMantle
client = AnthropicBedrockMantle(aws_region="us-east-1")
response = client.messages.create(
model="anthropic.claude-opus-5-5", # Bedrock model IDs use the anthropic. prefix
max_tokens=16000,
messages=[{"role": "user", "content": "Summarize the benefits of liquid cooling."}],
)
if response.stop_reason != "refusal":
print("".join(b.text for b in response.content if b.type == "text"))
The request and response shapes are the same as the first-party API, so switching between them is mostly a matter of changing the client. Some newer API features arrive on Anthropic's API before they reach every cloud platform — server-side fallbacks, for example, are not available on Bedrock — so check feature availability for your platform.
Step 5 — Control your costs
| Lever | How |
|---|---|
| Right-size the model | Use Opus for hard reasoning and agents, Sonnet for high-volume production, Haiku for simple classification and extraction. Measure quality on your own examples first. |
| Tune effort | Lower effort for simple tasks reduces tokens and latency. |
| Prompt caching | Put long, stable instructions or documents first and mark them cacheable; cached reads cost a fraction of normal input. |
| Batch API | For non-urgent jobs, batch processing costs about half as much. |
| Limit input | Truncate or validate user input (as the handler does) and cap request rates. |
| Alerts | Set spend limits in the Claude Console and an AWS Budgets alert for Lambda and Bedrock. |
Example: 1,000 requests averaging 1,000 input and 500 output tokens on Claude Opus 5.5 (US$4 / US$20 per million input / output tokens at the time of writing) is 1M input tokens ($4) plus 0.5M output tokens ($10) — about $14. The same traffic on Claude Haiku 5.5 would cost well under $1, which is why model choice matters for high-volume features.
Step 6 — Security checklist
- Keys live in Secrets Manager (or use Bedrock with IAM roles) — never in code, chat messages or git history.
- If a key is ever exposed, revoke it immediately and create a new one.
- Use least-privilege IAM: the function can read exactly one secret.
- Log request IDs and token usage, but not sensitive user content unless you need it and have a retention policy.
- Treat model output as untrusted when it feeds into other systems — validate before executing or storing it.
Where to go next
- Add tools and turn it into an agent: AI Agents in Production.
- Answer questions over your own documents: RAG and Vector Search.
- Connect to existing systems with MCP servers.