Get an API Key

Navigate to the settings page by clicking the user avatar in the top right corner and selecting “API Keys”

From here you can generate a new API key.

Trigger the API

After you’ve published an app, you can access its API in the API tab of that app’s “Deployments” page.

The endpoint will look like this:

https://app.wordware.ai/api/released-app/<app_id>/run

Request Body

You have to pass two parameters to the request body: inputs and version.

Inputs

Pass the inputs for this WordApp as a JSON object. The keys are the names of the inputs defined in the WordApp, and the values are the actual values you want to use for those inputs. For audio and image inputs you need to specify the type and provide a publicly accessible URL.

{
  "inputs": {
    "text": "<text_value>",
    "image": {
      "type": "image",
      "image_url": "<string>"
    },
    "audio": {
      "type": "audio",
      "audio_url": "<string>"
    }
  },
  "version": "^1.0"
}

Version

We use a simplified semantic versioning. All versions follow the format <major>.<minor>, for example 1.0.

You have to pass the version number you want to use. You can use the caret syntax like this to get the latest minor version: ^1.0. We recommend you use this syntax when you build your APIs. Example:

{ "version": "^1.0" }

Authentication

You need to pass your API key in the Authorization header. In a JavaScript fetch request this looks like:

headers: {
  Authorization: `Bearer ${API_KEY}`,
},

In Python requests this looks like:

headers={"Authorization": f"Bearer {API_KEY}"},

Response

It is super easy to stream the response from the API. We’ll send you chunks of the response as they’re generated. Below you can find examples of how to consume the response in Python and JavaScript.

Python Implementation

import json
import requests

def main():
    app_id = "YOUR_APP_ID"
    api_key = "YOUR_API_KEY"

    # Execute the prompt
    r = requests.post(f"https://app.wordware.ai/api/released-app/{app_id}/run",
                      json={
                          "inputs": {
                              "topic": "sugary cereal",
                              # Image inputs have a different format and require a publicly accessible URL
                              "image": {
                                  "type": "image",
                                  "image_url": "https://i.insider.com/602ee9ced3ad27001837f2ac",
                              },
                              "version": "^1.0"
                          }
                      },
                      headers={"Authorization": f"Bearer {api_key}"},
                      stream=True
                      )

    # Ensure the request was successful
    if r.status_code != 200:
        print("Request failed with status code", r.status_code)
        print(json.dumps(r.json(), indent=4))
    else:
        for line in r.iter_lines():
            if line:
                content = json.loads(line.decode('utf-8'))
                value = content['value']
                # We can print values as they're generated
                if value['type'] == 'generation':
                    if value['state'] == "start":
                        print("\nNEW GENERATION -", value['label'])
                    else:
                        print("\nEND GENERATION -", value['label'])
                elif value['type'] == "chunk":
                    print(value['value'], end="")
                elif value['type'] == "outputs":
                    # Or we can read from the outputs at the end
                    # Currently we include everything by ID and by label - this will likely change in future in a breaking
                    # change but with ample warning
                    print("\nFINAL OUTPUTS:")
                    print(json.dumps(value, indent=4))

if __name__ == '__main__':
    main()

JavaScript/TypeScript Implementation

const API_KEY = "YOUR_API_KEY";
const appId = "YOUR_APP_ID";

async function main() {
  console.log("Running app", appId);
  // Run the prompt, streaming the outputs as they're generated
  const r = await fetch(
    `https://app.wordware.ai/api/released-app/${appId}/run`,
    {
      method: "post",
      body: JSON.stringify({
        inputs: {
          topic: "Sugary cereal",
          // Image inputs have a different format and require a publicly
          // accessible URL
          image: {
            type: "image",
            image_url: "https://i.insider.com/602ee9ced3ad27001837f2ac",
          },
        },
        version: "^1.0",
      }),
      headers: {
        Authorization: `Bearer ${API_KEY}`,
      },
    }
  );

  if (!r.ok) {
    console.error("Run failed", await r.json());
    throw Error(`Run failed ${r.status}`);
  }

  const reader = r.body.getReader();

  const decoder = new TextDecoder();
  let buffer = [];

  try {
    while (true) {
      const { done, value } = await reader.read();

      if (done) {
        return;
      }

      const chunk = decoder.decode(value);

      for (let i = 0, len = chunk.length; i < len; ++i) {
        const isChunkSeparator = chunk[i] === "\n";

        // Keep buffering unless we've hit the end of a data chunk
        if (!isChunkSeparator) {
          buffer.push(chunk[i]);
          continue;
        }

        const line = buffer.join("").trimEnd();

        // This is the chunk
        const content = JSON.parse(line);
        const value = content.value;

        // Here we print the streamed generations
        if (value.type === "generation") {
          if (value.state === "start") {
            console.log("\nNEW GENERATION -", value.label);
          } else {
            console.log("\nEND GENERATION -", value.label);
          }
        } else if (value.type === "chunk") {
          process.stdout.write(value.value ?? "");
        } else if (value.type === "outputs") {
          console.log(value);
        }

        buffer = [];
      }
    }
  } finally {
    reader.releaseLock();
  }
}

main();

Check these out next

Here are some next steps you may want to take to get the most out of Wordware: