TypeScript SDK for the put.io API
Domain-first, schema-validated at the boundary, and designed for all runtimes.
npm install @putdotio/sdkuserAccessToken in these examples is an already-issued user token from your app or auth flow.
import { createPutioSdkPromiseClient } from "@putdotio/sdk";
const sdk = createPutioSdkPromiseClient({
accessToken: userAccessToken,
});
const account = await sdk.account.getInfo({
download_token: 1,
});The client can be created without a token, for flows that obtain or check one:
const sdk = createPutioSdkPromiseClient();
const validation = await sdk.auth.validateToken(tokenToCheck);
const login = await sdk.auth.login({
callbackUrl,
clientId,
clientSecret,
password,
username,
});Long-lived Promise clients can replace or clear their token without recreating the client:
sdk.setAccessToken(nextUserAccessToken);
const account = await sdk.account.getInfo({});
sdk.setAccessToken(undefined);The token is snapshotted when each Promise-client operation is invoked. Token changes apply to subsequent operations; an operation already in flight keeps the snapshot it started with. Base, upload, and web app URLs remain fixed from client creation.
Authorization-code clients can exchange a code without configuring a default access token:
const sdk = createPutioSdkPromiseClient();
const accessToken = await sdk.auth.exchangeAuthorizationCode({
clientId,
clientSecret,
code,
redirectUri,
});The exchange uses a form-encoded POST and never sends a configured bearer token. Known OAuth
failures are exposed as OAuthAuthorizationCodeExchangeError; client secrets and codes are not
included in validation errors.
Create and manage passwords for apps that use put.io basic authentication:
const created = await sdk.account.appSpecificPasswords.create({
note: "Media server",
});
savePasswordSecurely(created.password);
const passwords = await sdk.account.appSpecificPasswords.list();
await sdk.account.appSpecificPasswords.delete(created.id);
await sdk.account.appSpecificPasswords.deleteAll();The plaintext password is returned only by create. List results contain metadata instead, including a nullable last_used_at timestamp and a null or masked ip_address.
Shared formatting, URL, and error-localization helpers are available from the utilities subpath:
import {
FileUrlProvider,
secondsToReadableDuration,
toHumanFileSize,
} from "@putdotio/sdk/utilities";const urls = new FileUrlProvider({ baseUrl: "https://api.put.io", downloadToken });
const size = toHumanFileSize(1_572_864);
const duration = secondsToReadableDuration(444);import { Effect } from "effect";
import {
PutioSdk,
createPutioSdkEffectClient,
makePutioSdkLiveClientLayer,
makePutioSdkLiveLayer,
} from "@putdotio/sdk";
const sdk = createPutioSdkEffectClient();
const program = sdk.files
.list(0, {
per_page: 20,
total: 1,
})
.pipe(Effect.provide(makePutioSdkLiveLayer({ accessToken: userAccessToken })));
const result = await Effect.runPromise(program);Effect workflows can also depend on the SDK as a service:
const serviceProgram = Effect.gen(function* () {
const sdk = yield* PutioSdk;
return yield* sdk.files.list(0, { per_page: 20 });
}).pipe(Effect.provide(makePutioSdkLiveClientLayer({ accessToken: userAccessToken })));makePutioSdkLiveClientLayer(...) provides the SDK service, SDK config, and default fetch-backed transport.
makePutioSdkLiveLayer(...) provides both the SDK config and the default fetch-backed transport.
Use makePutioSdkLayer(...) with makePutioFetchLayer(...) or your own PutioHttpClient service when you want to supply custom transport.
Both client styles expose the same domain surface:
promiseClient.files.list(0, { per_page: 20 });
effectClient.files.list(0, { per_page: 20 });| Client | Use it for |
|---|---|
createPutioSdkPromiseClient(config) |
React apps, scripts, server handlers, React Query |
createPutioSdkEffectClient() |
Effect-native workflows and service composition |
Effect is the canonical typed surface. The Promise client is an adapter for environments that want standard async functions.
- Effect client: keeps errors in the Effect error channel with operation-specific typing
- Promise client: throws tagged SDK error objects such as
PutioOperationError,PutioApiError, andPutioRateLimitError - Promise client: owns a managed Effect runtime; call
await sdk.dispose()when tearing down a long-lived client in a script, test harness, or server - Promise client:
files.createUploadFormData(...)builds upload FormData without a request
Interrupting an Effect during fetch or response-body consumption aborts the underlying fetch request, including JSON and binary reads. Successful reads do not abort the request.
| Namespace | Purpose |
|---|---|
account |
account info, settings, subtitle languages, app-specific passwords, confirmations, clear/destroy |
auth |
token validation, login flows, device/OOB helpers, two-factor flows |
config |
app-owned JSON config storage |
downloadLinks |
download-link bundles |
events |
history events and event torrent payloads |
family |
family members and invites |
files |
file listing, search, move/delete/extract, MP4, direct access URLs, upload |
friendInvites |
friend invitation management |
friends |
friend graph and requests |
ifttt |
IFTTT integration endpoints |
oauth |
OAuth app management |
payment |
plans, vouchers, payment flows, payment history |
podcast |
podcast feed links for folders and media types |
rss |
RSS feed management |
sharing |
friend shares, public shares, clone flows |
transfers |
transfer list, add/retry/cancel/clean flows |
trash |
trash listing, restore, delete, empty |
tunnel |
route listing |
utilities |
file URLs, localized errors, and shared formatting helpers |
zips |
zip creation and lookup |
- schema-first contracts at every external boundary
- typed errors are first-class
- parameter-conditioned responses are modeled explicitly
- no compatibility namespace shims in the public API
- fetch-native core with runtime-portable Web APIs
The package is designed around standard Web APIs. Host runtimes should provide:
fetchRequest,Response, andHeadersURLandURLSearchParamsAbortControllerFormDatabtoafor username/password auth flows such asauth.login(...)
For upload flows, the host should also provide file-compatible inputs such as File or Blob.
If a target runtime is missing these APIs, provide them with host-level polyfills or adapters instead of patching the SDK surface.
CI installs the packed package into external Node, Bun, and bundled Chromium, Firefox, and WebKit consumers on every change.
The fetch transport retains HTTP status and rate-limit headers when an error
response contains empty or invalid JSON. These errors include a sanitized parsing
cause; response contents are not included in that cause. Failures while reading
the body remain transport errors, including errors from custom HTTP clients.
Backend error bodies preserve status, status_code, error_type, error_message,
error_uri, nullable error_id, and structured extra metadata. The legacy
details field remains available for compatibility, but current backend errors use
extra; details is planned for removal in the next major release.
Promise consumers receive tagged SDK error objects:
import {
createPutioSdkPromiseClient,
isPutioOperationError,
isPutioRateLimitError,
} from "@putdotio/sdk";
const sdk = createPutioSdkPromiseClient({
accessToken: userAccessToken,
});
try {
await sdk.files.createFolder({
name: "",
parent_id: 0,
});
} catch (error) {
if (isPutioOperationError(error)) {
if (error.operation === "createFolder") {
console.log(error.body.error_type);
}
}
if (isPutioRateLimitError(error)) {
console.log(error.retryAfter);
}
}Effect consumers keep errors in the typed error channel instead of throwing:
import { Effect } from "effect";
import { PutioSdk, makePutioSdkLiveClientLayer } from "@putdotio/sdk";
const handled = Effect.gen(function* () {
const sdk = yield* PutioSdk;
return yield* sdk.files.createFolder({
name: "",
parent_id: 0,
});
}).pipe(
Effect.catchTag("PutioOperationError", (error) => {
if (error.operation === "createFolder") {
return Effect.succeed(error.body.error_type);
}
return Effect.fail(error);
}),
Effect.provide(makePutioSdkLiveClientLayer({ accessToken: userAccessToken })),
);files exposes both JSON contracts and direct route helpers. Media URLs leave your app (players,
casting receivers, shared links, logs), so sign them with the account download token, which only
grants file access, instead of the OAuth token. downloadToken is required; the helpers never
fall back to the client's accessToken.
const { download_token: downloadToken } = await sdk.account.getInfo({ download_token: 1 });
const playlistUrl = await sdk.files.getHlsStreamUrl(fileId, {
downloadToken,
maxSubtitleCount: 1,
});
const vlcPlaylistUrl = await sdk.files.getXspfPlaylistUrl(fileId, { downloadToken });
// The master playlist put.io would serve, for inspecting the selected
// variant's CODECS and VIDEO-RANGE. `playOriginal` picks the original
// file over the MP4 conversion.
const masterPlaylist = await sdk.files.getHlsMasterPlaylist(fileId, {
playOriginal: false,
});
const upload = await sdk.files.upload({
file: new File(["hello"], "hello.txt"),
parentId: 0,
});Upload targets upload.put.io internally because api.put.io/v2/files/upload is only a redirect shim.
The TypeScript SDK mirrors the supported public put.io API surface. Scope, exclusions, and the latest audit are in API Coverage.
When requesting media_info, stream level values preserve FFmpeg's -99
sentinel for an unknown codec level. Known levels remain nonnegative integers.
Stream codec_name can be null when the codec was not identified, including
subtitle streams.
Named-child lookup avoids listing an entire folder and preserves the same query-conditioned fields as
files.get:
const child = await sdk.files.getChild({
parentId: folderId,
name: "movie.mp4",
query: { stream_url: 1 },
});
await sdk.files.touch({ fileIds: [child.id], updatedAt: new Date() });
const copy = await sdk.files.copy({ fileId: child.id, parentId: 0, name: "movie copy.mp4" });
const writableUserId = await sdk.files.canWrite(copy.id);canWrite resolves the user ID returned by the backend when the file is writable. A non-writable,
missing, or payment-gated file rejects with the corresponding typed SDK error rather than returning
false.
Torrent-backed transfers expose their original metainfo bytes and tracker mutation:
const torrent = await sdk.transfers.getTorrent(transferId);
await sdk.transfers.addTrackers({
transferId,
trackers: ["udp://tracker.example:80", "https://tracker.example/announce"],
});getTorrent rejects for magnet-backed or non-torrent transfers. Remove accepts exactly one selector,
preventing an ambiguous mix of IDs and filters:
await sdk.transfers.remove({ ids: [transferId] });
await sdk.transfers.remove({ filter: "completed" });Folder sort settings persist per folder and apply to subsequent file listings:
await sdk.files.setSort({
fileId: folderId,
sortBy: "MODIFIED_DESC",
});
await sdk.files.resetSortSettings();resetSortSettings() clears the saved sort setting for every folder, including the root folder.
Podcast links can target a folder and an explicit non-empty selection of feed types. Omit
types to request the API defaults:
const { links, token } = await sdk.podcast.getLinks({
parentId: folderId,
types: ["audio", "mp4"],
});links is a partial map keyed by all, audio, video, and mp4, so consumers should
check whether a requested link is present.
The Promise client plugs into TanStack Query directly:
import { useQuery } from "@tanstack/react-query";
import { createPutioSdkPromiseClient } from "@putdotio/sdk";
const sdk = createPutioSdkPromiseClient({
accessToken: token,
});
export const useAccountInfo = () =>
useQuery({
queryKey: ["account", "info"],
queryFn: () => sdk.account.getInfo({ download_token: 1 }),
});The Effect client also works well when you want the canonical typed API:
import { useQuery } from "@tanstack/react-query";
import { Effect } from "effect";
import { PutioSdk, makePutioSdkLiveClientLayer } from "@putdotio/sdk";
const sdkLayer = makePutioSdkLiveClientLayer({
accessToken: token,
});
export const useFiles = (parentId: number) =>
useQuery({
queryKey: ["files", parentId],
queryFn: () =>
Effect.runPromise(
Effect.gen(function* () {
const sdk = yield* PutioSdk;
return yield* sdk.files.list(parentId, { per_page: 50 });
}).pipe(Effect.provide(sdkLayer)),
),
});- Migrating to v12 for required
downloadTokenmedia URLs and theFileUrlProviderrenames - Migrating to v11 for the removed Coinbase and file-search contracts
- Architecture for package shape and boundaries
- Testing for local and live verification
- Distribution for release automation
- Security policy for private vulnerability reports; fixes target the latest published release and
main
Contributor setup, validation, and live-test workflow live in Contributing.
This project is available under the MIT License.
