> ## Documentation Index
> Fetch the complete documentation index at: https://docs.respell.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Run Spell from HubSpot Workflows

You can trigger Respell spells directly from your HubSpot workflows using a **Custom Code** action. This allows you to automate actions based on HubSpot events and data.

In this guide, we'll show you how to set up a workflow that triggers a spell to make a phone call using Bland AI.

## Workflow Setup

1. **Create a Spell with Manual Inputs in Respell**

   * Log in to your Respell account and create a new spell that uses Bland AI to make a phone call.
   * Ensure the spell requires manual inputs, such as the **name** of the person and **phone number** to call.

2. **Add a Custom Code Action in Your HubSpot Workflow**

   * In your HubSpot account, navigate to **Automation > Workflows** and select the workflow you want to modify.
   * Click on the **+** icon to add a new action and choose **Custom Code** under the **Actions** category.

3. **Get Your Respell API Credentials and Inputs**

   * Open your spell in Respell.
   * Click on the **`</>` API** tab.
   * Note your **API Key**, **Spell ID**, and **Input Parameters**.

     ![HubSpot Custom Webhook](https://mintlify.s3-us-west-1.amazonaws.com/respell-docs-v2/_images/api-reference/hubspot-custom-code-inputs.png)

4. **Set the Properties to Include in the Code**

   * In the **Custom Code** action in HubSpot, specify the properties you want to use from your workflow:
     * **Properties to include in code**: Add the names of the HubSpot properties you want to access, such as `name` and `phone`.
   * These properties will be accessible in your code via `event.inputFields`.

## Triggering the Spell

5. **Copy and Update the Code**

   Copy the code below and update it with your credentials from step 3.

   ```javascript
   exports.main = async (event, callback) => {
     // Get the inputs from the HubSpot workflow properties
     const name = event.inputFields["name"];
     const phoneNumber = event.inputFields["phone"];

     const response = await fetch("https://v2-api.respell.ai/spells/start", {
       method: "POST",
       headers: {
         "x-api-key": "<YOUR_RESPELL_API_KEY>", // Replace with your API key
         Accept: "application/json",
         "Content-Type": "application/json",
       },
       body: JSON.stringify({
         spellId: "<YOUR_SPELL_ID>", // Replace with your spell ID
         wait: false,
         inputs: {
           name: name, // Replace with the inputs used in your spell
           phone_number: phoneNumber, // Replace with the inputs used in your spell
         },
       }),
     });

     // Optional: Handle the response if needed
   };
   ```

   **Note**: Customize this code to use any contact properties from HubSpot as inputs to your spell.

   Here is an example of the Custom Code action in HubSpot:

   ![HubSpot Custom Code](https://mintlify.s3-us-west-1.amazonaws.com/respell-docs-v2/_images/api-reference/hubspot-custom-code.png)

## Using Display Outputs (Optional)

If you want to use the spell's output in future steps of your HubSpot workflow, set `wait: true` and modify the code to handle the response.

6. **Modify the Code to Wait for the Spell's Output**

   ```javascript
   exports.main = async (event, callback) => {
     const name = event.inputFields["name"];
     const phoneNumber = event.inputFields["phone"];

     const response = await fetch("https://v2-api.respell.ai/spells/start", {
       method: "POST",
       headers: {
         "x-api-key": "<YOUR_RESPELL_API_KEY>",
         Accept: "application/json",
         "Content-Type": "application/json",
       },
       body: JSON.stringify({
         spellId: "<YOUR_SPELL_ID>",
         wait: true, // Set this to true to wait for the spell to complete
         inputs: {
           name: name,
           phone_number: phoneNumber,
         },
       }),
     });

     const result = await response.json();

     // Use the callback to pass the spell's output to the next steps
     callback({
       outputFields: {
         transcript: result.outputs.transcript, // Adjust based on your spell's output structure
         answered_by: result.outputs.answered_by, // Adjust based on your spell's output structure
       },
     });
   };
   ```

   **Note**: Ensure that the keys in `result.outputs` match the actual output keys from your spell.

7. **Replace Placeholder Values**

   * `<YOUR_RESPELL_API_KEY>`: Your Respell API key. It's recommended to store this securely using HubSpot's **Secrets** feature.
   * `<YOUR_SPELL_ID>`: The ID of the spell you want to trigger.
   * Customize the `inputs` object based on your spell's required inputs.
   * Adjust `transcript` and `answered_by` in the `callback` function to match the data you need from the spell's response.

**How to Find the Output Keys for Your Spell:**

* Open your spell in Respell.
* **Important**: Make sure you have a **Display Outputs** step in your spell.
* Click on the **`</>` API** tab.
* Ensure the "Wait for the spell run to finish" option is checked.
* Review the output structure displayed to identify the correct keys.

  ![HubSpot Custom Code with Output](https://mintlify.s3-us-west-1.amazonaws.com/respell-docs-v2/_images/api-reference/hubspot-custom-code-outputs.png)

## Tips

* **Use HubSpot's Secrets Feature**: Store sensitive information like your Respell API key securely by using HubSpot's [Secrets](https://developers.hubspot.com/docs/api/workflows/custom-code-actions#manage-action-secrets) feature.
  * In your **Custom Code** action, click on **Manage Secrets** and add a new secret named `RESPELL_API_KEY` with your API key as the value.
  * Access the secret in your code using `process.env.RESPELL_API_KEY`.

* **Access Workflow Data**: Use `event.inputFields` to access data from any action in your workflow, allowing you to pass dynamic data to your spell.

* **Error Handling**: Add error handling to manage API request failures or unexpected responses.

  ```javascript
  if (!response.ok) {
    console.error("API request failed:", response.statusText);
    return;
  }
  ```

* **Logging for Debugging**: Use `console.log()` statements to log information for debugging purposes. These logs can be viewed in the workflow execution history.

## Complete Example with Error Handling and Logging

```javascript
exports.main = async (event, callback) => {
  try {
    const name = event.inputFields["name"];
    const phoneNumber = event.inputFields["phone"];

    console.log(
      "Starting spell with name and phone number:",
      name,
      phoneNumber
    );

    const response = await fetch("https://v2-api.respell.ai/spells/start", {
      method: "POST",
      headers: {
        "x-api-key": process.env.RESPELL_API_KEY, // Using Secrets
        Accept: "application/json",
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        spellId: "<YOUR_SPELL_ID>",
        wait: true,
        inputs: {
          name: name,
          phone_number: phoneNumber,
        },
      }),
    });

    if (!response.ok) {
      console.error("API request failed:", response.statusText);
      return;
    }

    const result = await response.json();

    console.log("Spell result:", result);

    callback({
      outputFields: {
        transcript: result.outputs.transcript, // Adjust based on your spell's output structure
        answered_by: result.outputs.answered_by, // Adjust based on your spell's output structure
      },
    });
  } catch (error) {
    console.error("Error executing spell:", error);
  }
};
```

* **Replace `<YOUR_SPELL_ID>`** with your actual spell ID.
* **Ensure that your Respell API key is stored as a secret** named `RESPELL_API_KEY`.

## Final Steps

* **Test Your Workflow**: Before activating the workflow, test it to ensure the spell is triggered correctly and the outputs are as expected.
  * Use test data in your HubSpot workflow to simulate a real contact.
  * Check the execution logs for any errors or warnings.
* **Monitor**: Keep an eye on the workflow's execution history for any errors or issues that may arise.
  * Navigate to the **History** tab in your workflow to see past executions.
  * Review the logs for debugging information.

By following these steps, you can seamlessly integrate Respell spells into your HubSpot workflows to automate phone calls using Bland AI, enhancing your automation and efficiency.

* **Stay Updated**: Regularly check for updates to the Respell API or HubSpot features that may affect your integration.
* **Documentation**: Refer to the [Respell API Documentation](https://www.respell.ai/docs) and [HubSpot Developer Documentation](https://developers.hubspot.com/docs) for more detailed information.

***
