Metadata ingestion scripts: Python templates

Prev Next

A Python data source template builds the catalog with one script that leaves pandas DataFrames in named variables: schema_dataframe and table_dataframe are required, column_dataframe is optional. Their columns use the same names as the SQL templates' scripts: Name for schemas; Schema, Name and Type for tables; Schema, Table, Name, DataType and Sequence for columns.

This is how Validatar catalogs sources with no SQL interface: REST APIs, file shares, object storage, governance tools. This page covers Script category templates. For SQL templates, see Metadata ingestion scripts: SQL templates. Every column, type and rule in one place: Ingestion script contract reference.

Where the script lives

Open the template and go to the Metadata Ingestion tab. A Python template has one editor, Combined Script, instead of the three SQL tabs. The panel beside it lists each DataFrame variable, whether it's required, and the columns it can carry, including optional custom field columns.

Metadata Ingestion tab of a Python template

How the script runs

When an ingestion starts, Validatar runs the connection's pre-execution script (copied from the template's Defaults tab) and the Combined Script together, in that order and in the same Python scope. Anything the pre-execution script imports or defines (a pandas import, a storage client, helper functions) is available to the ingestion script. Template parameters are already set as variables before either runs.

After the script finishes, Validatar reads the three variables by name. Variable names are exact, because Python is case-sensitive. Column names inside each DataFrame are matched without regard to letter case.

The DataFrames

Variable Required One row per
schema_dataframe Yes Schema, or whatever groups your tables: a folder, an API area, a project
table_dataframe Yes Table, file, endpoint or object
column_dataframe No Column or field

If a required variable isn't set, the ingestion fails with The expected DataFrame variable table_dataframe wasn't set by the script.

schema_dataframe columns

Column Required Value
Name Yes The schema name.

table_dataframe columns

Column Required Value
Schema Yes Must match a Name in schema_dataframe. Rows that don't match are skipped.
Name Yes The table name.
Type No Table or View. Leave it out or blank for tables. Any value that doesn't start with T or V, such as Endpoint or File, fails the ingestion.
ViewDefinition No Text stored with the table, used for views.

column_dataframe columns

Column Required Value
Schema Yes The table's schema.
Table Yes Must match a table in table_dataframe. Rows that don't match are skipped.
Name Yes The column name.
DataType Yes A type name listed on the template's Data Types tab.
Sequence Yes The column's position, as an integer.
IsNullable, IsIdentity, IsPrimaryKey No True/False, 1/0 or YES/NO.
StringMaxLength, NumericPrecision, NumericScale, DateTimePrecision No Integers.
Comment No The column's description.

Any other column whose name matches a catalog custom field's reference key at that level writes its non-blank values to that field. The Windows Directory template uses this with the File Info catalog custom fields from the marketplace: its script returns file_count and total_size_bytes for each folder and file_type and date_modified for each file, and those values land in the matching fields. Columns that match no custom field are ignored.

Parameters are variables

Each template parameter is a Python variable named by its reference key. A parameter with reference key api_base_url is read as api_base_url. There is no parameters dictionary.

