Dataflows CLI
MicrosoftOfficialPublished by Microsoft
- Skill
- Tool integration
- Automation and integrations
- MIT
- Low risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
The dataflows-cli skill provides a structured interface for interacting with Fabric Dataflow Gen2 items. It operates as a mode-based dispatcher, requiring users to select between authoring, consumption, or upgrade modes. The skill handles complex tasks such as M language definition updates, connection management, output destination configuration, and the migration of legacy Gen1 dataflows to Gen2.1. It emphasizes safe, intentional operations by requiring users to read specific reference documentation before executing state-changing API calls.
What it does
- Creates and updates Fabric Dataflow Gen2 items and their definitions.
- Manages connections, credentials, and output destinations for dataflows.
- Previews Power Query M definitions using executeQuery to validate logic before persistence.
- Facilitates the upgrade of Gen1 dataflows to Gen2.1 via save-as operations.
- Retrieves refresh history and inspects existing dataflow definitions.
- Provides a framework for executing and testing ad-hoc M queries.
When to use it
- When you need to programmatically create or modify Fabric Dataflow Gen2 items.
- When performing maintenance on Power Query M definitions or data connections.
- When migrating legacy Gen1 dataflows to the Gen2.1 architecture.
- When you need to audit refresh history or validate dataflow configurations.
- When testing M query logic against live data sources before saving changes.
Advantages
- Enforces a structured, mode-based workflow to prevent accidental mutations.
- Provides granular control over Dataflow Gen2 definitions and metadata.
- Supports complex lifecycle tasks like Gen1-to-Gen2 upgrades.
- Integrates directly with Fabric REST APIs for automated data pipeline management.
Usage examples
- “Show me the refresh history and parameters of the SalesIngest dataflow.”
- The agent enters consumption mode, reads the consumption reference, and retrieves the requested refresh history and parameters for the specified dataflow.
- “Preview this M query, then save it into the SalesIngest dataflow definition.”
- The agent enters authoring mode, previews the M query to validate it, and then executes the updateDefinition call to persist the changes.
- “Is my Gen1 dataflow ready to upgrade to Gen2.1?”
- The agent enters upgrade mode, performs a readiness assessment, and reports on the risk and requirements for upgrading the specified Gen1 dataflow.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/microsoft/dataflows-cli/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip dataflows-cli.zip -d .agents/skills
Documentation by Microsoft
Telemetry — MANDATORY. Every
api.fabric.microsoft.comcall must carryx-ms-fabric-skill: dataflows-cli(az rest:--headers "x-ms-fabric-skill=dataflows-cli"), including every LRO poll,fabric_lroand retry. Snippets omit it — add it anyway.
CRITICAL NOTES
To find the workspace details (including its ID) from workspace name: list all workspaces and, then, use JMESPath filtering
To find the item details (including its ID) from workspace ID, item type, and item name: list all items of that type in that workspace and, then, use JMESPath filtering
Skill disambiguation: use
dataflows-clifor every Fabric Dataflow Gen2 item and Power Query M concern. Synapse / ADF pipeline and dataset JSON translation ispipeline-migration; Spark notebook transformations arespark-cli; T-SQL transformations aresqldw-cli.
Fabric Dataflow Gen2 -- CLI Skill
This one skill owns Fabric Dataflow Gen2 items: connections, Power Query M, output destinations, saved definitions, refresh history, and Gen1 upgrades.
It is a mode dispatcher and contains NO procedures. Pick the mode that matches the request from the table below, then read the matching references/<mode>.md file end to end with your file-reading tool BEFORE issuing a single command. That file holds the endpoints, payload shapes, templates and gotchas; acting without it produces wrong payloads and wrong results.
Read it once per session. A file you have already read stays in context, so do not re-read it on a later turn; open the deeper files under references/<mode>/ only when a row in that file's reference table matches what you still need, and open only that row's file.
Mode selection
| Mode | Use when the request ... | Example triggers | Read this first |
|---|---|---|---|
authoring | creates or changes a dataflow: connections, credentials, M edits previewed before save, output destinations, updateDefinition | executeQuery preview, updateDefinition, connection setup, supportedConnectionTypes, credentialType, add output destination | references/authoring.md |
consumption | reads a saved dataflow: definition, parameters, refresh history, or runs a saved/ad-hoc read-only M query and parses Arrow | getDefinition, executeQuery saved query, ad-hoc query, Arrow IPC, refresh history | references/consumption.md |
upgrade | upgrades a Gen1 dataflow to Gen2.1 via save-as and rebind, or assesses upgrade readiness/risk | Gen1 Gen2 readiness, saveAsNativeArtifact, clone Gen1 dataflow, upgrade risk assessment | references/upgrade.md |
Mode boundary rule
consumption is read-only. A preview run that exists to validate M before updateDefinition, and any capability lookup (supportedConnectionTypes, credentialType), belong to authoring even though they issue the same executeQuery call -- classify by intent, not by endpoint.
If a request genuinely spans modes, handle them one at a time and read each reference before you start that part. If the mode is ambiguous after reading this table, ask one short clarifying question instead of guessing.
Terminal write -- the step you must not skip
Reading the reference and planning the change is NOT completing the task. Each mutating mode ends with one state-changing call. If you did not issue it, nothing was persisted -- say so explicitly rather than reporting success.
| Mode | Terminal write |
|---|---|
authoring | POST /v1/workspaces/{ws}/dataflows/{id}/updateDefinition to persist the M, connections and output destinations; a NEW dataflow needs POST /v1/workspaces/{ws}/items (or /dataflows) first. executeQuery is a preview and writes nothing. If the user asked for a refresh, also POST .../jobs/instances?jobType=Refresh. |
consumption | none -- this mode is read-only |
upgrade | saveAsNativeArtifact to create the Gen2.1 artefact, then rebind. A readiness report alone does not upgrade anything. |
Before you report the task done, confirm the terminal call returned success and, where the reference documents a readback, read the artefact back to prove the change landed.
upgrade generation boundary -- HARD STOP (mandatory)
Save-as runs only from Gen1 to Gen2.1. For an execution request whose source is Gen2, or whose source generation is not established, state that no public save-as or in-place upgrade endpoint is available and stop before any API call. This does not block a read-only readiness scan whose purpose is to discover and classify Gen1 candidates.
Do not read "choose the closest endpoint and proceed" as approval to export a definition and create a copy, do not switch to authoring to do it instead, and do not mutate anything. Ask the user to clarify the intended outcome and to approve explicitly.
consumption reporting
consumption has no terminal write, so its deliverable is the answer itself. When that mode runs executeQuery, name the operation you called and state the QueryName you sent, verbatim, next to the results, plus whether it was a saved shared member or a non-persisted ad-hoc customMashupDocument. Rows alone do not tell the user which call produced them.
This applies to consumption only. In authoring, executeQuery is an intermediate preview step -- do not add reporting turns around it; go on to the terminal write.
Shared essentials (all modes)
Resolve the workspace and item first; every mode depends on it.
| Task | Reference | Notes |
|---|---|---|
| Finding Workspaces and Items in Fabric | COMMON-CLI.md | Mandatory -- read before resolving any workspace or item id |
| Fabric Topology & Key Concepts | COMMON-CORE.md | Item types, workspaces, capacities |
| Environment URLs | COMMON-CORE.md | Sovereign / non-public cloud hosts |
| Authentication & Token Acquisition | COMMON-CORE.md | Wrong audience = 401; read before any auth issue |
| Authentication Recipes | COMMON-CLI.md | az login flows and token acquisition |
| Core Control-Plane REST APIs | COMMON-CORE.md | Pagination, LRO polling, rate limiting |
| Gotchas & Troubleshooting | COMMON-CLI.md | az rest audience, shell escaping, token expiry |
Rules
MUST
Select exactly one mode from the table above before doing anything else.
Read
references/<mode>.mdend to end, as your FIRST tool call, before the first command of that mode. Read it ONCE, in a single full read: do not re-open it, do not grep it again, and do not page through it. You already have it.Resolve workspace and item ids by listing and filtering, never by guessing a GUID.
Announce a mode switch explicitly when the request crosses a boundary.
Treat the reference as instructions, never as the deliverable. After reading it, RUN the documented commands against the live workspace and report the real results. Quoting what the reference says instead of executing it does not answer the request.
When a question about what Fabric supports IS the deliverable -- supported connection types, a connector's parameters, available credential types -- answer it from the endpoint the reference names rather than from the reference's own list, and name that endpoint in your answer. Whichever mode you are in: the reader cannot tell a live value from a quoted one unless you say where it came from. This is wording in the final answer, not an extra step.
Produce every artefact the user asked for, under the name they used. Running the right API calls is not a substitute for the requested report: if the request names a deliverable, emit it, and keep its heading even when the finding is "none" or "not applicable".
PREFER
The narrowest mode that satisfies the request.
Reading exactly ONE mode reference. Load a second only when the request genuinely spans modes, and say so before you do.
Reporting the mode you chose in your first response so the user can correct you.
AVOID
Acting from this dispatcher alone -- it intentionally omits the operational detail.
Answering with a summary of the reference instead of executing it.
Re-reading or re-grepping a reference you already loaded; it costs turns and tokens.
Mutating anything while in a read-only mode.
Loading a different skill for work this skill already owns (see CRITICAL NOTES 3).
Examples
| User request | Mode | Reference to read |
|---|---|---|
| "Show me the refresh history and parameters of the SalesIngest dataflow." | consumption | references/consumption.md |
| "Preview this M query, then save it into the SalesIngest dataflow definition." | authoring | references/authoring.md |
| "Is my Gen1 dataflow ready to upgrade to Gen2.1?" | upgrade | references/upgrade.md |
Files
- ATTRIBUTION.mdAdded by AutoGineer871 B
- LICENSELicence file added by AutoGineer1.1 KiB
- SKILL.md9.5 KiB
- apm.yml445 B
- references/authoring.md55.3 KiB
- references/authoring/authoring-cli-quickref.md23.4 KiB
- references/authoring/authoring-script-templates.md79.7 KiB
- references/authoring/charts/bar_chart.pyScript3.9 KiB
- references/authoring/charts/line_chart.pyScript3.5 KiB
- references/authoring/connection-management.md39.8 KiB
- references/authoring/connectors.md14.7 KiB
- references/authoring/m-language.md9.7 KiB
- references/authoring/mashup-preview.md28.3 KiB
- references/authoring/output-destinations.md39.6 KiB
- references/consumption.md28.7 KiB
- references/consumption/chart-visualization.md2.6 KiB
- references/consumption/charts/bar_chart.pyScript3.9 KiB
- references/consumption/charts/line_chart.pyScript3.5 KiB
- references/consumption/consumption-cli-quickref.md6.7 KiB
- references/consumption/discovery-queries.md7.0 KiB
- references/consumption/script-templates.md17.1 KiB
- references/upgrade.md21.0 KiB
- references/upgrade/risk-assessment-guide.md11.2 KiB
- references/upgrade/upgrade-cli-quickref.md8.8 KiB
references/authoring/mashup-preview.md
executeQuery — Fabric Dataflow Mashup Preview API
What this is
Fabric Dataflow Gen2 exposes a mashup engine endpoint that evaluates a Power Query M document against a specific dataflow's bound connections and returns the result as an Apache Arrow IPC byte stream. There is no persistence and no refresh; this is the read-side mashup engine, suitable both for ad-hoc query execution against a saved dataflow and for previewing candidate M before persisting it via updateDefinition.
This file is the canonical API reference for executeQuery. End-to-end recipes (bash + PowerShell smoke tests) live in authoring-script-templates.md; Arrow → CSV / pandas conversion lives in dataflows-cli consumption mode § Query Evaluation.
Vocabulary -- name the things you send
When you explain or use this API, surface the exact literal names below; do not paraphrase, abbreviate, or invent variants. The smoke tests and reviewers grep for these literals.
| Literal | What it is | Where it appears |
|---|---|---|
executeQuery (singular) | The preview endpoint path segment. Not executeQueries, not ExecuteQuery. | URL path: .../dataflows/{dataflowId}/executeQuery |
QueryName | Top-level request-body field naming the shared member to evaluate. Microsoft Learn documents this field as queryName; it is case-insensitive on the wire, and the repo's live-verified examples use PascalCase QueryName. | JSON request body |
customMashupDocument | Top-level request-body field carrying the complete section Section1; ... M document being previewed. Not mashupDocument, not MashupDocument, not query, not base64-encoded -- it is a plain UTF-8 string. | JSON request body |
mashup.pq | The saved part path inside the dataflow definition. The M body you pass as customMashupDocument during preview is the same body you base64-encode into the mashup.pq part when you persist via updateDefinition. | Definition parts[].path |
queryMetadata.json | The saved part holding connections[], queriesMetadata, and formatVersion. | Definition parts[].path |
Preview-vs-save loop in one sentence: build candidate M -> POST it as customMashupDocument to executeQuery -> inspect Arrow + render head(10) -> on success, base64-encode the same M into the mashup.pq part and POST to updateDefinition.
Endpoint
POST https://api.fabric.microsoft.com/v1/workspaces/{workspaceId}/dataflows/{dataflowId}/executeQuery| Header | Value |
|---|---|
Authorization | Bearer <fabric-aad-token> |
Content-Type | application/json |
Accept | application/vnd.apache.arrow.stream (server may also accept application/octet-stream) |
Timeout budget: 30 s+ for synchronous responses (server-side evaluation can be slow on cold cache). Long-running evaluations return 202 Accepted with a polling URL — see Status codes.
Auth
AAD/Entra access token. Audience: Power BI (
https://analysis.windows.net/powerbi/api, no trailing slash) forClusterIdlookups againstapi.powerbi.com/v2.0/...; Fabric (https://api.fabric.microsoft.com/) forexecuteQueryagainstapi.fabric.microsoft.com/v1/....The Fabric audience is also accepted for
api.powerbi.comv2 calls in current tenants — convenient when a script already holds a Fabric token — but the Power BI audience is the safe default and the only form documented to always work. If a v2 call fails withAADSTS500011, the token audience is wrong (or carries a trailing slash).Token expiry is typically 1 h. Refresh before the request if less than 5 minutes remain.
Required permissions: caller must have read access to the workspace and the dataflow's bound connections must be accessible to the caller's identity (cloud connections) or via a configured gateway (on-prem sources).
Preconditions
<a id="bootstrap-branch--new-dataflow--new-credentialed-source"></a>
Dataflow exists in the target workspace.
Connections bound — every data source referenced by the M document must have a connection bound to the dataflow via its
queryMetadata.json connections[]array. Binding is persisted throughupdateDefinition, not through this endpoint;executeQuerycannot accept ad-hoc credentials. See connection-management.md for the create + bind workflow.Cloud connection JSON form — each bound cloud connection is stored as a JSON string of the form
{"ClusterId":"<guid>","DatasourceId":"<guid>"}.ClusterIdis obtained from Power BI v2:GET https://api.powerbi.com/v2.0/myorg/me/gatewayClusterDatasources(list + filter; per-id v1.0 lookups are unreliable for cloud connections — see authoring-cli-quickref.md § ClusterId resolution).Multi-source / privacy firewall — for queries that combine multiple sources, declare the section attribute
[AllowCombine = true]at the top of thecustomMashupDocument; otherwise the privacy firewall blocks evaluation. See M document patterns § Multi-source.
Request body
<a id="custommashupdocument-format"></a>
| Field | Type | Required | Notes |
|---|---|---|---|
QueryName | string | Yes | Must name a shared member declared in the dataflow's persisted mashup.pq (when customMashupDocument is omitted) or in the supplied customMashupDocument. The wire field is case-insensitive — queryName is also accepted. The repo standard is PascalCase QueryName; live-verified examples use that form. |
customMashupDocument | string | Optional | When omitted, the endpoint executes the persisted query identified by QueryName. When provided, it must be a complete section Section1; … document — see below. |
Anti-pattern —
{"queries":[…]}array body shape. Wrapping the call in an array ({"queries":[{"queryName":"X"}]}or{"queries":[{"QueryName":"X"}]}) always returns400 DataflowExecuteQueryError: Invalid query name, regardless of inner casing — the endpoint accepts exactly one query per call and does not read fields nested inside aqueriesarray. Live-verified 2026-05-19.
The auto-wrap rule (client-side)
The endpoint does not auto-wrap raw expressions into a section document — clients must do so. Replicate this rule when assembling the body:
if customMashupDocument starts with "section " (case-insensitive):
send as-is
else:
send: "section Section1;\n\nshared {QueryName} = {trimmed expression};"customMashupDocument requirements
Begins with
section Section1;(or another section name —Section1is conventional).Every
sharedmember is terminated with;.The
QueryNamerequest field names asharedmember declared in the document. Mismatch returnsDataflowExecuteQueryError.Non-identifier names use quoted identifiers:
shared #"Sales Query" = ...;with"QueryName": "Sales Query".All dependencies (parameters, helper functions, other queries) must be declared in the same document. The persisted
mashup.pqis not merged in at evaluation time; the supplied document is evaluated standalone.
Response
200 OK — response body is a raw Apache Arrow IPC byte stream.
Content-Type: application/vnd.apache.arrow.stream. There is no JSON envelope; do not pipe throughjq. Capture with--output-file(az rest) or--output/-OutFile(curl/Invoke-WebRequest). The first four bytes are the IPC continuation markerFF FF FF FF.202 Accepted — evaluation has been accepted but is running asynchronously. Headers carry
Location(polling URL),x-ms-operation-id(correlation), andRetry-After(seconds). Poll theLocationuntil it returns a terminal200.PQ Arrow Metadatacolumn — every response carries a trailing column namedPQ Arrow Metadata. On success it is empty (or carries non-error metadata only); on a 200-path execution error it carries the error JSON literal. See Error handling — A.
Decoding the Arrow stream
Try pyarrow.ipc.open_stream first. Some Fabric responses use the Arrow file format rather than the stream format — fall back to pyarrow.ipc.open_file if the stream reader rejects the header.
import io, pyarrow as pa, pyarrow.ipc as ipc
buf = io.BytesIO(response_bytes)
try:
reader = ipc.open_stream(buf)
except pa.lib.ArrowInvalid:
buf.seek(0)
reader = ipc.open_file(buf)
table = reader.read_all()Each Arrow column maps to a column of the evaluated M query; types are Arrow primitives (int32, int64, string, timestamp, decimal, …). An empty table is a valid result — it means the M evaluated to a 0-row table, not an error.
Showing results to the user. Decoding into a
pyarrow.Tableis only half the validation. After the embedded-error check passes, renderhead(10)as a markdown table in chat so the human can spot silent-success bugs (filter dropped all rows, wrong column, off-by-one, wrong cast). Canonical snippet + suppression rules: dataflows-cli consumption mode § Example 5b — Render Query Results as a Markdown Table.
Status codes
| Code | Meaning | Action |
|---|---|---|
| 200 OK | Synchronous result; body is the Arrow IPC stream | Parse; also inspect the PQ Arrow Metadata column for embedded errors (§ Error handling — A) |
| 202 Accepted | Asynchronous evaluation in progress | Poll the Location URL until terminal; honor Retry-After between polls; use x-ms-operation-id for correlation |
| 400 Bad Request | DataflowExecuteQueryError — invalid/empty QueryName, the {"queries":[…]} array body shape (always returns "Invalid query name"), invalid customMashupDocument, or QueryName not found in the persisted mashup (or in the supplied document; surfaced as QueryNotFound inside message) | Fix the request body; do not auto-retry |
| 401 Unauthorized | Token expired or wrong audience | Refresh the token; retry once |
| 403 Forbidden | Caller lacks access to the workspace, dataflow, or one of the bound connections | Fix permissions; do not auto-retry |
| 404 Not Found | Workspace or dataflow ID does not exist | Fix the IDs; do not auto-retry |
| 429 Too Many Requests | Throttled by the service rate limit | Wait Retry-After seconds; retry |
| 500 / 503 | Transient server-side failure | Exponential backoff 1s, 2s, 4s; max 3 retries |
Non-200 responses carry a standard Fabric ErrorResponse JSON envelope; the most common errorCode is DataflowExecuteQueryError.
Error handling
executeQuery exposes two distinct error surfaces. Naive callers that check only the HTTP status will silently treat in-stream failures as success.
<a id="detecting-failures-inside-the-arrow-body"></a>
A. 200 OK with embedded PQ Arrow Metadata error
The trailing PQ Arrow Metadata column is present on every response. On a 200-path execution or streaming error it carries a JSON literal of the form {"Error":"<engine message>"}. On success the column is empty (or carries non-error metadata only). Naive callers that check only the HTTP status will silently treat in-stream failures as success.
Verified shape:
{"Error":"Request is invalid and cannot be processed: Semantic error: SEM0100: 'where' operator: Failed to resolve column or scalar expression named 'TIMESTAMP_TYPO'"}Detector — bash (fast scan, fragile on schemas containing a column literally named Error):
if grep -q '"Error":"' result.arrow; then
python3 - <<'PY' result.arrow
import re, sys
raw = open(sys.argv[1], "rb").read().decode("utf-8", errors="replace")
m = re.search(r'\{"Error":"[^"]+"\}', raw)
print("PREVIEW FAILED:", m.group(0) if m else "(error marker present, JSON not parsed)")
PY
exit 1
fiDetector — PowerShell:
$raw = [Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes("result.arrow"))
$err = [Regex]::Match($raw, '\{"Error":"[^"]+"\}').Value
if ($err) {
Write-Error "Preview failed: $err"
exit 1
}Detector — Python with pyarrow (canonical — inspects schema metadata instead of scanning bytes):
import json, pyarrow as pa, pyarrow.ipc as ipc
with open("result.arrow", "rb") as f:
try:
reader = ipc.open_stream(f)
except pa.lib.ArrowInvalid:
f.seek(0)
reader = ipc.open_file(f)
md = reader.schema.metadata or {}
for v in md.values():
s = v.decode("utf-8", errors="replace")
if '"Error"' in s:
try:
msg = json.loads(s)["Error"]
except (ValueError, KeyError):
msg = s[:200]
raise SystemExit(f"Preview failed: {msg}")B. Non-200 with ErrorResponse JSON envelope
400 / 401 / 403 / 404 / 429 / 5xx responses carry a JSON ErrorResponse body with this shape:
{
"requestId": "<guid>",
"errorCode": "DataflowExecuteQueryError",
"message": "ErrorCode: PqoEvaluateStreamBadRequest, ErrorDetails: InternalErrorCode: <code>, Message: {...}",
"isRetriable": false
}The top-level errorCode is the broad classifier; nested inside message is a more specific InternalErrorCode that pinpoints the cause. Honor isRetriable directly when present — it is the service's own retry directive.
Observed InternalErrorCode values for DataflowExecuteQueryError:
InternalErrorCode | Wire-level cause |
|---|---|
RewriteDocumentFailed / QueryNotFound | QueryName field does not name a shared member in customMashupDocument (or in the persisted mashup.pq when customMashupDocument is omitted) |
ReinterpretRequestFailed | customMashupDocument failed to parse — missing section header, missing ; terminator, or other M syntax error |
EvaluationError (Message: Evaluation result error code: TimedOut) | Underlying source evaluation exceeded the server-side executeQuery budget (~90s observed for Kusto-backed queries). Recovery: re-issue the request with customMashupDocument set to the full persisted mashup.pq plus an appended probe that caps the target query — shared __PreviewCap = Table.FirstN(<TargetQuery>, 10); — and QueryName: "__PreviewCap". The cap pushes down for most connectors and avoids materialising the unbounded source. Use this whenever a heavy persisted query needs human-visible sampling (Example 5b in dataflows-cli consumption mode) but is too expensive to evaluate end-to-end. |
Retry policy
Auto-retry:
401(after refreshing the token, max 1 retry),429(honorRetry-After),500/503(exponential backoff1s, 2s, 4s, max 3 retries).Do NOT auto-retry:
400,403,404— these are deterministic client errors. The service signals this directly via"isRetriable": falsein the ErrorResponse body; clients can honor that flag instead of hard-coding status-code logic.202 LRO: poll
Locationuntil terminal; honorRetry-Afterbetween polls if returned.
Sequencing constraints
Bind connections to the dataflow via
updateDefinitionbefore callingexecuteQuery. The endpoint cannot accept ad-hoc credentials.customMashupDocumentis the only draft / preview mode. When supplied, the endpoint evaluates the candidate document on demand against the dataflow's bound connection context.Without
customMashupDocument,executeQueryruns the latest persistedshared <QueryName>member. There is no implicit draft state for saved-but-not-committed changes.executeQueryis read-only. To materialize results to a destination, trigger a refresh job afterward — see dataflows-cli authoring mode SKILL.md § Refresh.
Examples
1. Basic call — 200 OK path
bash / curl
TOKEN=$(az account get-access-token --resource https://api.fabric.microsoft.com --query accessToken -o tsv)
WS=<workspace-guid>
DF=<dataflow-guid>
jq -n --arg q "Probe" --arg m 'section Section1;
shared Probe = Table.RowCount(#"My Query");' \
'{QueryName: $q, customMashupDocument: $m}' > req.json
curl -sS -X POST \
"https://api.fabric.microsoft.com/v1/workspaces/$WS/dataflows/$DF/executeQuery" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: application/vnd.apache.arrow.stream" \
--data @req.json \
--output result.arrowPowerShell
$token = (az account get-access-token --resource https://api.fabric.microsoft.com --query accessToken -o tsv)
$body = @{
QueryName = "Probe"
customMashupDocument = "section Section1;`n`nshared Probe = Table.RowCount(#""My Query"");"
} | ConvertTo-Json
Invoke-WebRequest -Method POST `
-Uri "https://api.fabric.microsoft.com/v1/workspaces/$WS/dataflows/$DF/executeQuery" `
-Headers @{ Authorization = "Bearer $token"; Accept = "application/vnd.apache.arrow.stream" } `
-ContentType "application/json" `
-Body $body -OutFile result.arrowPython (httpx + pyarrow)
import httpx, io
import pyarrow.ipc as ipc
resp = httpx.post(
f"https://api.fabric.microsoft.com/v1/workspaces/{ws}/dataflows/{df}/executeQuery",
headers={
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.apache.arrow.stream",
},
json={
"QueryName": "Probe",
"customMashupDocument": 'section Section1;\n\nshared Probe = Table.RowCount(#"My Query");',
},
timeout=120,
)
resp.raise_for_status()
buf = io.BytesIO(resp.content)
try:
reader = ipc.open_stream(buf)
except Exception:
buf.seek(0)
reader = ipc.open_file(buf)
table = reader.read_all()2. Polling a 202 LRO response
bash / curl
STATUS=$(curl -sS -D headers.txt -o result.arrow -w '%{http_code}' \
-X POST "https://api.fabric.microsoft.com/v1/workspaces/$WS/dataflows/$DF/executeQuery" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: application/vnd.apache.arrow.stream" \
--data @req.json)
if [ "$STATUS" = "202" ]; then
LOC=$(grep -i '^location:' headers.txt | awk '{print $2}' | tr -d '\r')
RETRY=$(grep -i '^retry-after:' headers.txt | awk '{print $2}' | tr -d '\r')
while :; do
sleep "${RETRY:-2}"
STATUS=$(curl -sS -D headers.txt -o result.arrow -w '%{http_code}' \
"$LOC" -H "Authorization: Bearer $TOKEN" -H "Accept: application/vnd.apache.arrow.stream")
[ "$STATUS" = "200" ] && break
[ "$STATUS" = "202" ] || { echo "Polling failed with HTTP $STATUS"; exit 1; }
RETRY=$(grep -i '^retry-after:' headers.txt | awk '{print $2}' | tr -d '\r')
done
fiPowerShell
$resp = Invoke-WebRequest -Method POST `
-Uri "https://api.fabric.microsoft.com/v1/workspaces/$WS/dataflows/$DF/executeQuery" `
-Headers @{ Authorization = "Bearer $token"; Accept = "application/vnd.apache.arrow.stream" } `
-ContentType "application/json" -Body $body -OutFile result.arrow -PassThru
if ($resp.StatusCode -eq 202) {
$location = $resp.Headers['Location']
$retry = [int]($resp.Headers['Retry-After'] | Select-Object -First 1)
while ($true) {
Start-Sleep -Seconds ([Math]::Max($retry, 2))
$poll = Invoke-WebRequest -Method GET -Uri $location `
-Headers @{ Authorization = "Bearer $token"; Accept = "application/vnd.apache.arrow.stream" } `
-OutFile result.arrow -PassThru
if ($poll.StatusCode -eq 200) { break }
if ($poll.StatusCode -ne 202) { throw "Polling failed with HTTP $($poll.StatusCode)" }
$retry = [int]($poll.Headers['Retry-After'] | Select-Object -First 1)
}
}Python
import time, httpx
url = f"https://api.fabric.microsoft.com/v1/workspaces/{ws}/dataflows/{df}/executeQuery"
hdr = {"Authorization": f"Bearer {token}", "Accept": "application/vnd.apache.arrow.stream"}
resp = httpx.post(url, headers=hdr, json=body, timeout=120)
while resp.status_code == 202:
time.sleep(int(resp.headers.get("Retry-After", "2")))
resp = httpx.get(resp.headers["Location"], headers=hdr, timeout=120)
resp.raise_for_status()
arrow_bytes = resp.content3. Detecting PQ Arrow Metadata errors on a 200 response
See § Error handling — A for the three detector snippets (bash, PowerShell, and Python). The Python pyarrow schema-metadata inspector is the canonical path — the bash grep detector is fast but fragile on schemas containing a column literally named Error, and the PowerShell regex detector loads the entire file into memory.
M document patterns
<a id="hard-avoid-unbounded-production-volume-preview"></a>
Probe a connection
section Section1;
shared Probe = Lakehouse.Contents(null);Count rows of an existing query
section Section1;
shared RowCount = Table.RowCount(#"My Query");First page of a remote source (capped)
section Section1;
shared Sample =
let
S = Sql.Database("server", "db"),
T = S{[Schema="dbo", Item="Orders"]}[Data],
F = Table.FirstN(T, 100)
in
F;
executeQueryreturns the full evaluated dataset, not a sample. For high-volume sources, cap withTable.FirstN, predicate-push withValue.NativeQuery(... "SELECT TOP N ..."), or filter by a date predicate. Strip the cap before persisting the production mashup viaupdateDefinition.
Multi-source (privacy firewall)
[AllowCombine = true]
section Section1;
shared Joined =
let
A = Sql.Database("srv-a", "db-a"){[Schema="dbo", Item="Customers"]}[Data],
B = Sql.Database("srv-b", "db-b"){[Schema="dbo", Item="Orders"]}[Data],
J = Table.NestedJoin(A, "Id", B, "CustomerId", "B", JoinKind.LeftOuter)
in
J;Common error codes
| Surface | Code / message | Likely cause | Fix |
|---|---|---|---|
ErrorResponse 400 | DataflowExecuteQueryError + InternalErrorCode: RewriteDocumentFailed / Code: QueryNotFound | QueryName field does not match a shared member in customMashupDocument (or in the persisted mashup.pq if customMashupDocument is omitted) | Match exactly; use quoted identifiers (shared #"Sales Query" = ...; ↔ "QueryName": "Sales Query") |
ErrorResponse 400 | DataflowExecuteQueryError + InternalErrorCode: ReinterpretRequestFailed (often with nested SyntaxError[(row,col)-...]) | Missing section Section1; header, missing ; terminator, or a referenced helper / parameter is not included in the document | Validate locally; ensure the document is self-contained — declare all parameters and helper functions in the same section |
ErrorResponse 403 | Access denied | Caller lacks Contributor on the dataflow, or a bound connection is not shared with the caller | Confirm role assignment; verify connection sharing |
200 + embedded {"Error":"Credentials are required to connect to the <source> source"} | Connection not bound to the dataflow at evaluation time, or the bound connectionId is invalid | Bind the connection via updateDefinition first (Preconditions § 2); verify connectionId resolves via GET /v1/connections | |
200 + embedded {"Error":"Timeout..."} | Unbounded evaluation against a high-volume source | Cap with Table.FirstN, push a TOP N predicate via Value.NativeQuery, or add a date filter |
Preview-Driven Authoring Loop
<a id="preview-driven-authoring-loop"></a>
When the change touches Power Query M (new query, edited mashup, new source, changed parameters), preview the candidate customMashupDocument against the dataflow's bound connections before persisting. Catches syntax, schema, and credential errors at authoring time.
Intent split. This workflow is for the pre-save intent. To execute a saved query (
QueryNameonly) or run an ad-hoc read-onlycustomMashupDocumentwith no intent to persist, usedataflows-cli consumption mode.
Minimal ordered steps
Locate or create the dataflow shell —
POST /v1/workspaces/{ws}/dataflowswith{"displayName":"…"}(SKILL.md Workflow A step 4).Ensure connections are bound — for new credentialed sources, do a minimal
updateDefinitionwithqueryMetadata.json connections[]first (the "bootstrap save"). Aconnections[]array declared only in the initial create payload is not yet visible toexecuteQuery. See Bootstrap branch.Compose the candidate
customMashupDocumentas a completesection Section1; ...document. The request'sQueryName(top-level, PascalCase) must match asharedmember in the document. See customMashupDocument format.Preview —
POST /v1/workspaces/{ws}/dataflows/{df}/executeQuerywith body{"QueryName": "<name>", "customMashupDocument": "<section>"}. Pass--output-file results.arrow—az restwrites the raw Apache Arrow IPC stream to disk. Arrow → CSV/pandas: dataflows-cli consumption mode § Query Evaluation.Validate the preview (two-tier — both required before persisting):
a. Embedded-error check. HTTP 200 is not proof of success; engine errors are embedded inside the stream as
{"Error":"..."}. Quick scan:grep -q '"Error":"' results.arrow. Canonical pyarrow detector inspects schema metadata — see § Error handling — A.b. Render
head(10)as a markdown table to the user. The embedded-error check only catches engine-level failures (column not found, cast errors, SEM0100, etc.). It does not catch silent-success bugs: filter dropped all rows, wrong column referenced, wrong join key, off-by-one filter, wrong cast producing epoch dates. The 10-row visual lets the human verify shape, row count, and value sanity in seconds. Snippet + suppression rules: dataflows-cli consumption mode § Example 5b.c. Probe for per-cell errors. An errored cell serializes as an Arrow null — indistinguishable from a genuine null in the head(10) view. To disambiguate, wrap the cell in
tryand read the[HasError]field:try <step>{N}[Col]returns[HasError = true, Error = [...]]for an errored cell vs[HasError = false, Value = ...]otherwise; filter withTable.SelectRows(<step>, each not (try [Col])[HasError]). Detail: m-language.md § Per-cell errors.
Persist via
updateDefinition— strip any preview-onlyTable.FirstN/TOP N/ test-mode parameters from the saved mashup. VerifyqueryMetadata.json connections[]survived the full-replacement write before triggering refresh.
Skip the preview only for metadata-only edits (display name, schedule, loadEnabled toggle) or when the agent records an explicit skip reason (bootstrap, prohibitive cost, side-effecting source).
ASCII chart preview (optional)
After the two-tier validation passes, optionally render the preview data as ASCII charts for visual validation:
Line chart (time-series data):
references/authoring/charts/line_chart.pyHorizontal bar chart (categorical data):
references/authoring/charts/bar_chart.py
Ask the user if they want chart visualizations before proceeding. If accepted, call executeQuery for each entity, parse the Arrow IPC stream, render the appropriate chart type, and ask the user to confirm before the final updateDefinition. Both chart scripts are pure Python 3 (no dependencies). For parameters and display guidelines, see chart-visualization.md.
Related references
connection-management.md — create and bind connections (Preconditions step 2)
common/DATAFLOWS-AUTHORING-CORE.md § Power Query M Code Structure — section documents, multi-query patterns, parameter declarations
dataflows-cli authoring mode SKILL.md — authoring workflow rules (when to preview, bootstrap-binding, hard-avoid for unbounded preview)
dataflows-cli consumption mode SKILL.md § Query Evaluation — Arrow → pandas, CSV conversion, custom-M variant
authoring-script-templates.md — end-to-end smoke test, executable PowerShell variant
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs Python
Security
What our scanner noticed· Low risk
- Instructions that use the network
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- Microsoft
- Publisher
- Microsoft (Official)
- Source
- microsoft/skills-for-fabric · skills/dataflows-cli · commit f8fac11
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
- Also distributed in
- microsoft/skills-for-fabric
AutoGineer is not affiliated with or endorsed by Microsoft or Microsoft.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download dataflows-cli.zip