Claude API Code Examples

Working 2026 code examples for the Anthropic API — Python, Node.js, TypeScript, Go.

💥 50p impulse-buy: Power Prompts PDF (first 10 buyers) 30 battle-tested Claude Code prompts · 8-page PDF · paste into CLAUDE.md and never re-type a prompt again · 50p impulse-buy, no commitment

Free tools

Cost Calculator → API Cookbook → Diff Summarizer → Skills Browser →

Visual references

Claude Code hooks lifecycle
Flow of all seven lifecycle hooks in order.
Claude Code commands reference
Built-in slash commands grouped by purpose.

All 147 code examples

Claude API Python Quickstart
Working Python code to call the Claude API in 2026. Install the Anthropic SDK, s…
Claude API Node.js / TypeScript Quickstart
Working Node.js code to call the Claude API in 2026. Install @anthropic-ai/sdk, …
Claude API Streaming in Python
How to stream Claude API responses in Python using the Anthropic SDK. Print toke…
Claude API Streaming in Node.js / TypeScript
Stream Claude API responses in Node.js using @anthropic-ai/sdk. Print tokens as …
Claude API Tool Use in Python
How to use Claude's tool_use (function calling) feature in Python. Define tools,…
Claude API Tool Use in Node.js / TypeScript
Function calling with Claude in Node.js. Define tools in JSON Schema, handle too…
Claude Prompt Caching in Python
How to use Claude's prompt caching feature in Python. Cache large system prompts…
Claude Vision API in Python
Analyze images with Claude in Python. Pass base64 images or URLs, extract text, …
Claude API JSON Structured Output
Get structured JSON from Claude without tool use. Use system prompts + temperatu…
Multi-Turn Conversations with Claude in Python
Build multi-turn chat with Claude in Python. Manage conversation history, contro…
Claude API TypeScript Quickstart
Type-safe Claude API calls in TypeScript. Use @anthropic-ai/sdk with full type i…
Claude API Error Handling in Python
Handle rate limits, overloads, and API errors from the Anthropic SDK in Python. …
Claude Batch API in Python
Use the Anthropic Batch API in Python to process thousands of requests at 50% of…
Claude Extended Thinking in Python
Enable extended thinking for Claude Opus in Python. Get step-by-step reasoning t…
Claude System Prompt Examples
Effective system prompt patterns for Claude. Role personas, output format enforc…
Async Claude API in Python
Run multiple Claude API calls concurrently with asyncio in Python. Use AsyncAnth…
Claude PDF Analysis in Python
Extract text, summarize, and analyze PDFs with the Claude API in Python. Pass PD…
Build a Claude MCP Server in Python
Create a Model Context Protocol (MCP) server in Python that Claude can use as a …
Claude API Environment Setup Guide
Set up your Anthropic API key securely. Store it in .env files, environment vari…
Claude API in Go
Call the Claude API from Go using the official Anthropic Go SDK. Install the pac…
Claude API Rate Limits Guide
Understand Anthropic API rate limits: RPM, TPM, and tier thresholds. How to read…
Claude API vs OpenAI API
Side-by-side comparison of the Claude API (Anthropic) vs OpenAI API: pricing, co…
Claude Haiku API Example
How to use claude-haiku-4-5 via the Anthropic Python SDK. Working code for class…
Claude Agents Python: Agentic Tool-Use Loop
Build an autonomous Claude agent in Python using the Anthropic SDK. Agentic loop…
Claude Structured Output Python: Pydantic & JSON Schema
Extract structured data from Claude in Python using Pydantic models, JSON schema…
Claude Function Calling (Tool Use) in Python
Claude uses 'tool use' instead of 'function calling'. This guide shows how Claud…
Claude Opus 4 API Example (claude-opus-4-7)
Working Python examples for Claude Opus 4 (claude-opus-4-7), Anthropic's most ca…
Claude API in Java
Call the Anthropic Claude API from Java using the official SDK or the Java HttpC…
Claude API in Next.js
Build a streaming Claude AI chatbot in Next.js using the App Router. Route handl…
Claude Computer Use
Call the Claude computer use API to let Claude control a desktop. Full Python ex…
Claude API LangChain Example
Use Claude with LangChain in Python. Install langchain-anthropic, build chains, …
Claude API curl Example
Call the Claude API with curl. Complete 2026 examples: basic message, streaming,…
Claude API FastAPI Example
Build a streaming Claude chatbot backend with FastAPI and the Anthropic SDK. Inc…
Claude API Flask Example
Build a Claude chatbot backend with Flask in Python. Includes streaming with SSE…
Claude API C# / .NET Example
Call the Claude API from C# using HttpClient. Complete working example with asyn…
Claude Files API Python Example
Use the Anthropic Files API in Python to upload documents once and reference the…
Claude API Ruby Example
Working Ruby code for the Claude API using net/http. No official Ruby gem needed…
Claude API PHP Example
Working PHP code for calling the Claude API using cURL and Guzzle. No official P…
Claude API React Chatbot Example
Build a working Claude chatbot in React using the Anthropic SDK via a backend pr…
Claude API Kotlin Example
Working Kotlin code to call the Claude API in 2026. No official SDK — use OkHttp…
RAG with Claude API (Python)
Build a RAG pipeline with the Claude API in Python. Embed documents, store in a …
Claude API Text Summarization (Python)
Working Python code to summarize text, documents, and URLs with the Claude API i…
Claude API Rust Example
Call the Anthropic Claude API from Rust using reqwest and tokio. Complete workin…
Text Classification with Claude API (Python)
Classify text with Claude in Python: single-label, multi-label, zero-shot, and b…
Claude API in AWS Lambda (Python)
Deploy Claude API calls in AWS Lambda with Python. Working handler pattern, stre…
Claude API Django Integration
Working Django code to integrate the Claude API in 2026. View-based chat handler…
Claude Sentiment Analysis with Python
Working Python code to run sentiment analysis with the Claude API in 2026. Zero-…
Claude Structured Data Extraction with Python
Working Python code to extract structured data from unstructured text using the …
Claude API with Express.js
How to call the Claude API from an Express.js backend in 2026. Covers minimal ha…
Text Translation with Claude API — Python
How to translate text between 100+ languages using the Claude API in Python. Cov…
Code Generation with Claude API — Python
How to generate, explain, refactor, and review code using the Claude API in Pyth…
Claude API Swift Example
Call the Anthropic Claude API from Swift using URLSession. Complete working exam…
Claude Content Moderation with Python
Build content moderation systems with the Claude API in Python. Zero-shot modera…
Claude Question Answering with Python
Build Q&A systems with the Claude API in Python. FAQ bots, document Q&A, context…
Build a Chatbot with Claude in Python
Step-by-step guide to building a Python chatbot with the Claude API. Terminal ch…
Text-to-SQL with Claude API in Python
Convert natural language questions to SQL queries using Claude API. Schema injec…
Claude Slack Bot Python: Build an AI Slack Assistant
Build a Slack bot powered by Claude using Python Bolt SDK. Mentions, DMs, thread…
undefined
Step-by-step guide to building a Claude-powered Discord bot in Python using disc…
undefined
Build email automation with Claude and Python. Covers drafting replies, classify…
undefined
Practical strategies to cut Claude API costs: model selection, prompt caching (9…
Claude API in GitHub Actions
Run Claude API calls inside GitHub Actions workflows. Automate code review, PR s…
Testing Claude API Applications in Python
How to unit test and integration test Python apps that call the Claude API. Mock…
Deploy Claude API App to Google Cloud Run
Deploy a Python Flask app that calls the Claude API to Google Cloud Run. Store t…
Claude API Rate Limits & 429 Error Handling in Python
Fix Anthropic API rate limit errors (429, overloaded_error) in Python. Working r…
Claude API Authentication & API Key Management
How to authenticate with the Anthropic Claude API. Set API keys securely in Pyth…
Claude API Timeout & Retry Handling in Python
Fix Claude API timeout errors in Python. Set request timeouts, implement retry l…
Using Claude on AWS Bedrock with Python (boto3)
Call Claude via AWS Bedrock in Python using boto3. Covers bedrock-runtime invoke…
Migrating from OpenAI to Claude API in Python
Step-by-step guide to switching from OpenAI GPT to Anthropic Claude in Python. S…
Claude API Monitoring & Observability in Python
Log every Claude API call, track token usage and latency, set cost alerts, and i…
Dockerize a Claude API Python App
Step-by-step Dockerfile and Docker Compose setup for containerizing Claude API P…
Claude API WebSocket Streaming in Python
Build real-time Claude API streaming over WebSocket in Python (2026). Uses FastA…
Claude API Chatbot with Streamlit
Build a streaming Claude API chatbot with Streamlit in Python (2026). Uses st.se…
Claude Code vs GitHub Copilot: Full 2026 Comparison
Detailed comparison of Claude Code vs GitHub Copilot in 2026. Context window, ag…
Claude API with LlamaIndex: RAG, Agents, and Query Engines
Use the Claude API with LlamaIndex in Python 2026. Build RAG pipelines, query en…
Build a Claude Chatbot with Gradio in Python
Use the Claude API with Gradio in Python 2026. Build a streaming chatbot, image …
Claude API vs Google Gemini API
Side-by-side comparison of Anthropic Claude API vs Google Gemini API: pricing, c…
Claude Sonnet 4.6 vs GPT-4o
Practical comparison of Claude Sonnet 4.6 vs GPT-4o for developers: pricing, con…
Claude API Pricing 2026
Complete Claude API pricing guide for 2026: all model prices, prompt caching sav…
Claude Haiku vs GPT-3.5-Turbo
Claude Haiku vs GPT-3.5-Turbo: price, speed, context window, and code examples i…
Claude API vs Azure OpenAI Service
Claude API vs Azure OpenAI: enterprise pricing, compliance, latency, Python exam…
Best LLM API in 2026
Comprehensive 2026 guide to the best LLM APIs: Claude, GPT-4o, Gemini, Mistral. …
Summarize Git Diffs with Claude AI
Use the Claude API to auto-generate pull request summaries from git diffs. Worki…
Build an LLM Pricing Calculator in Python
Python code to calculate and compare API costs across Claude, GPT-4o, and Gemini…
Claude Extended Thinking API — Python Examples
How to use Claude's extended thinking mode in Python. Working code for streaming…
Claude Code vs Cursor (2026 Comparison)
Detailed comparison of Claude Code and Cursor AI in 2026. Covers pricing, contex…
Claude Code Hooks Tutorial
How to configure Claude Code hooks to run shell commands before or after tool ca…
Claude Code Slash Commands Reference
Complete list of Claude Code slash commands (/help, /clear, /compact, /review, /…
Claude Code Memory System: CLAUDE.md and /memory
How to use CLAUDE.md files and the /memory command in Claude Code to give Claude…
Claude Code Permissions: settings.json and allowedTools
Configure what Claude Code is allowed to do: restrict shell commands, limit file…
Claude Code MCP Server Setup
How to configure MCP (Model Context Protocol) servers in Claude Code — add files…
Claude Code Git Workflow
Use Claude Code for git operations: generate commit messages, review diffs, writ…
Managing Claude Code's Context Window
How Claude Code's context window works, when to use /compact vs /clear, how to s…
Claude Code Multi-Agent Patterns
How to use Claude Code's multi-agent capabilities: spawn subagents for parallel …
Using Claude Code for Code Review
Automate PR review, diff analysis, and pre-commit checks with Claude Code. Inclu…
Claude Code settings.json Reference
Complete reference for Claude Code's settings.json configuration file: all keys,…
Install and Set Up Claude Code (2026)
Step-by-step guide to installing Claude Code on Mac, Windows, and Linux. Include…
Claude Code Projects
How to use Claude Code's Projects feature to organize sessions, share context ac…
Debugging with Claude Code
Use Claude Code to debug errors, analyze stack traces, find root causes, and fix…
Refactoring with Claude Code
How to use Claude Code for large-scale refactoring: rename symbols across a code…
Claude Code vs Aider
Detailed comparison of Claude Code vs Aider: features, pricing, model support, g…
Claude Code Headless and Non-Interactive Mode
How to run Claude Code non-interactively: --print flag, piping input, CI/CD auto…
Claude Code Cost and Pricing (2026)
Complete guide to Claude Code pricing in 2026: Pro vs Max plan, API billing, cos…
Claude Code vs Windsurf: Which AI Coding Tool Wins in 2026?
Detailed comparison of Claude Code and Windsurf (Codeium). Feature table, pricin…
Claude Code Subagents: Running Parallel AI Tasks
How to use Claude Code subagents to run parallel AI tasks. Complete guide with e…
Claude Code IDE Extensions: VS Code and JetBrains Setup
How to install and use Claude Code extensions for VS Code and JetBrains IDEs. St…
Claude Code vs Devin: Which AI Coding Agent Should You Use?
Side-by-side comparison of Claude Code and Devin AI in 2026. Compare autonomy, p…
Claude Code vs Cline: Which Claude-Powered Agent Should You Use?
Claude Code vs Cline (formerly Claude-Dev) — detailed 2026 comparison. Both use …
Claude Code Custom Slash Commands
How to create custom slash commands in Claude Code using CLAUDE.md and the .clau…
Claude Code vs Amazon Q Developer
Detailed comparison of Claude Code vs Amazon Q Developer in 2026. Feature table,…
Claude Code vs Gemini Code Assist
Claude Code vs Google Gemini Code Assist 2026: feature table, context window, pr…
Claude Code Pricing Plans 2026
Full breakdown of Claude Code subscription plans in 2026: Pro ($20/mo), Max ($10…
Best Prompts for Claude Code
Twelve specific, reusable Claude Code prompts that consistently outperform vague…
Claude Code Prompts for Code Review
Specific Claude Code prompt templates for reviewing pull requests, finding secur…
Claude Code Prompts for Refactoring
Refactor with Claude Code without surprise scope creep. Copy-paste prompts for s…
Claude Code System Prompts for Testing
Concrete Claude Code prompts to generate unit tests, find missing test coverage,…
Claude Code Prompt Cheatsheet
One-page cheatsheet of Claude Code prompt patterns: role + constraints + output …
CLAUDE.md Examples & Template
Working CLAUDE.md examples for Python, Node.js, monorepo, and team projects. Cop…
How to Write Claude Code Prompts
Step-by-step guide to writing Claude Code prompts that produce specific, actiona…
Claude Code Prompt Library
A curated library of Claude Code prompts organised by workflow: review, debug, t…
Claude Code Prompts for Debugging
Ten Claude Code prompt templates for debugging: stack-trace autopsy, flaky tests…
Claude Code Prompts for Documentation
Claude Code prompt templates for READMEs, changelogs, API reference, runbooks, a…
Claude Code Plan Mode
How to use Claude Code's /plan command to get a full implementation plan before …
Claude Code Context Compaction
How Claude Code's automatic context compaction works, when it triggers, what it …
Claude Code Git Worktrees
How to use git worktrees with Claude Code to run multiple parallel, isolated cod…
Claude Code Enterprise
How Claude Code Enterprise works for teams: SSO/SAML setup, usage policies, admi…
Claude Code on AWS Bedrock
How to run Claude Code via AWS Bedrock instead of Anthropic's direct API. Covers…
Claude Code in Docker
How to run Claude Code inside Docker containers — for reproducible dev environme…
Claude Code Prompts for Django Projects
Copy-paste Claude Code prompts for Django 5 models, safe migrations, DRF seriali…
Claude Code Prompts for FastAPI Projects
Battle-tested Claude Code prompts for FastAPI routes, Pydantic v2 models, depend…
Claude Code Prompts for Ruby on Rails
Copy-paste Claude Code prompts for Rails 7.1 + Hotwire — models, strong_params c…
Claude Code Prompts for Laravel Projects
Copy-paste Claude Code prompts for Laravel 11 — Eloquent models, FormRequests, q…
Claude Code Prompts for Spring Boot Projects
Copy-paste Claude Code prompts for Spring Boot 3 — JPA entities, controllers, Li…
Claude Code Prompts for Gin Go Projects
Copy-paste Claude Code prompts for Gin handlers, middleware, sqlc queries, and t…
Claude Code Prompts for SvelteKit
Copy-paste Claude Code prompts for SvelteKit 2 — +page.server.ts loaders, form a…
Claude Code Prompts for Nuxt 3
Copy-paste Claude Code prompts for Nuxt 3 — server routes, composables, useFetch…
Claude Code Prompts for Astro Projects
Copy-paste Claude Code prompts for Astro 4 — content collections, framework isla…
Claude Code Prompts for Remix
Copy-paste Claude Code prompts for Remix — loaders, actions, nested routes, Conf…
Claude Code Prompts for Vue 3 Projects
Copy-paste Claude Code prompts for Vue 3 — script setup, composables, Pinia, Vit…
Claude Code Prompts for Angular 18+
Copy-paste Claude Code prompts for Angular 18 — signals, standalone components, …
Claude Code Prompts for Prisma
Copy-paste Claude Code prompts for Prisma — schema design, safe migrations, seed…
Claude Code Prompts for Drizzle ORM
Copy-paste Claude Code prompts for Drizzle ORM — schema definitions, migrations …
Claude Code Prompts for SQLAlchemy 2.0
Copy-paste Claude Code prompts for SQLAlchemy 2.0 async — declarative models wit…
Claude Code Prompts for Supabase Projects
Copy-paste Claude Code prompts for Supabase — RLS policies, edge functions, Auth…
Claude Code Prompts for Tailwind CSS v4
Copy-paste Claude Code prompts for Tailwind v4 — config migration, custom utilit…
Claude Code Prompts for shadcn/ui
Copy-paste Claude Code prompts for shadcn/ui — installing components, customizin…
Claude Code Prompts for Playwright E2E Tests
Copy-paste Claude Code prompts for Playwright — writing stable role-based select…
Claude Code Prompts for pytest
Copy-paste Claude Code prompts for pytest — fixture design, parametrize, factory…

Frequently asked questions

Which Anthropic SDK should I use in Python?
Install `pip install anthropic`. The package name is `anthropic`. Initialize with `client = anthropic.Anthropic()` — it reads `ANTHROPIC_API_KEY` from your environment automatically.
Which Anthropic SDK should I use in Node.js?
Install `npm install @anthropic-ai/sdk`. The package is `@anthropic-ai/sdk`. TypeScript types are included — no separate `@types` package needed.
What is the best Claude model for most applications in 2026?
Claude Sonnet 4.6 is the recommended default — best price/quality balance at $3/M input and $15/M output tokens. Use Haiku 4.5 for high-volume cheap tasks. Reserve Opus 4.7 for complex reasoning where quality is paramount.
Do these code examples cost money to run?
Yes — each API call charges per token. A simple test call costs under $0.001. Get free credits on signup at console.anthropic.com to try the examples at no cost.

Get the Power Prompts pack

Three ways to grab it tonight — pick whichever fits:

£0.50
Full PDF, standard price
30 prompts · 6 categories · 8 pages · CC BY 4.0
Buy at 50p →
£0.30+
Pay what you can
Support free tools · same PDF · name your price from 30p
Pay 30p+ →

All three deliver the same PDF instantly after Stripe checkout. Refund within 7 days, no questions asked — just reply to your Stripe receipt.

Further reading from the indieweb

Independent developers writing about the Anthropic SDK, LLM tooling, and the indie web: