On this page
Lesson 1 of 8
Setup and key handling
What you'll learn
- Install the Anthropic SDK and make your first call
- Handle API keys safely in dev and prod
- Add retries and timeouts you can rely on
Boring on the surface, critical underneath. We will get keys and retries right once so the rest of the course is about ideas, not yak-shaving.
Install the SDK
Start a new TypeScript project and install the official SDK:
mkdir claude-api-lab && cd claude-api-lab
npm init -y
npm install @anthropic-ai/sdk
npm install -D typescript @types/node tsx
npx tsc --init --target es2022 --module nodenext --moduleResolution nodenext
The @anthropic-ai/sdk package handles authentication, retries, streaming, and type safety out of the box. You do not need node-fetch or any HTTP client — the SDK manages the transport layer.
Your first call
Create a file called hello.ts:
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
// SDK reads ANTHROPIC_API_KEY from the environment automatically
const message = await client.messages.create({
model: "claude-sonnet-4-6",
max_tokens: 256,
messages: [{ role: "user", content: "Say hello in one sentence." }],
});
console.log(message.content[0].type === "text" ? message.content[0].text : "");
Run it:
ANTHROPIC_API_KEY=sk-ant-... npx tsx hello.ts
If you see a greeting, you are live. Let us make sure this stays secure.
Safe key handling
Rule 1: Never hardcode a key. The SDK reads ANTHROPIC_API_KEY from the environment automatically, so you never need to pass it in code.
Rule 2: Use .env files locally, never in production. Create a .env file and add it to .gitignore immediately:
echo "ANTHROPIC_API_KEY=sk-ant-your-key-here" > .env
echo ".env" >> .gitignore
Load it at the start of your process using dotenv or your framework's built-in env loader. In production, set the key through your hosting platform's secret management — environment variables on the host, not files in the repo.
Rule 3: Scope keys to environments. Create separate API keys for development, staging, and production in the Anthropic Console. If a dev key leaks, production stays untouched. Rotate the compromised key, do not try to "unshare" it.
Rule 4: Audit access. The Anthropic Console shows which keys are active and when they were last used. Review this monthly. Delete keys that belong to people who left the team.
Retry and timeout configuration
Network calls fail. The Claude API will occasionally return 429 (rate limited), 500, or 529 (overloaded). The SDK retries automatically with exponential backoff, but you should configure it explicitly:
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic({
maxRetries: 3, // default is 2
timeout: 60_000, // 60 seconds, default is 10 minutes
});
The SDK retries on 408, 409, 429, 5xx errors. It does not retry 400 (bad request) or 401 (bad key) — those are your bugs, not transient failures. The backoff starts at about 0.5 seconds and doubles each retry.
For long-running requests (large context, high max_tokens), increase the timeout:
const message = await client.messages.create(
{
model: "claude-opus-4-7",
max_tokens: 8192,
messages: [{ role: "user", content: longDocument }],
},
{ timeout: 120_000 } // per-request override: 2 minutes
);
Error handling in practice
Wrap your calls and handle errors by type:
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic({ maxRetries: 3 });
try {
const message = await client.messages.create({
model: "claude-sonnet-4-6",
max_tokens: 512,
messages: [{ role: "user", content: "Summarize this for me." }],
});
console.log(message.content);
} catch (error) {
if (error instanceof Anthropic.AuthenticationError) {
// 401 — bad key, do not retry
console.error("Invalid API key. Check ANTHROPIC_API_KEY.");
} else if (error instanceof Anthropic.RateLimitError) {
// 429 — SDK already retried, you're truly throttled
console.error("Rate limited after retries. Back off or upgrade tier.");
} else if (error instanceof Anthropic.APIError) {
// Other API errors
console.error(`API error ${error.status}: ${error.message}`);
} else {
throw error; // unexpected, let it crash
}
}
The SDK exports typed error classes for every HTTP status. Use them instead of checking status codes manually — your code reads better and catches the right things.
The model lineup
You will use three models throughout this course:
| Model | ID | Input / Output cost | Context | Best for |
|---|---|---|---|---|
| Opus 4.7 | claude-opus-4-7 | $5 / $25 per MTok | 1M tokens | Complex reasoning, code generation |
| Sonnet 4.6 | claude-sonnet-4-6 | $3 / $15 per MTok | 1M tokens | Balanced quality and speed |
| Haiku 4.5 | claude-haiku-4-5 | $1 / $5 per MTok | 200K tokens | High-volume, low-latency tasks |
Start with Sonnet 4.6 for development. Switch to Haiku 4.5 when you need speed or volume. Reserve Opus 4.7 for tasks that genuinely need its reasoning power.
What's next
Now that your project is wired and your keys are safe, the next lesson — The Messages API — teaches you the request and response shape that every call to Claude follows. You will learn roles, system prompts, multi-turn conversations, and stop reasons.
تبدو مملّة ظاهريًّا، لكنّها حرجة في العمق. سنضبط المفاتيح والإعادة مرّة واحدة حتّى يكون باقي الدّورة عن الأفكار لا عن العمل التّحضيريّ.
تنصيب SDK
أنشئ مشروع TypeScript جديدًا ونصّب SDK الرّسمي:
mkdir claude-api-lab && cd claude-api-lab
npm init -y
npm install @anthropic-ai/sdk
npm install -D typescript @types/node tsx
npx tsc --init --target es2022 --module nodenext --moduleResolution nodenext
حزمة @anthropic-ai/sdk تتولّى المصادقة والإعادة والتّدفّق وسلامة الأنواع. لا تحتاج node-fetch أو أيّ عميل HTTP — SDK يدير طبقة النّقل.
أوّل استدعاء
أنشئ ملفًّا اسمه hello.ts:
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
const message = await client.messages.create({
model: "claude-sonnet-4-6",
max_tokens: 256,
messages: [{ role: "user", content: "قل مرحبًا في جملة واحدة." }],
});
console.log(message.content[0].type === "text" ? message.content[0].text : "");
شغّله:
ANTHROPIC_API_KEY=sk-ant-... npx tsx hello.ts
إذا رأيت تحيّة، أنت متّصل. لنتأكّد أنّ هذا يبقى آمنًا.
إدارة المفاتيح الآمنة
القاعدة 1: لا تكتب المفتاح في الكود مطلقًا. SDK يقرأ ANTHROPIC_API_KEY من البيئة تلقائيًّا.
القاعدة 2: استعمل ملفّات .env محلّيًّا فقط. أنشئ ملفّ .env وأضفه إلى .gitignore فورًا.
القاعدة 3: خصّص مفاتيح لكلّ بيئة. أنشئ مفاتيح منفصلة للتّطوير والتّجهيز والإنتاج. إذا تسرّب مفتاح التّطوير، الإنتاج لا يتأثّر.
القاعدة 4: راجع الوصول. لوحة Anthropic تُظهر المفاتيح النّشطة وآخر استعمال لها. راجعها شهريًّا.
إعداد الإعادة والمهلات
استدعاءات الشّبكة تفشل. واجهة Claude قد تُرجع 429 (حدّ المعدّل) أو 500 أو 529 (مثقلة). SDK يعيد المحاولة تلقائيًّا بتراجع أسّي:
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic({
maxRetries: 3,
timeout: 60_000,
});
SDK يعيد المحاولة على أخطاء 408، 409، 429، 5xx. لا يعيد على 400 (طلب خاطئ) أو 401 (مفتاح خاطئ) — تلك أخطاؤك وليست عابرة.
معالجة الأخطاء عمليًّا
غلّف استدعاءاتك وعالج الأخطاء حسب نوعها باستخدام أصناف الأخطاء المصدّرة من SDK — AuthenticationError و RateLimitError و APIError. هذا أوضح من فحص رموز الحالة يدويًّا.
تشكيلة النّماذج
| النّموذج | المعرّف | تكلفة المدخل / المخرج | السّياق | الأنسب لـ |
|---|---|---|---|---|
| Opus 4.7 | claude-opus-4-7 | $5 / $25 لكلّ مليون رمز | مليون رمز | الاستدلال المعقّد |
| Sonnet 4.6 | claude-sonnet-4-6 | $3 / $15 لكلّ مليون رمز | مليون رمز | التّوازن بين الجودة والسّرعة |
| Haiku 4.5 | claude-haiku-4-5 | $1 / $5 لكلّ مليون رمز | 200 ألف رمز | الحجم الكبير والكمون المنخفض |
ابدأ بـ Sonnet 4.6 للتّطوير. انتقل إلى Haiku 4.5 حين تحتاج سرعة أو حجمًا. احتفظ بـ Opus 4.7 للمهامّ التي تحتاج قدرته الاستدلاليّة فعلًا.
ما التّالي
الآن وقد ربطت مشروعك وأمّنت مفاتيحك، الدّرس القادم — واجهة الرّسائل — يعلّمك شكل الطّلب والاستجابة الذي يتبعه كلّ استدعاء لـ Claude. ستتعلّم الأدوار ومطالبات النّظام والمحادثات المتعدّدة وأسباب التّوقّف.
Try it yourself
Set up a fresh project. Make a call. Then deliberately fail it (bad key, no network) and verify your error path. Ship the retry config.
Reflect
What would happen in your current project if your API key leaked? How quickly could you rotate it?