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

# Create a Test Definition

> Create a custom test definition for data quality validation

# Create a Test Definition

Create a custom test definition to define organization-specific data quality validation logic.

## Body Parameters

**name** `string` *required*

Name of the test definition. Must be unique across all test definitions.

**displayName** `string`

Human-readable display name for the test definition.

**description** `string`

Description of what this test validates, in Markdown format.

**entityType** `string` *required*

The entity type this test targets: `TABLE` or `COLUMN`.

**testPlatforms** `array` *required*

Array of supported test platforms. Typically `["OpenMetadata"]`.

**supportedDataTypes** `array`

Array of data types this test can be applied to, for example `STRING`, `INT`, `DOUBLE`, `VARCHAR`, `CHAR`, `TEXT`, `NUMBER`, `FLOAT`, `BOOLEAN`. Only applicable when `entityType` is `COLUMN`.

**parameterDefinition** `array`

Array of parameter definitions that this test accepts.

**properties**

**name** `string` *required*

Name of the parameter.

**dataType** `string` *required*

Data type of the parameter, for example `INT`, `STRING`, `BOOLEAN`, `ARRAY`, `TABLE`.

**required** `boolean`

Whether this parameter is required when creating a test case. Defaults to `false`.

**description** `string`

Description of the parameter.

**sqlExpression** `string`

SQL template for custom SQL-based test definitions. OpenMetadata renders the template with Jinja2, so every placeholder must use double curly braces:

* `{{ table_name }}`: the table the test case runs against.
* `{{ column_name }}`: the column the test case runs against. Available only when `entityType` is `COLUMN`.
* `{{ paramName }}`: the value of a parameter declared in `parameterDefinition`.

