Skip to content

Call API Handlers from the Integration UI

It’s possible to call an API handler from your integration’s UI. This is useful if you want to interact with the Integration API or Netlify API from the Integration UI. For example:

  • create or update environment variables
  • update the integration configuration
  • get a list of sites for the team

To support this, we make an access token available to callback functions that you can use in calls to the Netlify API.

To call an API handler from within callbacks in the Integration UI, do the following:

  1. Use the fetch function provided in the surfaceState. This fetch function will ensure all the necessary headers are set so that you can make authenticated calls to your API handler.

  2. Provide the fetch function the name of your API handler. As a convenience, this fetch function sets a base URL for your API handler, so you only need to provide the name of your API handler. For example, if you created an API handler with integration.addApiHandler("save-config", ...) you can call this API handler with fetch("save-config", ...). Aside from the preset base URL, the fetch function works the same as the Fetch API.

Here’s a basic example showing how to call a function to save user input for integration configuration based on user interaction with a button.

// src/ui/index.ts
route.addButton({
  title: "Save changes",
  callback: async (surfaceState) => {
    const { fetch } = surfaceState;

    const response = await fetch("save-config", {
      method: "POST",
      body: JSON.stringify({
        // ...
      }),
    });
  },
});

Here’s a more complex example of a form element that includes a network call.

// src/ui/index.ts
route.addForm(
  {
    title: "Configuration",
    id: "configuration-form",
    onSubmit: (surfaceState) => {
      const { integrationContext, fetch, picker } = surfaceState;
      const { siteId, accountId } = integrationContext;

      const apiKey = picker.getFormInputValue('configuration-form', 'apiKey')
      const linkResponse = await fetch('link', {
        method: "POST",
        body: JSON.stringify({ siteId, accountId, apiKey }),
        });
    },
    (card) => {
      card.addInputPassword({
        id: "apiKey",
        label: "API key",
      });
    }
  }
);