Snipepy uses several well-known software design patterns working together.
The Snipepy class is the Facade: a single entry point that hides the HTTP session, authentication, and service wiring from the caller. Callers never instantiate services directly; they call Snipepy.from_env() and use the resulting object.
Each SnipeIT resource group (assets, users, licenses, …) is encapsulated in a Service Object: a stateless class responsible for all operations on that resource. Service objects hold behaviour, not data: checkout() lives on AssetsService, not on the Asset model.
Snipepy.from_env() and Config.from_env() are Factory Methods. They centralise the object-creation logic (reading env vars, validating config, wiring dependencies) so callers never call __init__ with raw arguments.
HttpClientProtocol is a typing.Protocol: Python's mechanism for structural subtyping. Service classes depend on this protocol rather than on the concrete HttpClient. Any object that satisfies the protocol's method signatures can be used in its place, which is how unit tests inject mock HTTP clients without subclassing.
Services in Snipepy are created on first access via @cached_property. This avoids allocating all 19 service objects when only one is needed, while still guaranteeing that the same service instance is returned on repeated access.
Snipepy is designed to conform to all five SOLID principles. Every contribution must maintain this conformance.
Each class has exactly one reason to change:
| Class | Single responsibility |
|---|---|
Config |
Read and validate connection parameters from the environment |
HttpClient |
Translate Python method calls into HTTP requests and surface errors |
*Service |
Provide operations for one SnipeIT resource group |
Asset, User, … |
Hold validated response data: nothing else |
Snipepy |
Wire config, HTTP client, and services; expose them as one object |
No class does two jobs. If you find yourself adding HTTP calls to a model, or configuration logic to a service, it is a SRP violation.
Code is open for extension, closed for modification.
The HTTP error mapping in _http_client.py demonstrates this:
_STATUS_EXCEPTIONS: dict[int, tuple[type[SnipepyError], str]] = {
HTTP_401_UNAUTHORIZED: (SnipepyAuthError, "Unauthorized"),
HTTP_403_FORBIDDEN: (SnipepyForbiddenError, "Forbidden"),
HTTP_404_NOT_FOUND: (SnipepyNotFoundError, "Not found"),
HTTP_409_CONFLICT: (SnipepyConflictError, "Conflict"),
}To support a new HTTP status code, add one entry to the dict: no branching logic changes. The _raise_for_status() method remains untouched.
Any object that satisfies HttpClientProtocol can replace HttpClient without breaking service classes. The mock objects used in unit tests are substituted in exactly this way: services call .get(), .post(), etc. on whatever is injected, and they cannot tell the difference.
HttpClientProtocol defines only the methods that service classes actually call (get, post, put, patch, delete, upload, post_binary, get_binary). Service classes are not forced to depend on configuration, session management, or any other concern of the concrete HttpClient.
High-level modules (service classes) depend on the abstraction (HttpClientProtocol), not on the concrete implementation (HttpClient).
AssetsService → HttpClientProtocol ← HttpClient
(abstraction) (concrete)
Snipepy.__init__ accepts http: HttpClientProtocol | None. When None, it creates an HttpClient; in tests a mock is passed directly. High-level policy (the service) never imports the low-level detail (the HTTP library).
┌──────────────────────────────────────────────┐
│ Snipepy (Facade) │
│ │
│ .assets → AssetsService │
│ .users → UsersService │
│ .licenses → LicensesService │
│ .accessories → AccessoriesService │
│ … (19 services total) │
└──────────────┬───────────────────────────────┘
│ shared
▼
┌──────────────────┐
│ HttpClient │ (requests.Session wrapper)
│ │
│ implements │
│ HttpClientProtocol (Protocol)
└──────────────────┘
SnipeIT's REST API is naturally resource-oriented. The Service Facade mirrors that structure directly:
- One service class per resource group → easy to find where any operation lives.
- The facade (
Snipepy) handles setup once; callers never touch sessions, headers, or base URLs. - Service objects are stateless - they hold no data, only behaviour. This makes them easy to test and reason about.
- Unlike Active Record, models are plain data containers. A
checkout()call lives onAssetsService, not on anAssetobject. This avoids coupling HTTP state to model instances.
- Reads configuration via
Config.from_env(): validatesSNIPEPY_URLandSNIPEPY_API_TOKEN, parses optional variables with documented defaults. - Creates a shared
HttpClientusing the configuration (or accepts an injectedHttpClientProtocolfor testing). - Instantiates all service objects lazily via
@cached_propertyand exposes them as attributes. - Provides the
from_env(dotenv_path=None)factory classmethod.
client = Snipepy.from_env()The Config dataclass (defined in src/snipepy/_config.py) is responsible for reading connection parameters from environment variables and exposing them as a frozen, typed dataclass. It validates required variables and raises ValueError if any are missing.
Dependency injection: Snipepy.__init__ accepts an optional http argument of type HttpClientProtocol. When omitted, a real HttpClient is created. In tests, a mock can be passed directly:
client = Snipepy(config=config, http=mock_http)One class per resource group. Each service:
- Accepts
HttpClientProtocolin__init__(injected by the facade). - Maps Python-friendly method calls to one or more API calls.
- Builds request payloads or query strings internally: callers never pass raw dicts.
- Returns typed Pydantic model instances, never raw dicts.
- Raises
SnipepyErrorsubclasses on failure: never returnsNoneto signal errors.
Common methods across all services:
client.assets.list(limit=50, offset=0, search="laptop") # → AssetList
client.assets.get(124) # → Asset
client.assets.create(asset_tag="T001", status_id=1, model_id=3) # → Asset
client.assets.update(124, name="New Name") # → Asset
client.assets.update_partial(124, notes="repaired") # → Asset (PATCH)
client.assets.delete(124) # → NoneAsset-specific operations:
client.assets.get_by_asset_tag("T00000124")
client.assets.get_by_serial("SN-XYZ")
client.assets.checkout(124, checkout_to_type="user", assigned_user=11)
client.assets.checkout(124, checkout_to_type="location", assigned_location=5)
client.assets.checkin(124, status_id=1, note="Returned")
client.assets.list_files(124)
client.assets.upload_file(124, file_path="/tmp/invoice.pdf")
client.assets.download_file(124, file_id=7)
client.assets.delete_file(124, file_id=7)
client.assets.list_audit_due()
client.assets.list_audit_overdue()
client.assets.audit(124, location_id=3)
client.assets.generate_label(124) # → bytes (PDF/PNG)
client.assets.generate_labels_bulk([124, 125, 126]) # → bytes
client.assets.restore(124)User-specific operations:
client.users.get_me()
client.users.list_assets(user_id=11)
client.users.list_licenses(user_id=11)
client.users.list_accessories(user_id=11)
client.users.list_consumables(user_id=11)
client.users.send_asset_list_email(user_id=11)
client.users.reset_two_factor(user_id=11)
client.users.restore(user_id=11)- Wraps
requests.Session. - Sets
Authorization: Bearer <token>andAccept: application/jsonheaders once in__init__. - Applies timeout and SSL settings from
Config. - Detects HTTP errors and SnipeIT-level
status: errorresponses; raises the appropriateSnipepyErrorsubclass. - Returns raw
dictorbytes: no model conversion at this layer.
Public methods:
| Method | HTTP verb | Use case |
|---|---|---|
get(path, params) |
GET | List and fetch resources |
post(path, json) |
POST | Create resources, trigger actions |
put(path, json) |
PUT | Full update (replace all fields) |
patch(path, json) |
PATCH | Partial update (only supplied fields) |
delete(path) |
DELETE | Remove a resource |
upload(path, files) |
POST multipart | Upload file attachments |
post_binary(path, json, accept) |
POST | Request binary content (labels, PDFs) |
get_binary(path, params, accept) |
GET | Download binary content (backups, PDFs) |
HttpClientProtocol is a typing.Protocol that defines the structural interface used by all service classes. This decouples services from the concrete HttpClient, enabling tests to pass a mock object without subclassing.
None-valued query parameters are stripped before the URL is built, so service methods can pass optional keyword arguments without extra filtering logic.
- Pure Pydantic v2
BaseModeldata classes: no methods that make HTTP calls. - All models use
model_config = ConfigDict(extra="allow")so unknown future SnipeIT fields do not raise validation errors. - Nested objects (
status_label,model,location,assigned_to) are typed sub-models, neverdict[str, Any]. - Shared building blocks live in
src/snipepy/models/_shared.py:NamedObject:{id, name}pair with extra fields allowedDatetimeField: ISO datetime string with model validator accepting plain stringsDateField: ISO date string with model validator accepting plain stringsAvailableActions:{checkout, checkin, clone, restore, update, delete}flagsStatusLabelRef:{id, name, status_type, status_meta}AssignedTo:{id, name, type}for user/asset assignments
SnipepyError
├── SnipepyAuthError # 401: bad or missing token
├── SnipepyForbiddenError # 403: insufficient permissions
├── SnipepyNotFoundError # 404: resource does not exist
├── SnipepyConflictError # 409: duplicate asset tag, etc.
├── SnipepyValidationError # HTTP 200 with status: error (field validation failure)
└── SnipepyServerError # 5xx: SnipeIT server error
client.assets.checkout(124, checkout_to_type="user", assigned_user=11)
│
├─ AssetsService.checkout(124, checkout_to_type="user", assigned_user=11)
│ builds payload: {"checkout_to_type": "user", "assigned_user": 11}
│ filters None values from payload
│
├─ HttpClient.post("/hardware/124/checkout", json=payload)
│ _build_url → "https://snipe.example.com/api/v1/hardware/124/checkout"
│ Session.post(url, json=payload, timeout=30, verify=False)
│ response.raise_for_status()
│ → SnipepyAuthError if 401
│ → SnipepyNotFoundError if 404
│ → SnipepyServerError if 5xx
│ _parse_payload(response)
│ → SnipepyValidationError if payload["status"] == "error"
│ → returns payload["payload"] or full dict
│
└─ AssetsService parses dict → Asset(**response_dict)
returns Asset
src/snipepy/
__init__.py # Public API exports (__all__)
snipepy.py # Snipepy facade class
_config.py # Config frozen dataclass
_http_client.py # HttpClient + HttpClientProtocol + exception hierarchy
_constants.py # HTTP status code constants
_whitelist.py # Vulture allowlist for intentionally public symbols
py.typed # PEP 561 marker
models/
__init__.py
_shared.py # NamedObject, DatetimeField, DateField, etc.
assets.py
users.py
licenses.py
accessories.py
components.py
consumables.py
locations.py
companies.py
categories.py
manufacturers.py
asset_models.py
status_labels.py
departments.py
groups.py
suppliers.py
asset_maintenances.py
custom_fields.py
settings.py
reports.py
services/
__init__.py
assets.py
users.py
licenses.py
accessories.py
components.py
consumables.py
locations.py
companies.py
categories.py
manufacturers.py
asset_models.py
status_labels.py
departments.py
groups.py
suppliers.py
asset_maintenances.py
custom_fields.py
settings.py
reports.py
- No caching: every call hits the API. Caching is the caller's responsibility.
- 429 retry only:
HttpClientretries on HTTP 429 (rate limit) using theRetry-Afterheader. All other transient failures (5xx, connection errors) propagate immediately as typed exceptions. See ADR-0001. - No async: all I/O is synchronous (
requests). This is intentional; sync is simpler and sufficient for the target use cases. - No Active Record: models do not know how to save or update themselves.
- No Repository abstraction: there is no query-builder layer between service objects and the HTTP client.
Snipepy is a general-purpose library designed to work in:
- Standalone scripts: IT automation, bulk imports, report generation, data quality checks.
- Applications: any Python application that needs to read or manage SnipeIT data.
- MCP servers: Snipepy can be used as the data layer inside a Model Context Protocol server, allowing LLM agents to query and manage IT assets. Because Snipepy is synchronous and raises typed exceptions, it integrates cleanly without requiring async infrastructure.
# Example: using Snipepy as the backend of an MCP tool handler
from snipepy import Snipepy
client = Snipepy.from_env()
def handle_get_asset(asset_id: int) -> dict:
asset = client.assets.get(asset_id)
return asset.model_dump()Significant design decisions are recorded as ADRs in docs/adr/.
Read them when you want to understand why the code is shaped the way it is,
not just what it does.
| # | Decision |
|---|---|
| ADR-0001 | HTTP 429 retry with Retry-After backoff in HttpClient |
| ADR-0002 | setuptools-scm for automatic version management |