AI Tools7 min read· May 9, 2026

Claude API Tutorial for Beginners: Your First Script in 10 Minutes

How to use the Claude API in 2026. Get your API key, install the Anthropic library, and write your first Claude-powered script in minutes — beginner-friendly guide.

Claude API Tutorial for Beginners: Your First Script in 10 Minutes

If you just built your first AI script with Python and the OpenAI API, Claude is the obvious next stop. Anthropic's Claude models have a massive context window, strong coding logic, and a reputation for being more careful and detailed than GPT models. The API works almost identically to OpenAI's — so if you followed our Python for AI Beginners guide, you already know 90% of what you need.

This guide covers everything from zero: getting your API key, installing the library, and running your first Claude script. It takes about 10 minutes.


Why Use the Claude API vs. the ChatGPT API?

Both APIs do the same fundamental thing — you send text, you get text back. The differences come down to model strengths:

Claude does better at:

  • Long documents (up to 200K tokens of context — roughly a full novel)
  • Detailed code review and multi-file reasoning
  • Following nuanced instructions precisely
  • Not adding filler or padding to responses

ChatGPT does better at:

  • Multi-modal tasks (images, voice, vision built in)
  • Plugin/tool use ecosystem (more third-party integrations)
  • Faster iteration cycles (more frequent model updates)

For summarizing long reports, reviewing contracts, analyzing codebases, or anything requiring deep careful reading — Claude is often the better pick. For fast general-purpose scripting, both work equally well.


Step 1 — Get Your Claude API Key

  1. Go to console.anthropic.com
  2. Sign up or log in
  3. Click API Keys in the left sidebar
  4. Click Create Key, give it a name, and copy it

New accounts get free credits to start — enough to run hundreds of test scripts before spending anything. Paid usage is charged per token at Anthropic's published rates.


Step 2 — Install the Anthropic Library

Open your terminal and run:

pip install anthropic

That's it. The official Anthropic Python library handles authentication, request formatting, and response parsing. If you're on a Mac and pip isn't found, use pip3.

Verify it installed:

python -c "import anthropic; print('Installed OK')"

Step 3 — Your First Claude Script

Create a file called my_claude_script.py and paste this:

import anthropic

client = anthropic.Anthropic(api_key="YOUR_API_KEY_HERE")

message = client.messages.create(
    model="claude-opus-4-5",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Explain the difference between machine learning and AI in 3 sentences."}
    ]
)

print(message.content[0].text)

Replace YOUR_API_KEY_HERE with your actual key, then run:

python my_claude_script.py

You'll see Claude's response printed in your terminal.

Models to know:

  • claude-opus-4-5 — most capable, best for complex tasks
  • claude-sonnet-4-5 — balanced speed and quality, good for most scripts
  • claude-haiku-3-5 — fastest and cheapest, good for high-volume simple tasks

For everyday scripts, claude-sonnet-4-5 hits the sweet spot between quality and cost.


Step 4 — Make It Interactive

Replace the hardcoded message with user input:

import anthropic

client = anthropic.Anthropic(api_key="YOUR_API_KEY_HERE")

question = input("Ask Claude anything: ")

message = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": question}
    ]
)

print("\nClaude says:")
print(message.content[0].text)

Run it, type any question, and Claude responds. You now have a command-line Claude.


The Killer Feature: Long-Context Document Analysis

The biggest practical advantage of the Claude API over OpenAI's is the 200K token context window. Here's what that unlocks in a script:

import anthropic

client = anthropic.Anthropic(api_key="YOUR_API_KEY_HERE")

# Read a long document from a file
with open("long_report.txt", "r") as f:
    document = f.read()

message = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=2048,
    messages=[
        {
            "role": "user",
            "content": f"Here is a long report:\n\n{document}\n\nSummarize the 5 most important findings and flag any risks."
        }
    ]
)

print(message.content[0].text)

Replace long_report.txt with any text file — a contract, a research paper, a transcript, an annual report. Claude reads the whole thing and answers based on the actual content. No chunking, no embeddings needed for most use cases.

