Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Principle:Anthropics Anthropic sdk python API Resource Pattern

From Leeroopedia
Knowledge Sources
Domains SDK Architecture, API_Client
Last Updated 2026-02-15 00:00 GMT

Overview

The API Resource Pattern principle describes how the Anthropic Python SDK organizes API endpoint access through resource classes. API resource classes (SyncAPIResource/AsyncAPIResource) provide method-per-endpoint access to API capabilities. Each resource class encapsulates URL construction, parameter serialization, and response deserialization for a specific API namespace. The Models resource provides list and retrieve methods; the Completions resource provides create with streaming support. This pattern transforms raw HTTP interactions into a fluent, discoverable Python interface.

Theoretical Basis

Resource as Namespace

Each API namespace (messages, completions, models, etc.) is represented by a dedicated resource class. The client object exposes these as attributes:

client = Anthropic()
client.messages.create(...)     # Messages resource
client.completions.create(...)  # Completions resource
client.models.list()            # Models resource
client.models.retrieve(id)      # Models resource

This structure mirrors the REST API's URL hierarchy. The messages resource maps to /v1/messages, models maps to /v1/models, and so on. By aligning the SDK's object model with the API's URL structure, developers can intuit the SDK method from the API documentation and vice versa.

Method-Per-Endpoint Mapping

Within each resource class, individual methods correspond to specific HTTP endpoints:

  • create() maps to POST -- used for generating completions, sending messages, and other write operations.
  • list() maps to GET (collection) -- returns a paginated collection of resources.
  • retrieve() maps to GET (single) -- fetches a specific resource by ID.

This naming convention follows the Active Record / Repository pattern common in API client design, where CRUD-like method names provide a consistent vocabulary across different resource types.

Parameter Serialization with TypedDicts

Each resource method accepts parameters defined as TypedDict classes (e.g., CompletionCreateParams). These TypedDicts serve multiple purposes:

  • Type safety -- Static type checkers can validate that the caller passes the correct parameter types and does not include unknown keys.
  • Documentation -- The TypedDict fields serve as self-documenting parameter specifications.
  • Serialization -- The SDK's transform utilities convert the TypedDict into JSON, resolving aliases (Python snake_case to API camelCase) and stripping NOT_GIVEN sentinel values.

Response Deserialization

Each resource method specifies a cast_to type that the base client uses to deserialize the raw JSON response. For example, Completions.create() specifies cast_to=Completion, instructing the client to parse the response body into a Completion Pydantic model. This ensures that the return type is always a well-typed Python object rather than a raw dictionary.

Sync and Async Resource Duality

Every resource class exists in both synchronous and asynchronous variants:

  • Models (sync) extends SyncAPIResource
  • AsyncModels (async) extends AsyncAPIResource

Both variants share the same method signatures, parameter types, and return types. The only difference is that async methods are coroutines that must be awaited. The base resource classes (SyncAPIResource/AsyncAPIResource) hold a reference to the parent client and delegate HTTP operations to it.

Nested Resource Hierarchies

Resources can contain sub-resources to model hierarchical API namespaces. For example, client.messages.batches is a sub-resource under messages that provides batch-specific operations. This nesting is implemented through resource composition: the parent resource class instantiates child resource classes and exposes them as attributes.

Design Constraints

  • Resource classes do not maintain per-request state. All state (authentication, timeouts, retry policy) is inherited from the parent client.
  • The _client attribute on each resource provides access to the underlying HTTP client for making raw requests.
  • Streaming variants of create() methods accept a stream=True parameter and return Stream or AsyncStream objects rather than the standard response model.
  • Resource methods use keyword-only arguments to prevent positional argument errors, following Python API design best practices.

Related Pages

Implemented By

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment