Bỏ qua

Artifact Operate API

Warning

The current page still doesn't have a translation for this language.

But you can help translating it: Contributing.

Use the Artifact Operate API to change a stored artifact of a finished task and get the result in the same HTTP response. The stored artifact is the template of the call: a test automation job makes many variants of it, one for each test case.

The API does not run a generate model and does not store the result. It reads the stored artifact, applies your operations in memory and returns the text as a resulting artifact.

Authentication

Create a project access token for the target project and send it as a Bearer token:

1
2
3
4
export DATAMIMIC_URL="https://datamimic.example.com"
export PROJECT_ID="your-project-id"
export TASK_ID="id-of-a-finished-task"
export PROJECT_TOKEN="your-project-access-token"

The token can access only its own project. Treat it as a secret.

PROJECT_ID is the Project ID on the project settings page. Copy TASK_ID with Copy Task ID in the task list, or use the task_id that the generate call returns.

Endpoint

1
POST /api/v2/projects/{project_id}/tasks/{task_id}/artifacts/operate

task_id is a task of the project with the status SUCCESS or SUCCESS_WITH_WARNING. The rows read its stored artifacts.

Use GET /api/v2/projects/{project_id}/tasks/{task_id}/artifacts/metadata to list the artifacts. The artifact value is name and type joined with a dot: "name": "order" and "type": "xml" give order.xml.

1
2
3
4
curl --fail-with-body --silent \
  "$DATAMIMIC_URL/api/v2/projects/$PROJECT_ID/tasks/$TASK_ID/artifacts/metadata" \
  -H "Authorization: Bearer $PROJECT_TOKEN" \
  | jq --raw-output '.artifacts[] | "\(.name).\(.type)"'

Select the latest task

Use latest instead of a task ID when the test job does not know the source task:

1
POST /api/v2/projects/{project_id}/tasks/latest/artifacts/operate

The server checks at most 20 generate tasks in this project. Eligible types are standard, infinite, timed_5min, timed_30min, timed_1hour, timed_4hour, timed_8hour and timed_24hour. A task must have status SUCCESS or SUCCESS_WITH_WARNING and a date_done timestamp. Tasks are sorted by date_done DESC, id DESC, so the most recently finished task comes first.

The first task that has all files named in the rows is selected. The files must belong to the same task. Missing files cause the server to check the next candidate. If none of the 20 candidates matches, the response is 404 NO_MATCHING_TASK. File format, size and operation errors still use the normal operate error contract; they do not cause selection of an older task.

The successful response returns task_id, the resolved source ID, as well as operate_id, the call ID. Store task_id and use it for the rest of the test run:

1
2
3
4
5
6
7
curl --fail-with-body --silent --request POST \
  "$DATAMIMIC_URL/api/v2/projects/$PROJECT_ID/tasks/latest/artifacts/operate" \
  -H "Authorization: Bearer $PROJECT_TOKEN" \
  -H 'Content-Type: application/json' \
  --data '{"rows":[{"id":"case-1","artifact":"xml/order.xml","operations":[]}]}' \
  --output response.json
TASK_ID=$(jq --exit-status --raw-output '.task_id' response.json)

The artifact list, single-file download and ZIP download also accept latest. A single-file download selects a task that has that file. A full list or ZIP selects a task that has at least one artifact. JSON responses return task_id; downloads return X-Datamimic-Task-Id. If a proxy removes custom headers, obtain the ID from JSON first.

Two calls to latest can select different tasks, because a run can finish between calls or the calls can request different files. Selection does not preserve the task or prevent housekeeping from deleting files. Logs and task metadata still require an explicit ID.

Keep the source task

The artifacts of a task do not change, but housekeeping archives them when the task is older than the full retention period. The task keeps its status SUCCESS. An operate call then returns 404 NOT_FOUND for the stored artifact. A worker can still operate from its cache until it removes the stored artifact. Do not rely on this.

Before you use the stored artifacts of a task, set its preserve flag. Housekeeping then leaves the artifacts of the task in place. Use the preserve action in the task menu of the UI, or call the API:

