TypeScript
Documentation for the Document AI TypeScript SDK
SDK Installation
The SDK can be installed with either npm, pnpm, bun or yarn package managers.
NPM
PNPM
Bun
Yarn
[!NOTE] This package is published with CommonJS and ES Modules (ESM) support.
Requirements
Supported JavaScript runtimes
This SDK is intended to be used in JavaScript runtimes that support ECMAScript 2020 or newer. The SDK uses the following features:
- Web Fetch API
- Web Streams API and in particular
ReadableStream
- Async iterables using
Symbol.asyncIterator
Runtime environments that are explicitly supported are:
- Evergreen browsers which include: Chrome, Safari, Edge, Firefox
- Node.js active and maintenance LTS releases
- Currently, this is v18 and v20
- Bun v1 and above
- Deno v1.39
- Note that Deno does not currently have native support for streaming file uploads backed by the filesystem (issue link)
Recommended TypeScript compiler options
The following tsconfig.json
options are recommended for projects using this
SDK in order to get static type support for features like async iterables,
streams and fetch
-related APIs (for await...of
,
AbortSignal
, Request
, Response
and
so on):
While target
can be set to older ECMAScript versions, it may result in extra,
unnecessary compatibility code being generated if you are not targeting old
runtimes.
SDK Example Usage
Example
Authentication
Per-Client Security Schemes
This SDK supports the following security scheme globally:
Name | Type | Scheme | Environment Variable |
---|---|---|---|
apiKeyAuth | http | HTTP Bearer | DOCUMENTAI_API_KEY_AUTH |
To authenticate with the API the apiKeyAuth
parameter must be set when initializing the SDK client instance. For example:
Available Resources and Operations
The available API operations and SDK implementation examples can be found within our API Reference documentation
Pagination
Some of the endpoints in this SDK support pagination. To use pagination, you
make your SDK calls as usual, but the returned response object will also be an
async iterable that can be consumed using the for await...of
syntax.
Here’s an example of one such pagination call:
Retries
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide a retryConfig object to the call:
If you’d like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:
Error Handling
Some methods specify known errors which can be thrown. All the known errors are enumerated in the models/errors/errors.ts
module. The known errors for a method are documented under the Errors tables in SDK docs. For example, the list
method may throw the following errors:
Error Type | Status Code | Content Type |
---|---|---|
errors.BadRequestError | 400 | application/json |
errors.UnauthorizedError | 401 | application/json |
errors.TooManyRequestsError | 429 | application/json |
errors.InternalServerError | 500 | application/json |
errors.APIError | 4XX, 5XX | */* |
If the method throws an error and it is not captured by the known errors, it will default to throwing a APIError
.
Validation errors can also occur when either method arguments or data returned from the server do not match the expected format. The SDKValidationError
that is thrown as a result will capture the raw value that failed validation in an attribute called rawValue
. Additionally, a pretty()
method is available on this error that can be used to log a nicely formatted multi-line string since validation errors can list many issues and the plain error string may be difficult read when debugging.
In some rare cases, the SDK can fail to get a response from the server or even make the request due to unexpected circumstances such as network conditions. These types of errors are captured in the models/errors/httpclienterrors.ts
module:
HTTP Client Error | Description |
---|---|
RequestAbortedError | HTTP request was aborted by the client |
RequestTimeoutError | HTTP request timed out due to an AbortSignal signal |
ConnectionError | HTTP client was unable to make a request to a server |
InvalidRequestError | Any input used to create a request is invalid |
UnexpectedClientError | Unrecognised or unexpected error |
Server Selection
Override Server URL Per-Client
The default server can be overridden globally by passing a URL to the serverURL: string
optional parameter when initializing the SDK client instance. For example:
Custom HTTP Client
The TypeScript SDK makes API calls using an HTTPClient
that wraps the native
Fetch API. This
client is a thin wrapper around fetch
and provides the ability to attach hooks
around the request lifecycle that can be used to modify the request or handle
errors and response.
The HTTPClient
constructor takes an optional fetcher
argument that can be
used to integrate a third-party HTTP client or when writing tests to mock out
the HTTP client and feed in fixtures.
The following example shows how to use the "beforeRequest"
hook to to add a
custom header and a timeout to requests and how to use the "requestError"
hook
to log errors:
Debugging
You can setup your SDK to emit debug logs for SDK requests and responses.
You can pass a logger that matches console
’s interface as an SDK option.
[!WARNING] Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It’s recommended to use this feature only during local development and not in production.
You can also enable a default debug logger by setting an environment variable DOCUMENTAI_DEBUG
to true.