Skip to content

writerai/writer-client-sdk-typescript

Repository files navigation

Typescript SDK

AI for everyone.

SDK Installation

NPM

npm add @writerai/writer-sdk

Yarn

yarn add @writerai/writer-sdk

Authentication

Writer authenticates your API requests using your account’s API keys. If you do not include your key when making an API request, or use one that is incorrect or outdated, Writer returns an error.

Your API keys are available in the account dashboard. We include randomly generated API keys in our code examples if you are not logged in. Replace these with your own or log in to see code examples populated with your own API keys.

writer-auth

If you cannot see your secret API keys in the Dashboard, this means you do not have access to them. Contact your Writer account owner and ask to be added to their team as a developer.

SDK Example Usage

Example

import { Writer } from "@writerai/writer-sdk";

const writer = new Writer({
    apiKey: "<YOUR_API_KEY_HERE>",
    organizationId: 850421,
});

async function run() {
    const result = await writer.billing.getSubscriptionDetails();

    // Handle the result
    console.log(result);
}

run();

Available Resources and Operations

  • detect - Content detector api
  • check - Check your content against your preset styleguide.
  • correct - Apply the style guide suggestions directly to your content.
  • list - List available LLM models
  • create - Create model customization
  • delete - Delete Model customization
  • get - Get model customization
  • list - List model customizations
  • fetchFile - Download your fine-tuned model (available only for Palmyra Base and Palmyra Large)
  • get - Get document details
  • list - List team documents

Global Parameters

A parameter is configured globally. This parameter must be set on the SDK client instance itself during initialization. When configured as an option during SDK initialization, This global value will be used as the default on the operations that use it. When such operations are called, there is a place in each to override the global value, if needed.

For example, you can set organizationId to 99895 at SDK initialization and then you do not have to pass the same value on calls to operations like detect. But if you want to do so you may, which will locally override the global setting. See the example code below for a demonstration.

Available Globals

The following global parameter is available. The required parameter must be set when you initialize the SDK client.

Name Type Required Description
organizationId number ✔️ The organizationId parameter.

Example

import { Writer } from "@writerai/writer-sdk";

const writer = new Writer({
    apiKey: "<YOUR_API_KEY_HERE>",
    organizationId: 496531,
});

async function run() {
    const contentDetectorRequest = {
        input: "<value>",
    };
    const organizationId = 592237;

    const result = await writer.aiContentDetector.detect(contentDetectorRequest, organizationId);

    // Handle the result
    console.log(result);
}

run();

Error Handling

All SDK methods return a response object or throw an error. If Error objects are specified in your OpenAPI Spec, the SDK will throw the appropriate Error type.

Error Object Status Code Content Type
errors.FailResponse 400,401,403,404,500 application/json
errors.SDKError 4xx-5xx /

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 string since validation errors can list many issues and the plain error string may be difficult read when debugging.

import { Writer } from "@writerai/writer-sdk";
import * as errors from "@writerai/writer-sdk/sdk/models/errors";

const writer = new Writer({
    apiKey: "<YOUR_API_KEY_HERE>",
    organizationId: 850421,
});

async function run() {
    let result;
    try {
        result = await writer.billing.getSubscriptionDetails();
    } catch (err) {
        switch (true) {
            case err instanceof errors.SDKValidationError: {
                // Validation errors can be pretty-printed
                console.error(err.pretty());
                // Raw value may also be inspected
                console.error(err.rawValue);
                return;
            }
            case err instanceof errors.FailResponse: {
                console.error(err); // handle exception
                return;
            }
            default: {
                throw err;
            }
        }
    }

    // Handle the result
    console.log(result);
}

run();

Server Selection

Select Server by Index

You can override the default server globally by passing a server index to the serverIdx optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the indexes associated with the available servers:

# Server Variables
0 https://enterprise-api.writer.com None
import { Writer } from "@writerai/writer-sdk";

const writer = new Writer({
    serverIdx: 0,
    apiKey: "<YOUR_API_KEY_HERE>",
    organizationId: 850421,
});

async function run() {
    const result = await writer.billing.getSubscriptionDetails();

    // Handle the result
    console.log(result);
}

run();

Override Server URL Per-Client

The default server can also be overridden globally by passing a URL to the serverURL optional parameter when initializing the SDK client instance. For example:

import { Writer } from "@writerai/writer-sdk";

const writer = new Writer({
    serverURL: "https://enterprise-api.writer.com",
    apiKey: "<YOUR_API_KEY_HERE>",
    organizationId: 850421,
});

async function run() {
    const result = await writer.billing.getSubscriptionDetails();

    // Handle the result
    console.log(result);
}

run();

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:

import { Writer } from "@writerai/writer-sdk";
import { HTTPClient } from "@writerai/writer-sdk/lib/http";

const httpClient = new HTTPClient({
  // fetcher takes a function that has the same signature as native `fetch`.
  fetcher: (request) => {
    return fetch(request);
  }
});

httpClient.addHook("beforeRequest", (request) => {
  const nextRequest = new Request(request, {
    signal: request.signal || AbortSignal.timeout(5000);
  });

  nextRequest.headers.set("x-custom-header", "custom value");

  return nextRequest;
});

httpClient.addHook("requestError", (error, request) => {
  console.group("Request Error");
  console.log("Reason:", `${error}`);
  console.log("Endpoint:", `${request.method} ${request.url}`);
  console.groupEnd();
});

const sdk = new Writer({ httpClient });

Authentication

Per-Client Security Schemes

This SDK supports the following security scheme globally:

Name Type Scheme
apiKey apiKey API key

To authenticate with the API the apiKey parameter must be set when initializing the SDK client instance. For example:

import { Writer } from "@writerai/writer-sdk";

const writer = new Writer({
    apiKey: "<YOUR_API_KEY_HERE>",
    organizationId: 850421,
});

async function run() {
    const result = await writer.billing.getSubscriptionDetails();

    // Handle the result
    console.log(result);
}

run();

File uploads

Certain SDK methods accept files as part of a multi-part request. It is possible and typically recommended to upload files as a stream rather than reading the entire contents into memory. This avoids excessive memory consumption and potentially crashing with out-of-memory errors when working with very large files. The following example demonstrates how to attach a file stream to a request.

Tip

Depending on your JavaScript runtime, there are convenient utilities that return a handle to a file without reading the entire contents into memory:

  • Node.js v20+: Since v20, Node.js comes with a native openAsBlob function in node:fs.
  • Bun: The native Bun.file function produces a file handle that can be used for streaming file uploads.
  • Browsers: All supported browsers return an instance to a File when reading the value from an <input type="file"> element.
  • Node.js v18: A file stream can be created using the fileFrom helper from fetch-blob/from.js.
import { Writer } from "@writerai/writer-sdk";
import { openAsBlob } from "node:fs";

const writer = new Writer({
    apiKey: "<YOUR_API_KEY_HERE>",
    organizationId: 403654,
});

async function run() {
    const uploadModelFileRequest = {
        file: await openAsBlob("./sample-file"),
    };
    const organizationId = 330343;

    const result = await writer.files.upload(uploadModelFileRequest, organizationId);

    // Handle the result
    console.log(result);
}

run();

Requirements

For supported JavaScript runtimes, please consult RUNTIMES.md.

SDK Generated by Speakeasy