SDK Requirements

Su Suriya Ravichandran Updated 10 Nov 2026
13 min read ·Lesson 3 of 200

What You Need Before Using the Anthropic SDK

To call Claude from Python, you need a working environment on your computer and access to the Claude API. That means meeting two groups of requirements: technical requirements for your machine, and account requirements for the API.

RequirementWhy it is neededHow to checkCovered in
Python 3.10 or laterThe SDK supports only Python 3.10+python --versionThis lesson
pip (or another package manager)Installs the SDK and its dependenciespython -m pip --versionThis lesson, Lesson 4
A virtual environment (recommended)Isolates project dependenciespython -m venv --helpLesson 4
Internet access to api.anthropic.com over HTTPSEvery SDK call is an HTTPS requestConnectivity check belowThis lesson
A Claude Console accountAPI access, billing, and keys are managed thereSign in at platform.claude.comLesson 6
An API keyAuthenticates your requestsStarts with sk-ant-Lessons 6–7
Billing set upAPI usage is paid per tokenConsole → BillingLesson 6
Basic Python knowledgeFunctions, lists, dicts, exceptions—This lesson

The rest of this lesson explains each requirement: what it is, why it exists, how to check it, and what happens when it is missing.


Python 3.10 or Later

The Requirement

The Anthropic Python SDK requires Python 3.10 or later. Python 3.9 and older are not supported by current releases.

Why a Minimum Version Exists

Python releases are supported for about five years. After that, they stop receiving bug and security fixes and reach end of life (EOL). Library maintainers then drop support for those versions so they can use newer language features and avoid testing against unmaintained interpreters.

That is why the SDK's minimum version rises over time. It also affects which version you should choose for a new project:

Python versionStatus (as of late 2026)Recommendation
3.9 and olderEnd of lifeNot supported by the SDK. Upgrade.
3.10At or past its scheduled end of life (October 2026)Works, but plan to upgrade
3.11Supported (security fixes)Works
3.12, 3.13, 3.14SupportedRecommended for new projects

Note: Python's release and support schedule is published at python.org/downloads. Check it when starting a long-lived project.

How to Check Your Python Version

From a terminal:

# macOS / Linux
python3 --version

# Windows (Python launcher)
py --version

# Any system where "python" points to Python 3
python --version

Example output:

Python 3.13.1

On Windows, the Python launcher can list every installed version:

py --list

You can also check from inside Python. This is useful in scripts that need to verify their own environment:

import sys

print(sys.version)          # Full version string
print(sys.version_info)     # Structured version information

if sys.version_info < (3, 10):
    raise SystemExit("This project requires Python 3.10 or later.")

How the check works: sys.version_info is a tuple-like object, such as (3, 13, 1, 'final', 0). Python compares tuples element by element, so (3, 9, 18) < (3, 10) is True and (3, 13, 1) < (3, 10) is False. Comparing against (3, 10) checks the major and minor version without caring about the patch number.

What Happens on an Older Python

This is a subtle but important behavior. Every package release declares which Python versions it supports, in a field called Requires-Python. pip uses that field when it chooses a version to install.

On an unsupported interpreter, one of two things happens:

  1. pip finds no compatible release and fails with an error like:

    ERROR: Could not find a version that satisfies the requirement anthropic
  2. pip installs an old release that still declared support for your Python version. The installation "succeeds", but you get an outdated SDK. That SDK may not support current models or features, and its behavior may not match the documentation.

The second case is easy to miss. If the current documentation's examples fail on a machine with an old Python, check the versions first:

python --version
python -m pip show anthropic

python vs. python3 vs. py

A computer can have several Python installations, and the command name decides which one runs:

CommandTypical meaning
python3Python 3 on macOS and Linux
pythonPython 3 on Windows and in activated virtual environments. On some older Linux and macOS systems it may be missing or point to Python 2.
pyThe Windows Python launcher. py -3.13 selects a specific version.

