> For the complete documentation index, see [llms.txt](https://developer.collibra.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developer.collibra.com/tutorials/collibra-api-task-workflow.md).

# Collibra API Task workflow

This tutorial explains how to use the **Collibra API Task** in a workflow to create a community in Collibra. You learn how to construct a JSON request body dynamically, send it to the Collibra Core REST API, and handle potential validation errors.

<img src="/files/tLebw2kzwn3sOTLnvnsg" alt="A BPMN diagram of the sample Collibra API Task workflow" width="75%">

## Learning objectives

* Configure a user task to collect community details.
* Build a dynamic JSON request body using the Groovy **JsonBuilder** in a script task.
* Use the **Collibra API Task** to interact with the Collibra Core REST API.
* Implement error handling for API responses using an **Error Boundary Event** and **JsonSlurper**.

## Prerequisites

* Access to a Collibra environment with the Workflow Designer.
* Familiarity with creating and publishing workflows.
* Basic understanding of Groovy scripting.
* Basic understanding of JSON.
* Permissions to create communities in Collibra.

## Workflow overview

This sample workflow automates the creation of a community in Collibra. If a validation error occurs during the community creation process, the workflow provides an opportunity to correct the community details and retry the creation.

The workflow includes the following main components:

* **User Task** - *Create community*: Collects the name, description, and parent community ID from the user to create a new community.
* **Script Task** - *Build request body*: Constructs the JSON payload required by the Collibra Communities API using the user-provided details.
* **Collibra API Task** - *Add community*: Sends the constructed JSON payload to the Collibra environment to create the community.
* **Error Boundary Event** - *on Add community*: Catches specific HTTP error codes returned by the Collibra API.
* **Script Task** - *Parse validation error response*: Parses the error response from the API.
* **User Task** - *Community creation - validation error*: Presents the error message to the user and allows retry.

## Create a user task for input

Start the workflow with a user task to gather the necessary information for the new community:

1. Add a **User Task** to your workflow and name it *Create community*.
2. Configure the task form to collect the following information:
   * **Text** - *Community Name*: Map this to a *communityName* variable.
   * **Multiline Text** - *Description*: Map this to a *description* variable.
   * **Community** - *Parent Community ID*: Map this to a *parentCommunity* variable.

<img src="/files/4eWqCGMHLsnmSMTm6i7K" alt="A user task that collects information to create a community in a Collibra API Task workflow" width="50%">

## Build the API request body

After the user provides the community details, use a script task to construct the JSON request body dynamically:

1. Add a **Script Task** after the **Create community** user task and name it *Build request body*.
2. In the script task, enter the following Groovy code. This code uses **JsonBuilder** to create the JSON payload. Optional fields are only added if a value is present in the corresponding process variable.

```groovy
import groovy.json.JsonBuilder

JsonBuilder json = new JsonBuilder()
json {
    name communityName

    if (execution.getVariable("description")) {
        description execution.getVariable("description")
    }
    if (execution.getVariable("parentCommunity")) {
        parentId execution.getVariable("parentCommunity")
    }
}

String jsonBody = json.toPrettyString()
execution.setVariable("cummunityRequest", jsonBody)
```

Explanation:

* **JsonBuilder** helps create JSON objects programmatically.
* The **name** field is always included.
* The **description** and **parentId** fields are conditionally added if their corresponding process variables, **description** and **parentCommunity**, have values.
* The **toPrettyString()** method formats the JSON for readability.
* The resulting JSON string is stored in the **communityRequest** workflow variable.

### The JSON output

Given the following variable values:

* **communityName** = "Sample Community"
* **description** = "This is a sample community description."
* **parentCommunity** = "00000000-0000-0000-0000-000000900001"

The **communityRequest** variable will contain the following JSON object:

```json
{
  "communityName": "Sample Community",
  "description": "This is a sample community description.",
  "parentCommunity": "00000000-0000-0000-0000-000000900001",
}
```

## Call the Collibra API

Use a **Collibra API Task** to send the prepared JSON request to the Collibra Core REST API endpoint for creating communities:

1. Add a **Collibra API Task** activity after the **Build request body** script task and name it *Add community*.
2. Configure the task properties:
   * **Request Path**: */communities*. This path corresponds to the **POST /communities** endpoint of the Collibra Core REST API for creating communities. The host is added automatically by the Collibra API Task.
   * **Request Body**: Enter the **communityRequest** process variable.
   * **Handle Status Code**: *400*. This specifies that if the API returns an HTTP 400 Bad Request status code, the workflow should trigger the associated error handling path.
   * **Response Variable Name**: *response*. The full API response body will be stored in this process variable.

<img src="/files/ksYGvcepmBtzh2NMPudh" alt="The properties of a Collibra API Task that creates a community" width="50%">

## Implement error handling

Configure an **Error Boundary Event** on the **Add community** task to catch specific API errors, such as validation failures:

1. Attach an **Error Boundary Event** to the **Add community** task.
2. Configure the event properties:
   * **Error code**: *HTTP400*. This matches the HTTP status code specified in the **Handle Status Code** property of the **Add community** task. When a 400 error occurs, this error boundary event will be triggered.
   * **Error variable name**: *validationError*.

<img src="/files/IDcSUDPCqsJ1kgB5wSan" alt="" width="75%">

## Parse validation errors and allow retry

When an HTTP 400 error occurs, the API typically returns a JSON response containing details about the validation error. Use a script task to parse this response and provide feedback to the user:

{% stepper %}
{% step %}
Connect the **Error Boundary Event** to a **Script Task** and name it *Parse validation error response*.
{% endstep %}

{% step %}
In this script task, enter the following Groovy code. This code uses **JsonSlurper** to parse the **response** process variable, which contains the API error response, and extract relevant error details.

```groovy
import groovy.json.JsonSlurper

Object errorResponseObject = new JsonSlurper().parseText(response)

execution.setVariable("errorStatusCode", errorResponseObject.statusCode)
execution.setVariable("errorMessage", errorResponseObject.userMessage)
execution.setVariable("errorCode", errorResponseObject.errorCode)
```

Explanation:

* **JsonSlurper** parses JSON strings into Groovy objects from the **response** variable, populated by the Collibra API Task.
* Common fields in Collibra API error responses, such as **statusCode**, **userMessage**, and **errorCode**, are extracted and stored in corresponding process variables.

{% tabs %}
{% tab title="Example" icon="glasses-round" %}
Parsing more complex JSON

If your API responses contain deeply nested JSON, **JsonSlurper** can navigate through it:

```groovy
import groovy.json.JsonSlurper
import java.util.Map

String json = '''
{
  "level1": {
    "level2": {
      "level3": {
        "level4": {
           "message": "Deep structure works!"
        }
      }
    }
  }
}
'''

Map<String, Object> parsed = new JsonSlurper().parseText(json)
loggerApi.info(parsed.level1.level2.level3.level4.message)
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="Example" icon="glasses-round" %}
Parsing JSON arrays

You can also parse and access elements within JSON arrays:

```groovy
import groovy.json.JsonSlurper
import java.util.List

String json = '''
[
  {
    "name": "value1"
  },
  {
    "name": "value2"
  }
]
'''

List<Object> parsed = new JsonSlurper().parseText(json)
loggerApi.warn("[TEST] JSON: "+parsed[1].name)
```

{% endtab %}
{% endtabs %}
{% endstep %}

{% step %}
After the **Parse validation error response** script task, add a **User Task** and name it *Community creation - validation error*.
{% endstep %}

{% step %}
In this user task, show the **errorMessage** process variable to the user. Include options for the user to go back to the **Create community** task to correct the information or to cancel the workflow.
{% endstep %}

{% step %}
Connect the **Community creation - validation error** user task back to the **Create community** user task to allow the user to retry.
{% endstep %}
{% endstepper %}

## Success outcome

If the **Add community** Collibra API Task executes without triggering the error boundary event, for example if the HTTP status code is 2xx, it signifies a successful community creation. From this point, you can end the workflow or add further steps, such as sending a success notification or logging the new community details. The newly created community will be visible in Collibra.

## Testing and verification

{% stepper %}
{% step %}
Publish the workflow to your Collibra environment.
{% endstep %}

{% step %}
Test the successful creation path:

1. Start the workflow.
2. Enter valid community details, such as a unique name, optional description, and a valid parent community if needed.
3. Verify that the workflow creates the community.
   {% endstep %}

{% step %}
Test the error handling path:

1. Start the workflow.
2. Enter invalid community details that would trigger a 400 error, such as a community name that already exists.
3. Verify that the **Community creation - validation error** user task shows the appropriate error message, and that you can retry the creation.
   {% endstep %}
   {% endstepper %}

## Summary

You have successfully built a workflow that uses the Collibra API Task to create communities and handle potential validation errors. This demonstrates a powerful pattern for integrating Collibra workflows with its REST API for various data management and manipulation tasks.

## Additional resources

Download the [Collibra API Task workflow](https://cdn.collibra.com/developer/SimpleCollibraTask.zip).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://developer.collibra.com/tutorials/collibra-api-task-workflow.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
