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

# Quick scripts and API examples

> Automate API calls and integrate them into workflows or applications, and get working examples for quick application. 

Here are practical examples of using Next Matter's API for common automation tasks.

## Start instance and complete a step (script)

Use this Python script to automatically create workflow instances and complete steps programmatically.

**Use case:** Create a new employee onboarding workflow, automatically complete the first step  by, for example, automatically filling in personal details, and advance to the next step.

1. The script creates an instance with process\_id and tags. The name is created automatically as per Next Matter settings.
   * Uses the API endpoint: [https://core.nextmatter.com/api/instances/](https://core.nextmatter.com/api/instances/)
   * Returns:
     * Instance ID (for reference)
     * Instance URL (for navigation)
     * If an error occurs, it prints the error message.
2. Fills the step with the required input data and marks a step in the workflow as completed.
   * Uses the API endpoint: [https://core.nextmatter.com/api/instances//complete\_step/](https://core.nextmatter.com/api/instances/%7Binstance_id%7D/complete_step/)
   * Requires:
     * Instance ID (to specify the workflow instance)
     * Step ID (which step to complete)
     * List of form fields ( with input data required for the step to complete)
       If successful, shows a completion message.

<Accordion title="Script">
  <CodeGroup>
    ```python python theme={null}
    # Next Matter API Key (Replace with actual API Key)
    API_KEY = "API_KEY_VALUE"

    # Workfow and Step IDs (Replace with actual values)
    PROCESS_ID = "WORKFLOW_ID_VALUE"
    STEP_ID = "STEP_ID_VALUE"

    # Next Matter API Base URL
    BASE_URL = "https://core.nextmatter.com/api/"

    # Headers for authentication
    HEADERS = {
        "Authorization": f"Api-Key {API_KEY}",
        "Content-Type": "application/json"
    }

    def create_instance(process_id: str,  tags: list = None):
        """
        Creates a new instance of a Next Matter workflow. 
        The name of the instance will be automatically created by Next Matter.

        :param process_id: ID of the workflow to create an instance for.
        :param tags: Optional list of tags to assign to the instance.
        :return: Instance ID and Instance URL if successful, None otherwise.
        https://help.nextmatter.com/reference/instances_create
        """
        url = f"{BASE_URL}instances/"
        payload = {
            "process": f"https://core.nextmatter.com/api/processes/{process_id}/"
        }

        if tags:
            payload["tags"] = tags

        response = requests.post(url, json=payload, headers=HEADERS)

        if response.status_code == 201:
            instance_data = response.json()
            print(f"✅ Instance created successfully: {instance_data['id']}")
            return instance_data["id"], instance_data["url"]
        else:
            print(f"❌ Error creating instance: {response.text}")
            return None, None

    def complete_step(instance_id: str, step_id: int, actions: list):
        """
        Completes a step in a given Next Matter instance.

        :param instance_url: URL of the instance where the step should be completed.
        :param step_id: ID of the step to be completed.
        :param actions: List of form fields (each containing an action_id and input_object).
        :return: API response data.
        https://help.nextmatter.com/reference/instances_complete_step
        """
        url = f"{BASE_URL}instances/{instance_id}/complete_step/"
        payload = {
            "step_id": step_id,
            "actions": actions
        }

        response = requests.post(url, json=payload, headers=HEADERS)

        if response.status_code == 200:
            print("✅ Step completed successfully.")
            return response.json()
        else:
            print(f"❌ Error completing step: {response.text}")
            return None

    if __name__ == "__main__":
        # Example usage
        instance_id, instance_url = create_instance(PROCESS_ID, instance_name="Test Instance")

        if instance_url:
            # Modify the form field list according to your workflow's requirements
            actions = [
                {
                    "action_id": 123456,  # Replace with actual action ID
                    "input_object": {"inputValue": "Value 1"} # Key (i.e. inputValue) depends on the type of form field
                },
                {
                    "action_id": 789012,  # Replace with actual action ID
                    "input_object": {"itemSelected": "Value 2"}
                }
            ]

            complete_step(str(instance_id), STEP_ID, actions)
    ```
  </CodeGroup>
</Accordion>

## Filter instances by max total runtime

**Use case:** Find all workflow instances that completed within a specific time frame.

You can use [this API call](/reference/processes_instances_list) to get filtered instances of a workflow. In the example below, we're filtering for all instances with a maximum total runtime of 50 seconds.

<CodeGroup>
  ```ruby HTTP theme={null}
  https://core.nextmatter.com/api/processes/WORKFLOW_ID/instances/?total_runtime_max=00:50
  ```

  ```Text Response theme={null}
  {
      "count": NUMBER,
      "next": null,
      "previous": null,
      "results": [
          {
              "id": ID_VALUE,
              "name": "NAME_VALUE",
              "status": "completed",
              "public_url": null
          },
          {
              "id":ID_VALUE,
              "name": "NAME_VALUE",
              "status": "completed",
              "public_url": null
          }
      ]
  }
  ```
</CodeGroup>

Here are some other examples of values to use:

* 01 09:30 - 1 day and 9 minutes and 30 seconds
* 02:30:00 - 2 hours and 30 minutes (and 0 seconds)
* PT50M - 50 minutes (as per ISO 8601 duration formats)
* PT1H30S - 1 hour and 30 seconds (as per ISO 8601 duration formats)