1
2
3
4
5
curl --fail-with-body --silent --request PUT \
  "$DATAMIMIC_URL/api/v2/projects/$PROJECT_ID/tasks/$TASK_ID/preserve" \
  -H "Authorization: Bearer $PROJECT_TOKEN" \
  -H 'Content-Type: application/json' \
  --data '{"preserve": true}'

Request

Send a JSON body with the Content-Type: application/json header.

Field Type Rule
operation_not_matched_action string Optional. warn (default) or error. It sets what happens when an operation matches nothing.
rows list 1 to 100 rows.
rows[].id string Your name for the row, up to 256 characters. The response returns it unchanged.
rows[].artifact string The relative path of a stored artifact from metadata path, for example xml/order.xml. Up to 32 segments; the full object key (task_id/path) is at most 1024 UTF-8 bytes. Empty, dot, parent, backslash and control-character segments are rejected.
rows[].operations list of strings Operation commands, for example set(path, value), applied in the listed order.

A field that is not in this table gives 422. A misspelled field never falls back to a default.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
{
  "operation_not_matched_action": "warn",
  "rows": [
    {
      "id": "case-1",
      "artifact": "order.xml",
      "operations": ["set(//order/id, '2')", "delete(//order/note)"]
    },
    {
      "id": "case-2",
      "artifact": "order.xml",
      "operations": ["set(//order/missing, 'x')"]
    }
  ]
}

Each row starts from its stored artifact. One row never sees the changes of another row. Many rows can use the same stored artifact.

Operation values are literals. The API never evaluates an expression in a value. Function operations ({functionName}) are not available in this API. They fail with the kind execution.

The command splits at the first comma. The path cannot contain a comma; the value can. The value is read as JSON when it can be: 5 is a number, true is a boolean, null is null. Other text is a string.

Quote the value to write a string: upsertProperty($.customer.zip, '53111') writes the string "53111", and upsertProperty($.customer.zip, 53111) writes a number. The quotes are removed. In XML, the value is written as text, and null gives an empty element.