Inside an activated virtual environment (Lesson 4), python always refers to that environment's interpreter. That is one reason virtual environments remove so much confusion.


pip: The Package Installer

pip downloads packages from the Python Package Index (PyPI) and installs them together with their dependencies. It is included with modern Python installations.

Check that it works:

python -m pip --version

Example output:

pip 25.2 from /home/user/project/.venv/lib/python3.13/site-packages/pip (python 3.13)

Why python -m pip instead of just pip: the pip command might belong to a different Python installation than the python you run your code with. python -m pip runs pip for that specific interpreter, so the package is installed exactly where your code will look for it. The path in the output confirms which installation pip belongs to.

If pip is missing, Python can usually install it itself:

python -m ensurepip --upgrade

Alternatives to pip, such as uv and Poetry, are also widely used. Lesson 4 shows the installation command for each.


The SDK's Dependencies

The anthropic package depends on other libraries. pip installs them automatically, so you never install them by hand. Two of them are worth knowing because they appear in error messages and documentation:

LibraryRole in the SDK
httpx2The HTTP client that sends requests. It is an API-compatible fork of the popular httpx library.
PydanticDefines the typed response models, such as Message, and provides to_dict() and to_json().

To see the full list of dependencies for your installed version:

python -m pip show anthropic

The Requires: line lists them.

Note: Because the SDK depends on Pydantic and an HTTP library, version conflicts are possible in projects that pin those libraries to old versions. Using a dedicated virtual environment per project (Lesson 4) prevents most of these conflicts.

Optional Extras

Some features need additional dependencies. These are installed only when you request an extra:

ExtraInstall commandNeeded for
bedrockpip install "anthropic[bedrock]"Claude on Amazon Bedrock
vertexpip install "anthropic[vertex]"Claude Models on Google Cloud (Google managed)
google_cloudpip install "anthropic[google_cloud]"Claude Models on Google Cloud (Anthropic managed)
awspip install "anthropic[aws]"Claude Platform on AWS
aiohttppip install "anthropic[aiohttp]"The faster aiohttp backend for the async client

Microsoft Foundry support is included in the base package and needs no extra. For the beginner lessons, the base package is all you need.


Network Access

Every SDK call is an HTTPS request to https://api.anthropic.com on port 443. Your machine must be able to reach that address.

Networks that commonly cause problems:

  • Corporate networks that send all traffic through a proxy server.
  • Firewalls that allow only approved domains.
  • Restricted cloud environments, such as containers or serverless functions without outbound internet access.

When the API cannot be reached, the SDK retries the request and then raises anthropic.APIConnectionError. This is different from an API error: the request never got a response at all.

If you must use a proxy, the SDK can be configured with one through its http_client option. This is shown in the Python SDK documentation's "Configuring the HTTP client" section and covered in the advanced lessons.

The Claude API is also available only in supported countries and regions. Anthropic publishes the list on its supported-regions page.


Account Requirements

The SDK is only a client. To use it, you need access to the service it talks to:

  1. A Claude Console account at platform.claude.com. This is separate from a Claude app account and plan.
  2. Billing configured for your organization. API usage is charged per token, and requests fail if your organization cannot be billed.
  3. An API key, created in the Console, with permission to call the API.

Lesson 6 walks through all three. If any of them is missing, the SDK still installs and imports normally. The failure appears only when you send a request, usually as an authentication or permission error.


Knowledge Prerequisites

This tutorial assumes basic Python knowledge:

TopicUsed for
Variables, strings, lists, dictionariesBuilding messages lists and reading responses
Functions and keyword argumentsEvery SDK call uses keyword arguments
for loops and list comprehensionsReading content blocks
try / exceptHandling API errors
Classes and attributesReading typed response objects (message.usage.output_tokens)
Running scripts from a terminalRunning every example
async / await (later lessons)The asynchronous client, Lessons 71–80