OpenMetadata doesn't substitute single-brace placeholders, which produce invalid SQL. By default, the test passes only when the rendered query returns 0 rows. To tolerate some violating rows, set a failure threshold. `table_name` is reserved for all definitions, and `column_name` is also reserved when `entityType` is `COLUMN`. Don't use reserved names as parameter names. For more information, see [Custom SQL Test Definitions](#custom-sql-test-definitions).

**validatorClass** `string`

Class name of the validator that runs the test. For a custom SQL test definition, set one of the following values. The OpenMetadata UI sets the same values when you create a custom SQL test definition:

* `ColumnRuleLibrarySqlExpressionValidator`: use when `entityType` is `COLUMN`.
* `TableRuleLibrarySqlExpressionValidator`: use when `entityType` is `TABLE`.

Built-in test definitions use their own validators, which you can't select for a custom definition. The server accepts any string for this field, so always set it explicitly for SQL-based definitions.

**dataQualityDimension** `string`

Name of the data quality dimension that test cases of this definition use by default. Accepts a built-in dimension (`Completeness`, `Accuracy`, `Consistency`, `Validity`, `Uniqueness`, `Integrity`, `SQL`, or `NoDimension`) or any custom dimension registered in **Settings** > **Preferences** > **Data Quality**.

**supportedServices** `array`

Names of the services this test definition supports. When empty, all services are supported. Defaults to `[]`.

**domains** `array`

Fully qualified names of the domains the test definition belongs to.

**owners** `array`

Array of owner references (users or teams) to assign.

**properties**

**id** `string`

UUID of the owner entity.

**type** `string`

Type of owner entity, for example `user`, `team`.

**name** `string`

Name of the owner entity.

```python POST /v1/dataQuality/testDefinitions theme={null}
from metadata.sdk import configure
from metadata.sdk.entities import TestDefinitions
from metadata.generated.schema.api.tests.createTestDefinition import CreateTestDefinitionRequest

configure(
    host="https://your-company.open-metadata.org/api",
    jwt_token="your-jwt-token"
)

request = CreateTestDefinitionRequest(
    name="columnValuesMaxLength",
    displayName="Column Values Max Length",
    description="Fails when a value is longer than the allowed length",
    entityType="COLUMN",
    testPlatforms=["OpenMetadata"],
    dataQualityDimension="SQL",
    supportedDataTypes=["STRING", "VARCHAR", "TEXT"],
    sqlExpression="SELECT * FROM {{ table_name }} WHERE LENGTH({{ column_name }}) > {{ maxLength }}",
    validatorClass="ColumnRuleLibrarySqlExpressionValidator",
    parameterDefinition=[
        {
            "name": "maxLength",
            "dataType": "INT",
            "required": True,
            "description": "Maximum allowed length"
        },
        {
            "name": "threshold",
            "dataType": "NUMBER",
            "required": False,
            "description": "Number of failing rows to tolerate before the test fails"
        },
        {
            "name": "thresholdUnit",
            "dataType": "STRING",
            "required": False,
            "description": "ABSOLUTE for a row count or PERCENTAGE for a share of rows"
        }
    ]
)

test_def = TestDefinitions.create(request)
print(f"Created: {test_def.name.root}")
```

```java POST /v1/dataQuality/testDefinitions theme={null}
import java.util.List;
import org.openmetadata.schema.api.tests.CreateTestDefinition;
import org.openmetadata.schema.tests.TestCaseParameter;
import org.openmetadata.schema.tests.TestPlatform;
import org.openmetadata.schema.type.ColumnDataType;
import org.openmetadata.schema.type.TestCaseParameterDataType;
import org.openmetadata.schema.type.TestDefinitionEntityType;

// client is an initialized OpenMetadataClient.
var request = new CreateTestDefinition()
    .withName("columnValuesToMatchBusinessRule")
    .withDisplayName("Column Values To Match Business Rule")
    .withDescription("Validates that column values conform to a custom business rule regex pattern")
    .withEntityType(TestDefinitionEntityType.COLUMN)
    .withTestPlatforms(List.of(TestPlatform.OPEN_METADATA))
    .withSupportedDataTypes(List.of(
        ColumnDataType.STRING, ColumnDataType.VARCHAR, ColumnDataType.TEXT))
    .withParameterDefinition(List.of(
        new TestCaseParameter()
            .withName("regexPattern")
            .withDataType(TestCaseParameterDataType.STRING)
            .withRequired(true)
            .withDescription("The regex pattern to match against"),
        new TestCaseParameter()
            .withName("threshold")
            .withDataType(TestCaseParameterDataType.INT)
            .withRequired(false)
            .withDescription("Maximum number of non-matching values allowed")));

var testDefinition = client.testDefinitions().create(request);
```

```bash POST /v1/dataQuality/testDefinitions theme={null}
curl -X POST "{base_url}/api/v1/dataQuality/testDefinitions" \
  -H "Authorization: Bearer {access_token}" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "columnValuesMaxLength",
    "displayName": "Column Values Max Length",
    "description": "Fails when a value is longer than the allowed length",
    "entityType": "COLUMN",
    "testPlatforms": ["OpenMetadata"],
    "dataQualityDimension": "SQL",
    "supportedDataTypes": ["STRING", "VARCHAR", "TEXT"],
    "sqlExpression": "SELECT * FROM {{ table_name }} WHERE LENGTH({{ column_name }}) > {{ maxLength }}",
    "validatorClass": "ColumnRuleLibrarySqlExpressionValidator",
    "parameterDefinition": [
      {"name": "maxLength", "dataType": "INT", "required": true, "description": "Maximum allowed length"},
      {"name": "threshold", "dataType": "NUMBER", "required": false, "description": "Number of failing rows to tolerate before the test fails"},
      {"name": "thresholdUnit", "dataType": "STRING", "required": false, "description": "ABSOLUTE for a row count or PERCENTAGE for a share of rows"}
    ]
  }'
```

```json Response theme={null}
{
  "id": "b7c4e912-3a1f-4d6e-9c2b-8f5a7d3e1b4c",
  "name": "columnValuesToMatchBusinessRule",
  "displayName": "Column Values To Match Business Rule",
  "fullyQualifiedName": "columnValuesToMatchBusinessRule",
  "description": "Validates that column values conform to a custom business rule regex pattern",
  "version": 0.1,
  "updatedAt": 1769982700000,
  "updatedBy": "admin",
  "testPlatforms": ["OpenMetadata"],
  "supportedDataTypes": ["STRING", "VARCHAR", "TEXT"],
  "parameterDefinition": [
    {
      "name": "regexPattern",
      "dataType": "STRING",
      "required": true,
      "description": "The regex pattern to match against"
    },
    {
      "name": "threshold",
      "dataType": "INT",
      "required": false,
      "description": "Maximum number of non-matching values allowed"
    }
  ],
  "entityType": "COLUMN",
  "provider": "user",
  "deleted": false
}
```

***

## Returns

Returns the created test definition object with all specified properties and system-generated fields.

## Response

**id** `string`

Unique identifier for the test definition (UUID format).

**name** `string`

Test definition name.

**fullyQualifiedName** `string`

Fully qualified name (same as name for test definitions).

**displayName** `string`

Human-readable display name.

**description** `string`

Description of what the test validates.

**entityType** `string`

Target entity type: `TABLE` or `COLUMN`.

**testPlatforms** `array`

Supported test platforms.

**supportedDataTypes** `array`

Data types this test can be applied to.

**parameterDefinition** `array`

Parameters accepted by this test definition.

**properties**

**name** `string`

Parameter name.

**dataType** `string`

Data type of the parameter.

**required** `boolean`

Whether this parameter is required.

**description** `string`

Description of the parameter.

**sqlExpression** `string`

SQL template for custom SQL-based test definitions.

**validatorClass** `string`

Validator that runs the test.

**dataQualityDimension** `string`

Data quality dimension the test belongs to.

**provider** `string`

Always `user` for custom test definitions.

**version** `number`

Version number for the entity (starts at 0.1).

***

## Custom SQL Test Definitions

A custom test definition is a reusable SQL template. To run a one-off SQL query on a single table, such as the **Custom SQL Query** test type in the UI, create a test case with the built-in `tableCustomSQLQuery` definition instead. For more information, see [Custom SQL Test Cases](https://docs.open-metadata.org/v2.1.x/api-reference/data-quality/test-cases/create.md#custom-sql-test-cases).

To create a test definition that runs your own SQL, set `sqlExpression` and declare every `{{ paramName }}` placeholder in `parameterDefinition`. The following request creates a column-level test that fails when any value in the column is longer than a limit:

```bash theme={null}
curl -X POST "{base_url}/api/v1/dataQuality/testDefinitions" \
  -H "Authorization: Bearer {access_token}" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "columnValuesMaxLength",
    "displayName": "Column Values Max Length",
    "description": "Fails when a value is longer than the allowed length",
    "entityType": "COLUMN",
    "testPlatforms": ["OpenMetadata"],
    "dataQualityDimension": "SQL",
    "supportedDataTypes": ["STRING", "VARCHAR", "TEXT"],
    "sqlExpression": "SELECT * FROM {{ table_name }} WHERE LENGTH({{ column_name }}) > {{ maxLength }}",
    "validatorClass": "ColumnRuleLibrarySqlExpressionValidator",
    "parameterDefinition": [
      {"name": "maxLength", "dataType": "INT", "required": true, "description": "Maximum allowed length"},
      {"name": "threshold", "dataType": "NUMBER", "required": false, "description": "Number of failing rows to tolerate before the test fails"},
      {"name": "thresholdUnit", "dataType": "STRING", "required": false, "description": "ABSOLUTE for a row count or PERCENTAGE for a share of rows"}
    ]
  }'
```

How OpenMetadata evaluates the SQL:

* **Pass condition**: By default, the test case passes only when the rendered query returns 0 rows. Write the query so that it returns the rows that violate the rule.
* **Failure threshold**: To let a test case tolerate some violating rows, declare both `threshold` and `thresholdUnit` in `parameterDefinition`. The server ignores `threshold` unless the definition declares `thresholdUnit`. For more information, see [Failure Thresholds](#failure-thresholds).
* **Reserved names**: `table_name` is reserved for table-level definitions. `table_name` and `column_name` are reserved for column-level definitions. Do not declare them in `parameterDefinition`, because the validator supplies their values at runtime.
* **Parameters**: A test case supplies values for `{{ paramName }}` through `parameterValues`. For more information, see [Create a Test Case](https://docs.open-metadata.org/v2.1.x/api-reference/data-quality/test-cases/create.md#custom-sql-test-cases).

### Failure Thresholds

A failure threshold is the number of violating rows a test case tolerates before it fails. It turns the default "fail on any row" pass condition into a tolerance.

| Parameter | Data type | Description |
| - | - | - |
| `threshold` | `NUMBER` | Tolerated violations. Must be a non-negative number. Defaults to `0`. |
| `thresholdUnit` | `STRING` | `ABSOLUTE` reads `threshold` as a row count. `PERCENTAGE` reads it as a share of the evaluated rows, up to `100`. |

The test case supplies the values in `parameterValues`. For more information, see [Create a Test Case](https://docs.open-metadata.org/v2.1.x/api-reference/data-quality/test-cases/create.md#custom-sql-test-cases) and [Failure Thresholds](https://docs.open-metadata.org/v2.1.x/how-to-guides/data-quality-observability/quality/failure-thresholds.md).

## Create or Update (PUT)

Use `PUT /v1/dataQuality/testDefinitions` instead of `POST` to perform an upsert. If a test definition with the same name already exists, it will be updated; otherwise, a new test definition is created. The request body is the same as `POST`.

```bash theme={null}
curl -X PUT "{base_url}/api/v1/dataQuality/testDefinitions" \
  -H "Authorization: Bearer {access_token}" \
  -H "Content-Type: application/json" \
  -d '{ ... same body as POST ... }'
```

> [!NOTE]
>
> `PUT` will not return a `409` conflict error if the entity already exists. It will update the existing entity instead.

***

## Error Handling

| Code | Error Type | Description |
| - | - | - |
| `400` | `BAD_REQUEST` | Invalid request body or missing required fields |
| `401` | `UNAUTHORIZED` | Invalid or missing authentication token |
| `403` | `FORBIDDEN` | User lacks permission to create test definitions |
| `409` | `ENTITY_ALREADY_EXISTS` | Test definition with same name already exists (POST only) |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.