docsGuidesConnecting APIs directly

Connecting API endpoints directly

We can connect PromptQL to API endpoints to query them directly.

Sometimes bulk loading data from API services might be overkill. In such cases, connecting to API endpoints directly is useful or a convenient way to test your API integration.

However, if you expect to run into API rate limits, or need more flexible access to data that would require filtering data in ways that the API doesn’t natively allow for, consider bulk loading the data instead.

Add a “code” connector

Instead of adding a “data” connector that is backed by a persistent data store (like a database, or DuckDB), we’ll add a code connector.

After creating your supergraph project with ddn supergraph init myproject --with-promptql load one of the following connectors:

  1. TypeScript + DuckDB: hasura/duckduckapi
  2. TypeScript with NodeJS runtime: hasura/nodejs
  3. Python: hasura/python

All of these connectors follow the same design, but for the purposes of this guide we’ll follow the TypeScript guide.

Add the connector

Install the connector and say hello!

ddn connector init typescript -i
> choose hasura/nodejs from the dropdown
> hit return to tap through the defaults

Introspect and see what the connector has

ddn connector introspect typescript
ddn commands list typescript

You should see a default hello world command being AVAILABLE which means that its not yet added to the supergraph.

Calling an external API

Head over to app/connector/typescript/ and open up functions.ts. In it, change the hello function to:

/**
 * This is an API to say hello from httpbin for a given name
 * @readonly
 */
export async function helloFromHttpBin(name?: string): Promise<{ greeting?: string }> {
  const greeting = { greeting: name };
 
  const response = await fetch('https://httpbin.org/post', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ greeting: `Hello ${name}!` }),
  });
 
  const data: any = await response.json();
  return { greeting: data?.json?.greeting };
}

Add to the metadata & run

ddn connector introspect typescript
ddn commands list typescript
ddn commands add typescript helloFromHttpBin
ddn supergraph build local

Restart the docker container:

ddn run docker-start

Try PromptQL

Run the console:

ddn console --local

Head over to the playground and see if the AI assistant is able to call your API integration.

say hello from httpBin for everyone