You do not need to know HTTP, REST, or machine learning in advance. The tutorial explains them when they become relevant.


Practical Example: An Environment Check Script

This script checks the technical requirements in one run. It does not send a request to Claude, so it costs nothing. It verifies the Python version, the SDK installation, the presence of an API key, and network access to the API.

Save it as check_environment.py:

"""check_environment.py: verify the requirements for the Anthropic SDK."""

import importlib.util
import os
import socket
import sys

MIN_PYTHON = (3, 10)
API_HOST = "api.anthropic.com"


def check_python() -> bool:
    version = ".".join(map(str, sys.version_info[:3]))
    ok = sys.version_info >= MIN_PYTHON
    status = "OK" if ok else "FAIL (3.10+ required)"
    print(f"[{'+' if ok else '!'}] Python {version}: {status}")
    print(f"    Interpreter: {sys.executable}")
    return ok


def check_sdk() -> bool:
    if importlib.util.find_spec("anthropic") is None:
        print("[!] anthropic SDK: NOT INSTALLED (run: python -m pip install anthropic)")
        return False
    import anthropic

    print(f"[+] anthropic SDK: version {anthropic.__version__}")
    return True


def check_api_key() -> bool:
    key = os.environ.get("ANTHROPIC_API_KEY", "")
    if not key:
        print("[!] ANTHROPIC_API_KEY: NOT SET")
        return False
    if not key.startswith("sk-ant-"):
        print("[!] ANTHROPIC_API_KEY: set, but does not start with 'sk-ant-'")
        return False
    print(f"[+] ANTHROPIC_API_KEY: set ({key[:10]}...{key[-4:]})")
    return True


def check_network() -> bool:
    try:
        with socket.create_connection((API_HOST, 443), timeout=5):
            pass
    except OSError as error:
        print(f"[!] Network: cannot reach {API_HOST}:443 ({error})")
        return False
    print(f"[+] Network: {API_HOST}:443 is reachable")
    return True


def main() -> int:
    results = [check_python(), check_sdk(), check_api_key(), check_network()]
    print()
    if all(results):
        print("All checks passed. You are ready to use the Anthropic SDK.")
        return 0
    print("Some checks failed. Fix the items marked [!] above.")
    return 1


if __name__ == "__main__":
    sys.exit(main())

Run it:

python check_environment.py

Example output on a ready machine:

[+] Python 3.13.1: OK
    Interpreter: /home/user/claude-tutorial/.venv/bin/python
[+] anthropic SDK: version 2.0.0
[+] ANTHROPIC_API_KEY: set (sk-ant-api...x7Qa)
[+] Network: api.anthropic.com:443 is reachable

All checks passed. You are ready to use the Anthropic SDK.

Example output on a new machine:

[+] Python 3.13.1: OK
    Interpreter: /usr/bin/python3
[!] anthropic SDK: NOT INSTALLED (run: python -m pip install anthropic)
[!] ANTHROPIC_API_KEY: NOT SET
[+] Network: api.anthropic.com:443 is reachable

Some checks failed. Fix the items marked [!] above.

How the Script Works

  • check_python() compares sys.version_info with (3, 10). It also prints sys.executable, the full path of the interpreter running the script. That shows immediately whether you are inside your virtual environment (a path containing .venv) or using the system Python.
  • check_sdk() uses importlib.util.find_spec("anthropic") to test whether the package can be found without importing it. A missing package therefore produces a clear message instead of an ImportError traceback. If it exists, the script imports it and prints the version.
  • check_api_key() reads the environment variable and checks the sk-ant- prefix that Claude API keys use. It prints only the first 10 and last 4 characters. Never print a full key, because terminal output ends up in logs, screenshots, and screen shares.
  • check_network() opens a TCP connection to port 443 and closes it immediately. A successful connection proves that DNS resolution and the network path to the API work, without sending an API request or using tokens.
  • main() runs every check, even after one fails, so you see all problems at once. It returns exit code 0 or 1 so other tools can use the result.

Note: This script verifies that a key is present, not that it is valid. Validating a key requires calling the API. Lesson 6 shows a zero-token way to do that with client.models.list().


Common Mistakes

Installing the SDK into One Python and Running Another

What happens: pip install anthropic succeeds, but running the script gives ModuleNotFoundError: No module named 'anthropic'.

Why: the pip command belonged to a different Python installation from the python command that ran the script.

Fix: install with python -m pip install anthropic, using the same python command that runs your code. Better still, use a virtual environment (Lesson 4). Print sys.executable to see which interpreter is actually running.

Using an Unsupported Python Version Without Noticing

What happens: installation works, but examples from the current documentation fail with unexpected TypeErrors or missing attributes.

Why: on an old interpreter, pip silently picked an old SDK release that still supported it.

Fix: upgrade Python to a supported version (3.12+ recommended for new projects), recreate the virtual environment, and reinstall the SDK.

Confusing a Claude App Plan with API Access

What happens: you have a Claude subscription, but API requests fail.

Why: the app and the API are separate products with separate accounts and billing.

Fix: sign in to the Claude Console at platform.claude.com, set up billing, and create an API key (Lesson 6).

Assuming Installation Problems Are Network Problems, or the Reverse

What happens: time spent debugging the wrong layer.

Fix: separate the layers. ModuleNotFoundError is an installation problem. APIConnectionError is a network problem. AuthenticationError is a key problem. The environment check script tests each layer independently.


Best Practices

  • Use a currently supported Python release for new projects (3.12 or later). Do not start new work on a version close to end of life.
  • Always use python -m pip instead of bare pip, so packages go into the interpreter you actually use.
  • Create one virtual environment per project to avoid dependency conflicts with other projects and with the system Python.
  • Record requirements explicitly. Put the minimum Python version in your README or pyproject.toml (requires-python = ">=3.10"), and put the SDK in requirements.txt or pyproject.toml.
  • Run an environment check in new setups. A script like check_environment.py saves time on new machines, servers, and CI pipelines.
  • Check network access early in restricted environments, such as corporate networks, containers, and serverless platforms, before debugging code.

Exercise

  1. Run python --version and python -m pip --version. Confirm that both refer to the same Python installation by comparing the path in pip's output.
  2. Save and run check_environment.py. Which checks fail on your machine?
  3. Modify check_python() to print a warning (not a failure) when the version is 3.10 or 3.11, recommending an upgrade for new projects.
Show a possible solution for step 3
def check_python() -> bool:
    version = ".".join(map(str, sys.version_info[:3]))

    if sys.version_info < MIN_PYTHON:
        print(f"[!] Python {version}: FAIL (3.10+ required)")
        return False

    if sys.version_info < (3, 12):
        print(f"[~] Python {version}: OK, but 3.12+ is recommended for new projects")
    else:
        print(f"[+] Python {version}: OK")

    print(f"    Interpreter: {sys.executable}")
    return True

How it works: the function first rejects unsupported versions. It then uses a second comparison against (3, 12) to separate "supported but aging" from "recommended". The warning still returns True, because Python 3.10 and 3.11 meet the SDK's requirement.

0 Comments

Reviewed before they appear

No comments yet.