An XML artifact uses XPath paths. A JSON artifact uses JSONPath paths. A JSON example: set($.a.b, 5). A path that starts with /, ., *, @ or ( is read from the root as written. A path that starts with a name is read like //path.

A path must select elements. To change an attribute, select its element and use upsertAttribute, for example upsertAttribute(//order, kind=test). For the operations, the path rules and examples, see the operation reference.

The operation reference also describes the <operate> element of a model. In that reference, a "control cell" is one entry of operations. Read only the sections "Path rules", "Values" and the operation list. This API accepts warn and error only. The value ignore gives 422. The outcomes in the response replace the warnings that the reference names.

Response

The response has status 200. It lists one resulting artifact for each row, in request order.

Field Meaning
task_id The resolved source task ID. Reuse it for the rest of the test run.
operate_id The correlation id of this request. See Audit record.
artifacts[].id The id of the row.
artifacts[].content The resulting text.
artifacts[].media_type application/xml or application/json, from the stored artifact.
artifacts[].outcomes One entry for each requested operation, with the path of an operation that had no effect. See Outcomes.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
  "task_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "operate_id": "2f6c1d0e-8a3b-4c57-9e21-5b7d4a9c1f30",
  "artifacts": [
    {
      "id": "case-1",
      "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<order>\n  <id>2</id>\n  </order>\n",
      "media_type": "application/xml",
      "outcomes": [
        {"operation_index": 0, "command": "set(//order/id, '2')", "status": "applied", "path": null},
        {"operation_index": 1, "command": "delete(//order/note)", "status": "applied", "path": null}
      ]
    },
    {
      "id": "case-2",
      "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<order>\n  <id>1</id>\n  <note>first</note>\n</order>\n",
      "media_type": "application/xml",
      "outcomes": [
        {"operation_index": 0, "command": "set(//order/missing, 'x')", "status": "not_matched", "path": "//order/missing"}
      ]
    }
  ]
}

A delete keeps the whitespace of the stored artifact around the deleted element. That is why case-1 ends with </order>.

The same input gives the same output. The stored artifact is read as UTF-8 and the output declares UTF-8. The operate call keeps the XML declaration of the stored artifact. It changes a declared encoding other than UTF-8 to UTF-8, also when no operation changes the document. A JSON number that no operation changes keeps its written form: 100.00 stays 100.00.

Outcomes

operation_index is the position of the command in the operations list of the row. The first command has the index 0.

Outcome status Meaning
applied The operation ran on its target. A target that already has the requested state also gives applied.
not_matched The path matched nothing.
skipped_deleted_path An earlier operation of the row deleted the path. The operation did nothing.

With warn, the path of an outcome that is not applied is the path that matched nothing. The path of an applied outcome is null.

With error, the request fails with status 422 for the first operation that is not applied. No artifact is returned.

An operation that cannot be parsed is always an error, also with warn.

Limits

Limit Value Result when exceeded
Rows for each request 100 413
Body size 1 MiB 413
Length of rows[].id 256 characters 422
Artifact path 32 segments; 1024 UTF-8 bytes including task ID and slash 400
Size of one stored artifact 8 MiB 413
Stored artifact size summed over the rows 64 MiB 413
Resulting artifact size summed over the rows (UTF-8) 64 MiB 413
Operate call time 5 s soft, 10 s hard 504

The API is synchronous. It waits up to 10 seconds for the result. Split a large test suite into several requests. The limits keep one call inside the 10 s wait of a synchronous HTTP request and keep one call from blocking the operate workers.

The operate worker reads the size of each stored artifact before it loads one. Each row counts the size of its stored artifact, also when many rows use the same stored artifact. For example, 100 rows of a 1 MiB artifact count 100 MiB and give 413.

An operation writes its value into every match, so a small stored artifact can give a large resulting artifact. For example, one set of a 10 KB value into 1,000 matches gives about 10 MB. The operate worker builds the rows one at a time and adds the UTF-8 size of each resulting artifact. The row that brings the sum over 64 MiB fails the request with 413, and row_index names that row. The worker checks a row after it builds the row, so until a later release adds a check inside a row, only the worker memory limits one very large row.

One failing row fails the whole request. The response then holds no artifact of any row.

Errors

An error response is JSON with the fields detail and code. An error after the server queued the operate call also has operate_id. These are 404 for a stored artifact, 413 for an artifact or response size, 422 for a row, 500 INTERNAL_SERVER_ERROR from the operate worker, and 504.

Status code Cause What to do
400 INVALID_FILE_PATH An artifact path is invalid. Use the relative path from the artifact metadata. Correct the path before retrying.
400 BAD_REQUEST The task has not finished with SUCCESS or SUCCESS_WITH_WARNING. Use a task with SUCCESS or SUCCESS_WITH_WARNING. Do not retry.
401 UNAUTHORIZED The token is missing or not valid, it is the access token of another project, or the user of the token is not a member of the project. Check the token, its project and its expiry date. Do not retry.
403 AUTH_ORIGIN_FORBIDDEN A browser session sent the request from an origin that is not allowed. A call with a token does not get this error. Use a token.
404 PROJECT_NOT_FOUND The project does not exist. Check the project id.
404 NO_MATCHING_TASK No candidate has all requested files within the latest 20 eligible tasks. Check the artifacts or use a known task ID.
404 NOT_FOUND The task or a stored artifact does not exist. Check the task id and the artifact name. Housekeeping can archive a stored artifact, see Keep the source task.
413 PAYLOAD_TOO_LARGE The body is larger than 1 MiB, or the request has more than 100 rows. A stored artifact is larger than 8 MiB, or the stored artifacts of all rows are larger than 64 MiB together: detail names the artifact. The resulting artifacts of all rows are larger than 64 MiB together: row_index names the row. Split the rows into several requests. Use stored artifacts of 8 MiB or less. Write smaller values into fewer matches.
422 VALIDATION_ERROR The body is not valid, for example it has an unknown field (the response lists errors), or a row failed (see below). Fix the body, or the operation operation_index of the row row_index. Do not retry unchanged.
500 INTERNAL_SERVER_ERROR The operate call failed for an unexpected reason. Retry once. If it fails again, give operate_id (when present) to your administrator.
500 USER_EMAIL_MISSING The user of the token has no email address. Ask your administrator to add an email address to the user of the token.
503 SERVICE_UNAVAILABLE The operate queue is not reachable. Retry after a few seconds, with a backoff.
504 GATEWAY_TIMEOUT The operate call did not finish in 10 seconds: it reached the soft time limit, no worker serves the operate queue, or the request waited too long in the queue. The queue drops a request that waited too long. An operate call that started late can still finish, but it changes nothing. Send the request again, with a backoff. If it repeats, send fewer rows or smaller artifacts.

A 422 response for a body that is not valid lists the problems in errors. It has no operate_id:

1
2
3
4
5
{
  "detail": "Request validation failed",
  "code": "VALIDATION_ERROR",
  "errors": [{"type": "missing", "loc": ["body", "rows"], "msg": "Field required"}]
}

A 422 response for a failed row adds operate_id and three fields:

1
2
3
4
5
6
7
8
{
  "detail": "Path matched nothing: //order/missing",
  "code": "VALIDATION_ERROR",
  "operate_id": "2f6c1d0e-8a3b-4c57-9e21-5b7d4a9c1f30",
  "row_index": 1,
  "operation_index": 0,
  "kind": "not_matched"
}

row_index and operation_index start at 0. operation_index is null when the error concerns the whole row. The kind has one of these values:

kind Cause
parse An operation command is empty or cannot be parsed. A value that is not a finite number (NaN, Infinity, 1e999) cannot be parsed.
not_matched A path matched nothing, and operation_not_matched_action is error.
skipped An earlier operation deleted the path, and operation_not_matched_action is error.
execution The operation failed, or it cannot change its target. Examples: mergeObject with a value that is not an object, a JSONPath union, or an XPath that selects values such as count(//a).
template_format The stored artifact is not valid XML or JSON, or not valid UTF-8 text. An XML artifact that declares an entity in its DOCTYPE and a JSON artifact with NaN or Infinity also fail.

The value template_format comes from the operate engine contract and keeps its name: the stored artifact is the template of the row.

Audit record

The response is the record of the operate call. It holds one outcome for each requested operation. An outcome of an operation without effect also holds its path. Store the response, or the parts that you need, with your test result.

The platform keeps no record of an operate call. An operate call creates no task, no task log and no entry in the task list. operate_id is a correlation id only: there is no route to read an operate call later. The platform request log keeps the time, the caller and the status of each request.

An operate call reads the stored artifact and changes nothing in the platform. A lost or late response is safe: send the request again.

Example with curl

This example makes one variant of order.xml. It uses synthetic data.

Put the request body in request.json:

1
2
3
4
5
6
7
8
9
{
  "rows": [
    {
      "id": "case-1",
      "artifact": "order.xml",
      "operations": ["set(//order/id, '2')", "delete(//order/note)"]
    }
  ]
}

Send it and read the response from a file:

1
2
3
4
5
6
7
8
set -euo pipefail
curl --fail-with-body --silent --request POST \
  "$DATAMIMIC_URL/api/v2/projects/$PROJECT_ID/tasks/$TASK_ID/artifacts/operate" \
  -H "Authorization: Bearer $PROJECT_TOKEN" \
  -H 'Content-Type: application/json' \
  --data @request.json \
  --output response.json
jq --raw-output '.artifacts[0].content' response.json

On an error, curl exits with a status other than 0, and set -e stops the script. response.json then holds the error body. A file also removes the shell quoting of '2'.

Store the response with your test result. An error response after the server queued the operate call has operate_id too. Give it to your administrator when you report a problem. A request that the server rejects earlier has no operate_id.

Example with a JSON artifact

customer.json is {"customer": {"name": "Bob", "city": "Bonn"}}. Put this body in request.json:

1
2
3
4
5
6
7
{
  "operation_not_matched_action": "warn",
  "rows": [
    {"id": "case-1", "artifact": "customer.json", "operations": ["set($.customer.name, 'Ada')", "delete($.customer.city)"]},
    {"id": "case-2", "artifact": "customer.json", "operations": ["upsertProperty($.customer.zip, '53111')", "delete($.customer.phone)"]}
  ]
}

Send it with one of the scripts in Use the response in test automation. The scripts write case-1.json and case-2.json and print case-2: 1 not_matched $.customer.phone. Use "operation_not_matched_action": "error" when a test case must fail on an operation without effect.

Use the response in test automation

A test automation job sends one request for a group of test cases. It then writes each resulting artifact to its own file. The resulting artifacts come back in the order of the request rows, and id identifies the test case.

Both scripts below do the same steps:

  1. Send request.json with the project token from the environment.
  2. Stop on a status other than 200 and print the error body. An error body after the server queued the operate call contains operate_id.
  3. Store the response in response.json, the record of the call.
  4. Write each artifacts[].content to a file named <id>.xml or <id>.json, from media_type.
  5. Print each row with an outcome status other than applied.

Give each row a unique id that is a valid file name. The files hold the exact content text, without an added newline.

Python, with the standard library only:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import json
import os
import sys
import urllib.error
import urllib.request
from pathlib import Path

EXTENSIONS = {"application/xml": ".xml", "application/json": ".json"}

url = "{}/api/v2/projects/{}/tasks/{}/artifacts/operate".format(
    os.environ["DATAMIMIC_URL"], os.environ["PROJECT_ID"], os.environ["TASK_ID"]
)
request = urllib.request.Request(
    url,
    data=Path("request.json").read_bytes(),
    headers={"Authorization": "Bearer " + os.environ["PROJECT_TOKEN"], "Content-Type": "application/json"},
    method="POST",
)
try:
    with urllib.request.urlopen(request, timeout=30) as response:
        body = response.read()
except urllib.error.HTTPError as error:
    sys.exit(f"HTTP {error.code}: {error.read().decode()}")

Path("response.json").write_bytes(body)
for artifact in json.loads(body)["artifacts"]:
    Path(artifact["id"] + EXTENSIONS[artifact["media_type"]]).write_text(artifact["content"], encoding="utf-8")
    without_effect = [o for o in artifact["outcomes"] if o["status"] != "applied"]
    if without_effect:
        print(artifact["id"] + ": " + ", ".join(f"{o['operation_index']} {o['status']} {o['path']}" for o in without_effect))

Bash, with curl and jq:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
set -euo pipefail
if ! curl --fail-with-body --silent --show-error --request POST \
  "$DATAMIMIC_URL/api/v2/projects/$PROJECT_ID/tasks/$TASK_ID/artifacts/operate" \
  -H "Authorization: Bearer $PROJECT_TOKEN" \
  -H 'Content-Type: application/json' \
  --data @request.json \
  --output response.json; then
  cat response.json >&2
  exit 1
fi
jq --raw-output '.artifacts | to_entries[]
  | "\(.key)\t\(.value.id).\({"application/xml": "xml", "application/json": "json"}[.value.media_type])"' response.json |
  while IFS=$'\t' read -r index file; do
    jq --join-output --argjson index "$index" '.artifacts[$index].content' response.json > "$file"
  done
jq --raw-output '.artifacts[] | select(any(.outcomes[]; .status != "applied"))
  | "\(.id): \([.outcomes[] | select(.status != "applied") | "\(.operation_index) \(.status) \(.path)"] | join(", "))"' response.json

Worker for the operate queue

An operate call uses the artifact_operate queue. A worker on every queue serves it. A worker with an explicit WORKER_QUEUES list must include it, else every operate call returns 504. For heavy operate load, give the queue its own worker pool. See Custom Worker Configuration.