Wood Wide Python SDK
The Wood Wide Python SDK provides typed access to the Wood Wide API from Python 3.9 or later. It includes:
- High-level workflow helpers for dataset ingestion, model training, batch inference, result retrieval, and data connection imports.
- Typed resource clients for direct access to every documented API endpoint.
- Synchronous and asynchronous interfaces powered by httpx.
The resource clients and request and response models are generated with Stainless. The workflow helpers compose those generated methods into common multi-step operations.
Documentation
Installation
# install from PyPI
pip install woodwide
Quick start
Set the WOODWIDE_API_KEY environment variable, then create a client. Passing api_key explicitly is also supported.
from woodwide import WoodWide
client = WoodWide()
jobs = client.jobs.list()
print(jobs.items)
For local development, python-dotenv can load WOODWIDE_API_KEY from a .env file. Do not commit API keys to source control.
High-level workflow helpers
High-level workflow helpers compose common API operations. Helpers that monitor jobs return only after the job succeeds; they raise RuntimeError if it fails, is rejected, or is canceled, and TimeoutError if it exceeds the configured timeout. Transfer and result-iteration helpers expose HTTP and argument errors appropriate to their operations.
All helpers can be imported directly from woodwide:
| Workflow | Synchronous helper | Asynchronous helper |
|---|---|---|
| Wait for any job | wait_for_job |
async_wait_for_job |
| Wait for training | wait_for_training |
async_wait_for_training |
| Upload and ingest a dataset | ingest_dataset |
async_ingest_dataset |
| Ingest a large dataset by signed URL | ingest_large_dataset |
async_ingest_large_dataset |
| Train a model | train_model |
async_train_model |
| Run batch inference | infer_batch_and_wait |
async_infer_batch_and_wait |
| Download job results | download_job_results |
async_download_job_results |
| Iterate through result rows | iter_result_rows |
async_iter_result_rows |
| Import connection data | import_connection_data |
async_import_connection_data |
Ingest, train, and infer
The following example runs a complete synchronous workflow. Each operation waits for its job to succeed before returning.
from pathlib import Path
from woodwide import WoodWide
from woodwide import download_job_results
from woodwide import infer_batch_and_wait
from woodwide import ingest_dataset
from woodwide import train_model
client = WoodWide()
dataset = ingest_dataset(
client,
file=Path("customers.csv"),
dataset_name="customers",
)
model = train_model(
client,
model_type="anomaly",
dataset_id=dataset.submission.id,
)
inference = infer_batch_and_wait(
client,
model.submission.id,
dataset_id=dataset.submission.id,
output_type="parquet",
)
download_job_results(
client,
inference.job.id,
"customer_anomalies.parquet",
)
Workflow results retain both the initial API response and the completed job. For example, TrainModelResult.submission is the original ModelTrainResponse, while TrainModelResult.job is the successful JobDetail returned after polling.
Ingest large files
Use ingest_large_dataset when a file should be uploaded directly to object storage instead of sent through the multipart dataset endpoint. The helper prepares a signed upload, streams the file, signals completion, and waits for ingestion.
from pathlib import Path
from woodwide import WoodWide, ingest_large_dataset
client = WoodWide()
dataset = ingest_large_dataset(
client,
file=Path("large_dataset.parquet"),
dataset_name="large-dataset",
)
print(dataset.submission.id)
print(dataset.job.status)
Paths and seekable binary file objects are streamed. If the filename cannot be inferred, provide filename; if the MIME type cannot be inferred, provide content_type.
Iterate through result rows
iter_result_rows handles offset pagination and yields one row at a time. The API supports pages of up to 500 rows.
from woodwide import WoodWide, iter_result_rows
client = WoodWide()
for row in iter_result_rows(
client,
"job_A8K2P9QX",
columns=["id", "anomaly_score"],
page_size=500,
):
print(row)
Import data from a connection
import_connection_data supports table, query, and object imports from an existing data connection.
from woodwide import WoodWide, import_connection_data
client = WoodWide()
result = import_connection_data(
client,
"conn_A8K2P9QX",
mode="table",
table_schema="public",
table_name="customers",
dataset_name="warehouse-customers",
)
print(result.submission.dataset_id)
Wait for an existing job
Submission endpoints return job IDs for asynchronous work. Pass the job ID—not a model or dataset ID—to wait_for_job or wait_for_training.
from woodwide import WoodWide, wait_for_job
client = WoodWide()
job = wait_for_job(client, "job_A8K2P9QX", timeout=1800, poll_interval=5)
print(job.status)
timeout is the maximum total time to wait. poll_interval controls the delay between job status requests.
Async usage
Use AsyncWoodWide with the async_ workflow helpers. Asynchronous row iteration uses async for.
import asyncio
from pathlib import Path
from woodwide import AsyncWoodWide
from woodwide import async_ingest_dataset
async def main() -> None:
async with AsyncWoodWide() as client:
dataset = await async_ingest_dataset(
client,
file=Path("customers.csv"),
dataset_name="customers",
)
print(dataset.submission.id)
asyncio.run(main())
The synchronous and asynchronous clients expose the same generated resources and parameters.
With aiohttp
By default, the async client uses httpx for HTTP requests. However, for improved concurrency performance you may also use aiohttp as the HTTP backend.
You can enable this by installing aiohttp:
# install from PyPI
pip install woodwide[aiohttp]
Then instantiate the client with http_client=DefaultAioHttpClient():
import asyncio
from woodwide import AsyncWoodWide, DefaultAioHttpClient
async def main() -> None:
async with AsyncWoodWide(
http_client=DefaultAioHttpClient(),
) as client:
jobs = await client.jobs.list()
print(jobs.items)
asyncio.run(main())
Direct API access
Use resource methods when you need direct control over individual HTTP operations. These methods return immediately after the corresponding endpoint responds; asynchronous server work can then be monitored with wait_for_job.
from pathlib import Path
from woodwide import WoodWide, wait_for_job
client = WoodWide()
submission = client.datasets.create(
file=Path("customers.csv"),
dataset_name="customers",
)
if submission.job_id is not None:
job = wait_for_job(client, submission.job_id)
print(job.status)
See api.md for every generated resource method and response type.
Request and response types
Nested request parameters are TypedDicts. Responses are Pydantic models which also provide helper methods for things like:
- Serializing back into JSON,
model.to_json() - Converting to a dictionary,
model.to_dict()
Typed requests and responses provide autocomplete and documentation within your editor. If you would like to see type errors in VS Code to help catch bugs earlier, set python.analysis.typeCheckingMode to basic.
Nested request parameters
Nested parameters are dictionaries, typed using TypedDict, for example:
from woodwide import WoodWide
client = WoodWide()
response = client.datasets.upload(
file={
"bytes": 1048576,
"content_type": "text/csv",
"filename": "customers.csv",
},
)
print(response.upload.upload_url)
This low-level call only prepares a signed upload. The application must still upload the file to response.upload.upload_url and call client.datasets.complete(response.version_id). Use ingest_large_dataset to manage that complete workflow automatically.
File parameters
Request parameters that correspond to file uploads can be passed as bytes, or a PathLike instance or a tuple of (filename, contents, media type).
from pathlib import Path
from woodwide import WoodWide
client = WoodWide()
client.datasets.create(file=Path("customers.csv"))
The asynchronous client accepts the same values and reads PathLike inputs asynchronously. For large files, prefer ingest_large_dataset or async_ingest_large_dataset so file bytes are sent directly to object storage.
Handling errors
When the library is unable to connect to the API (for example, due to network connection problems or a timeout), a subclass of woodwide.APIConnectionError is raised.
When the API returns a non-success status code (that is, 4xx or 5xx), a subclass of woodwide.APIStatusError is raised. The exception includes status_code and response properties.
All errors inherit from woodwide.APIError.
import woodwide
from woodwide import WoodWide
client = WoodWide()
try:
client.jobs.list()
except woodwide.APIConnectionError as exc:
print("The server could not be reached")
print(exc.__cause__) # The underlying exception, commonly raised by httpx.
except woodwide.RateLimitError:
print("A 429 status code was received; we should back off a bit.")
except woodwide.APIStatusError as exc:
print("Another non-200-range status code was received")
print(exc.status_code)
print(exc.response)
Error codes are as follows:
| Status Code | Error Type |
|---|---|
| 400 | BadRequestError |
| 401 | AuthenticationError |
| 403 | PermissionDeniedError |
| 404 | NotFoundError |
| 422 | UnprocessableEntityError |
| 429 | RateLimitError |
| >=500 | InternalServerError |
| N/A | APIConnectionError |
Retries
Certain errors are automatically retried twice by default with a short exponential backoff. Connection errors, HTTP 408 Request Timeout, HTTP 409 Conflict, HTTP 429 Rate Limit, and HTTP 5xx server errors are retried.
You can use the max_retries option to configure or disable retry settings:
from woodwide import WoodWide
# Configure the default for all requests:
client = WoodWide(
# default is 2
max_retries=0,
)
# Or, configure per-request:
client.with_options(max_retries=5).jobs.list()
Timeouts
By default requests time out after 60 seconds. You can configure this with a timeout option,
which accepts a float or an httpx.Timeout object:
import httpx
from woodwide import WoodWide
# Configure the default for all requests:
client = WoodWide(
# 20 seconds (default is 1 minute)
timeout=20.0,
)
# More granular control:
client = WoodWide(
timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0),
)
# Override per-request:
client.with_options(timeout=5.0).jobs.list()
On timeout, the SDK raises APITimeoutError.
Note that requests that time out are retried twice by default.
Advanced
Logging
We use the standard library logging module.
You can enable logging by setting the environment variable WOODWIDE_LOG to info.
export WOODWIDE_LOG=info
Or to debug for more verbose logging.
How to tell whether None means null or missing
In an API response, a field may be explicitly null, or missing entirely; in either case, its value is None in this library. You can differentiate the two cases with .model_fields_set:
if response.my_field is None:
if "my_field" not in response.model_fields_set:
print('Received JSON without a "my_field" property.')
else:
print('Received JSON with "my_field": null.')
Accessing raw response data (e.g. headers)
Access the raw response by prefixing an HTTP method call with .with_raw_response:
from woodwide import WoodWide
client = WoodWide()
response = client.jobs.with_raw_response.list()
print(response.headers.get("X-My-Header"))
job = response.parse() # get the object that `jobs.list()` would have returned
print(job.items)
These methods return an APIResponse object.
The async client returns an AsyncAPIResponse with the same structure, the only difference being awaitable methods for reading the response content.
.with_streaming_response
The above interface eagerly reads the full response body when you make the request, which may not always be what you want.
To stream the response body, use .with_streaming_response instead, which requires a context manager and only reads the response body once you call .read(), .text(), .json(), .iter_bytes(), .iter_text(), .iter_lines() or .parse(). In the async client, these are async methods.
with client.jobs.with_streaming_response.list() as response:
print(response.headers.get("X-My-Header"))
for line in response.iter_lines():
print(line)
The context manager is required so that the response will reliably be closed.
Making custom/undocumented requests
This library is typed for convenient access to the documented API.
If you need to access undocumented endpoints, params, or response properties, the library can still be used.
Undocumented endpoints
Use client.get, client.post, and the other HTTP methods to call endpoints that are not represented by generated resources. Client options such as retries are applied to these requests.
import httpx
response = client.post(
"/foo",
cast_to=httpx.Response,
body={"my_param": True},
)
print(response.headers.get("x-foo"))
Undocumented request params
Use the extra_query, extra_body, and extra_headers request options to send parameters that are not represented by a generated method signature.
Undocumented response properties
Undocumented response properties are available as attributes such as response.unknown_prop. They are also available as a dictionary through response.model_extra.
Configuring the HTTP client
You can directly override the httpx client to customize it for your use case, including:
- Support for proxies
- Custom transports
- Additional advanced functionality
import httpx
from woodwide import WoodWide, DefaultHttpxClient
client = WoodWide(
# Or use the `WOODWIDE_BASE_URL` env var
base_url="http://my.test.server.example.com:8083",
http_client=DefaultHttpxClient(
proxy="http://my.test.proxy.example.com",
transport=httpx.HTTPTransport(local_address="0.0.0.0"),
),
)
You can also customize the client on a per-request basis by using with_options():
client.with_options(http_client=DefaultHttpxClient(...))
Managing HTTP resources
By default the library closes underlying HTTP connections whenever the client is garbage collected. You can manually close the client using the .close() method if desired, or with a context manager that closes when exiting.
from woodwide import WoodWide
with WoodWide() as client:
# Make requests here.
...
# HTTP client is now closed
Versioning
This package generally follows SemVer conventions, though certain backwards-incompatible changes may be released as minor versions:
- Changes that only affect static types, without breaking runtime behavior.
- Changes to library internals which are technically public but not intended or documented for external use. (Please open a GitHub issue to let us know if you are relying on such internals.)
- Changes that we do not expect to impact the vast majority of users in practice.
We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.
We are keen for your feedback; please open an issue with questions, bugs, or suggestions.
Determining the installed version
If you've upgraded to the latest version but aren't seeing any new features you were expecting then your python environment is likely still using an older version.
You can determine the version that is being used at runtime with:
import woodwide
print(woodwide.__version__)
Requirements
Python 3.9 or higher.
Contributing
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file woodwide-0.9.0.tar.gz.
File metadata
- Download URL: woodwide-0.9.0.tar.gz
- Upload date:
- Size: 285.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via:
uv/0.9.13 {"installer":{"name":"uv","version":"0.9.13"},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
666ded165aabc026772e4eead3ad3b491e06769c0e304c484dd4281b0b69fed3
|
|
| MD5 |
df69f4bde53d32e5c6a50038eae71928
|
|
| BLAKE2b-256 |
41e6fc4ed33dca9fc96a81df3ea1e76fb96ddd82c2c13b45cc28934d7560909e
|
File details
Details for the file woodwide-0.9.0-py3-none-any.whl.
File metadata
- Download URL: woodwide-0.9.0-py3-none-any.whl
- Upload date:
- Size: 163.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via:
uv/0.9.13 {"installer":{"name":"uv","version":"0.9.13"},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9058199e4c572541a12e887142e8e73df8c359764f9af54202e93d226306ba4d
|
|
| MD5 |
9a34457b4c11365e4cddb56aad7508d1
|
|
| BLAKE2b-256 |
46c9a7ed328a8463242f1acea585cd257b42db913c49de66637675d02eefefb3
|