Anthropic SDK Using Python
Anthropic SDK Intro Claude API Intro SDK Requirements Install Anthropic SDK Upgrade the SDK Create an API Key Set API Keys Use Environment Variables Import Anthropic Create a Client Send Your First Message Choose a Claude Model Set Max Tokens Read a Response Print Response Text Understand Message Blocks Use System Prompts Send User Messages Set Temperature Handle Stop Reasons Messages API Intro Create Messages Use Message Roles Send Conversation History Continue a Conversation Build a Chat Loop Reset Chat History Use Multiple Turns Inspect Message IDs Read Usage Data Write Clear Prompts Set a System Prompt Add Context to Prompts Use Prompt Templates Add Examples to Prompts Request JSON Output Use XML Tags Control Response Length Improve Prompt Quality Avoid Prompt Injection Read Text Blocks Read Content Blocks Check Stop Reasons Count Input Tokens Count Output Tokens Count Tokens Before Sending Limit Output Tokens Use Stop Sequences Read Request IDs Parse API Responses Streaming Intro Stream Text Output Use Stream Events Use Stream Helpers Get Final Messages Stream Async Responses Handle Stream Errors Build a Live Chat Stream Long Responses Close Streams Safely Build a Chatbot Keep Chat History Manage Chat Sessions Add Chat Memory Build a CLI Chatbot Build a Web Chatbot Use Flask with Claude Use FastAPI with Claude Return JSON from an API Add Chat Error Messages Async SDK Intro Create an Async Client Send Async Messages Use asyncio Run Parallel Requests Stream Async Text Handle Async Errors Set Async Timeouts Close Async Clients Choose Sync or Async Tool Use Intro Define a Tool Create Tool Schemas Send Tools to Claude Read Tool Calls Run Python Tools Return Tool Results Continue After Tool Use Control Tool Choice Handle Tool Errors Use the beta_tool Decorator Create a Tool Runner Add Tool Docstrings Validate Tool Inputs Use Multiple Tools Limit Tool Calls Log Tool Activity Build a Weather Tool Build a Search Tool Build a Calculator Tool Structured Output Intro Request JSON Data Validate JSON Output Use Pydantic Models Handle Invalid JSON Extract Fields from Text Generate Typed Data Use Image URLs Send Base64 Images Read PDFs with Claude Use Output Schemas Build Data Extraction Test Structured Responses Send Image Inputs Upload Files Use File IDs Process Text Files Summarize Documents Extract Table Data Handle File Errors Read Cache Usage Reduce Repeated Input Costs Debug Cache Misses Prompt Caching Intro Enable Prompt Caching Cache System Prompts Cache Long Context Test Cache Performance Use Cache Breakpoints Cache Best Practices Message Batches Intro Create a Message Batch Set Batch IDs Check Batch Status List Message Batches Get Batch Results Process Batch Outputs Handle Failed Batch Items Use Batches for Bulk Tasks Compare Batches and Requests Handle API Errors Handle Rate Limits Retry Failed Requests Set Request Timeouts Handle Network Errors Use Exponential Backoff Build Reliable API Calls Use Extended Thinking Log API Errors Track Request IDs Paginate API Results Set Thinking Budgets Read Thinking Blocks Use Tool Search Use Web Search Tools Use Computer Tools Use Citations Use Token Counting Read Raw Responses Set Custom Headers Use Claude on AWS Bedrock Use Claude on Vertex AI Use Claude on Microsoft Foundry Configure Cloud Credentials Choose a Cloud Provider Compare API Integrations Configure Provider Clients Handle Cloud Errors Use Cloud SDK Extras Deploy Cloud Apps Protect API Keys Use a .env File Ignore Secrets in Git Validate User Input Reduce Prompt Injection Limit Tool Permissions Avoid Unsafe Tool Calls Sanitize Tool Results Set Usage Limits Review Security Logs Test SDK Functions Mock API Responses Test Error Handling Test Streaming Code Measure Token Usage Track API Costs Configure Logging Deploy with Docker Deploy a FastAPI App Monitor Production Apps Build a Claude Chatbot Build a Text Summarizer Build a Code Explainer Build a JSON Extractor Build a PDF Assistant Build a Streaming Chat App Build a Tool-Calling Agent Build a Batch Processor Build a Research Assistant Build a Claude API Dashboard
Ask about this post
AI Ask about this post

Ask questions about SDK Requirements and get answers drawn from it.

Signed-in readers only.