Parameter type Python value
String, Dropdown str
Secret str, decrypted
Integer int (0 when the value isn't a whole number)
Boolean bool

Secret values are plain text inside the script, so don't print them. Parameters are defined on the template's Defaults tab and filled in on each data source's connection.

Example: REST API

This script catalogs a REST API from its OpenAPI 2.0 (Swagger) document. Each tag becomes a schema, each GET endpoint a table, and each property of the endpoint's 200 response a column. api_base_url and api_key are parameters of the template.

import pandas as pd
import requests

headers = {"Authorization": f"Bearer {api_key}"}
response = requests.get(f"{api_base_url}/swagger/v1/swagger.json", headers=headers, timeout=30)
response.raise_for_status()
spec = response.json()

schema_rows, table_rows, column_rows = [], [], []
seen_schemas = set()

for path, methods in spec.get("paths", {}).items():
    details = methods.get("get")
    if not details:
        continue
    schema = (details.get("tags") or ["default"])[0]
    if schema not in seen_schemas:
        seen_schemas.add(schema)
        schema_rows.append({"Name": schema})

    table = path.strip("/").replace("/", "_") or "root"
    table_rows.append({"Schema": schema, "Name": table, "Type": "Table"})

    properties = details.get("responses", {}).get("200", {}).get("schema", {}).get("properties", {})
    for position, (field, info) in enumerate(properties.items(), start=1):
        column_rows.append({
            "Schema": schema,
            "Table": table,
            "Name": field,
            "DataType": info.get("type", "string"),
            "Sequence": position,
            "IsNullable": True,
        })

schema_dataframe = pd.DataFrame(schema_rows, columns=["Name"])
table_dataframe = pd.DataFrame(table_rows, columns=["Schema", "Name", "Type"])
column_dataframe = pd.DataFrame(column_rows, columns=["Schema", "Table", "Name", "DataType", "Sequence", "IsNullable"])

The DataType values here are JSON schema types (string, integer, number, boolean, array, object). Add each one to the template's Data Types tab and map it to an internal type, or those columns get no internal type.

Example: folder of CSV files

This script catalogs a folder of CSV files. The folder is the schema, each file is a table, and each header column is a column. directory_path is a String parameter of the template.

import os
import pandas as pd

schema = os.path.basename(os.path.normpath(directory_path))
table_rows, column_rows = [], []

for file_name in sorted(os.listdir(directory_path)):
    if not file_name.lower().endswith(".csv"):
        continue
    table = os.path.splitext(file_name)[0]
    table_rows.append({"Schema": schema, "Name": table, "Type": "Table"})

    sample = pd.read_csv(os.path.join(directory_path, file_name), nrows=1000)
    for position, column in enumerate(sample.columns, start=1):
        column_rows.append({
            "Schema": schema,
            "Table": table,
            "Name": column,
            "DataType": str(sample[column].dtype),
            "Sequence": position,
            "IsNullable": bool(sample[column].isna().any()),
        })

schema_dataframe = pd.DataFrame([{"Name": schema}])
table_dataframe = pd.DataFrame(table_rows, columns=["Schema", "Name", "Type"])
column_dataframe = pd.DataFrame(column_rows, columns=["Schema", "Table", "Name", "DataType", "Sequence", "IsNullable"])

str(dtype) returns pandas type names such as int64, float64, object and bool. A new Python template already maps bool, float, float64, int, int64, object and str, so these columns get an internal type with no extra setup. Add datetime64[ns] to the Data Types tab if you parse dates.

Defaults and overrides

The Combined Script on the template is the default. Each data source can replace it:

  1. Open the data source and go to Schema Metadata.
  2. Click Configure Ingestion Script.
  3. Select Override Default Script and edit the script.
  4. Set Limit Records and click Preview Script. The preview shows the schemas, tables and columns the script returns, any validation message, and whatever the script printed.

The override is stored on the data source. Data sources without an override run the template's current script.

Tips for Python ingestion scripts

Always set both required DataFrames

Create schema_dataframe and table_dataframe with their columns at the top of the script, then replace them when you have rows. An empty source then ingests as empty instead of failing on a missing variable.

Give every table a schema

Tables whose Schema isn't in schema_dataframe are skipped. If your source has no natural grouping, return one schema row named after the source and put every table in it.

Use Table as the type

Files, endpoints and objects are all tables to Validatar. Type accepts only values starting with T or V.

Fail with a clear message

Call raise_for_status() on HTTP responses and raise an exception with a readable message when the source can't be reached. The ingestion fails and shows the Python error, which is easier to act on than a half-empty catalog.

Keep the source's rate limits

Ingestion makes every request in one run. If the API limits request rates, page through results and pause between calls.

Build it up in preview

Return schema_dataframe first and preview it, then add table_dataframe, then column_dataframe. Use print() to check intermediate values: printed output shows in the preview.