This alone covers a huge range of practical automation that was awkward or expensive with GPT-4.


Practical Scripts You Can Build Today

Code reviewer: Paste a function, ask Claude to spot bugs, explain what each part does, and suggest improvements.

code_to_review = """
def calculate_discount(price, pct):
    return price * pct / 100
"""

message = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    messages=[{
        "role": "user",
        "content": f"Review this Python function. Spot any bugs. Suggest improvements:\n\n{code_to_review}"
    }]
)
print(message.content[0].text)

Batch email summarizer: Loop through a list of email strings and get a one-sentence summary of each.

Contract clause extractor: Feed in a legal document and ask Claude to list all payment terms, deadlines, and cancellation clauses.

YouTube comment analyzer: Paste 50 comments and ask Claude to identify the 3 main complaints, the most-requested features, and general sentiment.

All of these fit in less than 20 lines of Python, work reliably, and would take hours to do by hand.


Claude vs. OpenAI API: Quick Comparison

The syntax is nearly identical, but there are two small differences to know:

Claude API OpenAI API
Import import anthropic from openai import OpenAI
Client anthropic.Anthropic(api_key=...) OpenAI(api_key=...)
Create call client.messages.create(...) client.chat.completions.create(...)
Model param model="claude-sonnet-4-5" model="gpt-4o-mini"
Response text message.content[0].text response.choices[0].message.content

If you've already built something with the OpenAI API, adapting it to Claude is about 5 minutes of find-and-replace. The message format (role/content) is the same.

For running large open-source models you own entirely — without any API costs — check our Llama 4 local install guide and LM Studio setup guide. For high-performance inference on big models without buying a GPU, Ampere Cloud gives you hourly GPU access.


Storing Your API Key Safely

Never hardcode your key inside a script you might share. Use environment variables:

On Mac/Linux (add to ~/.zshrc or ~/.bashrc):

export ANTHROPIC_API_KEY="sk-ant-..."

On Windows (PowerShell):

$env:ANTHROPIC_API_KEY = "sk-ant-..."

Then in your script, just do:

import os
import anthropic

client = anthropic.Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))

Or use a .env file with python-dotenv — the same pattern covered in our Python for AI Beginners guide.


FAQ

Q: Is the Claude API free?
A: New accounts get free credits to experiment. After that, it's pay-per-token. Claude Haiku (the cheapest model) costs a fraction of a cent per typical request. For personal scripts, $10 covers a huge volume of usage.

Q: What's the difference between claude-opus, claude-sonnet, and claude-haiku?
A: Opus is the most capable and slowest. Sonnet is balanced — best for most use cases. Haiku is the fastest and cheapest — good when you're running lots of short requests. If you're unsure, start with Sonnet.

Q: Can I use the Claude API without knowing Python?
A: You need to be able to run a script and change a few values. Our Python for AI Beginners guide covers everything you need in about 10 minutes.

Q: How does Claude's context window affect cost?
A: You're billed for tokens in (your prompt + document) and tokens out (Claude's response). A 200-page PDF is roughly 100K tokens. Sending it every request adds up — batch your documents intelligently if cost is a concern.

Q: Can Claude browse the internet or search in real time?
A: The base API does not have live web access. It works on text you provide. If you need up-to-date information, you'd fetch it yourself (with requests or BeautifulSoup) and pass the text to Claude for analysis.

Q: I'm getting AuthenticationError — what's wrong?
A: Your API key is incorrect, expired, or has no credits. Double-check the key at console.anthropic.com and make sure your account has a payment method or free credits remaining.


You've got the foundation. Combine Claude with Python file reading, web scraping, or a simple loop and you have a tool that handles real work. Start with the document analyzer — paste something you'd normally read manually, see what Claude surfaces, and go from there.

Alex the Engineer

Alex the Engineer

Founder & AI Architect

Senior software engineer turned AI Agency owner. I build massive, scalable AI workflows and share the exact blueprints, financial models, and code I use to generate automated revenue in 2026.

Related Articles