Preview any SDK call as curl or runnable Python
Sometimes you want the exact wire request an SDK call would fire without firing it,
so you can reproduce it, share it, log it, or freeze it in a test. Every call routed
through SVIClient can be previewed with client.preview_next() (a context manager)
or client.preview(callable, *args, **kwargs) (functional sugar). Both return a
RequestPreview with two
renderers:
.to_curl()renders copy-paste curl for shells, tickets, and pipelines..to_httpx()renders copy-paste Python httpx2 code for scripts, tests, and notebooks.
Both render the same captured request: the same method, URL, headers, and body.
The universal entry point
import sasvi
client = sasvi.SVIClient.from_env()
# Context-manager form wraps any handwritten call.
with client.preview_next() as p:
client.documents.create(entity_type_name="alerts", field_values={"summary": "..."})
print(p.captured.to_curl())
# Functional form takes the callable plus its arguments.
preview = client.preview(client.alerts.list, limit=5)
print(preview.to_httpx())
Both work across every domain: search, documents, alerts, workflows, admin
(including client.admin.reference_lists), and a bound document's insights. Any
handwritten method that wraps a single HTTP request will preview. Local validation,
payload normalization, and ID minting still run. Only the network call is
short-circuited.
Multi-call methods (bulk operations, fetch-then-update flows) raise
PreviewMultiCallError after the first capture. A method whose first request is a
prerequisite read (entity metadata, a lock, an ETag) and which then fails on the
stand-in answer raises PreviewIncompleteError instead; the captured read stays on
the error's captured attribute, and it is never returned as the write. For those,
use the explicit *_preview() method on the operation when one exists, or invoke
the single underlying API call directly. Both errors are in sasvi.errors.
The search one-liner
print(client.search.text("invoice").preview().to_curl())
curl -X POST https://svi.example.com/svi-sand/searches \
-H "Authorization: Bearer $SASVI_ACCESS_TOKEN" \
-H 'Accept: application/vnd.sas.sand.search.response+json' \
-H 'Content-Type: application/vnd.sas.sand.search.request+json' \
--data @- <<'JSON'
{
"version": 3,
"query": {
"type": "text",
"language": "lucene",
"text": "invoice"
},
"visualizations": {
"summary": {
"type": "summary",
"start": 1,
"limit": 50
}
}
}
JSON
Only the Authorization line is double-quoted, so your shell expands
$SASVI_ACCESS_TOKEN there and leaves the body alone. Export the variable and the
command runs as-is.
What you can do with it
Capture a failing call for a support ticket
preview = (
client.search
.types("alerts")
.text(suspect_query)
.around_graph_preview(vertex_types=["alerts", "supplier"])
)
ticket_attachment = preview.to_curl()
# Paste into the ticket. The reviewer reproduces it locally with
# their own SASVI_ACCESS_TOKEN.
To embed a literal bearer for a reviewer who cannot re-authenticate, pass token=:
preview.to_curl(token=client.auth.get_token())
Snapshot a request in CI
Lock the wire shape so a refactor cannot silently change what hits SAND.
def test_alerts_text_search_shape_is_stable():
preview = client.search.text("test").types("alerts").preview()
assert preview.method == "POST"
assert preview.path == "/searches"
assert preview.body_dict["query"]["text"] == "test"
# Or assert against a checked-in fixture:
# assert preview.to_dict() == _load_fixture("alerts_text_search.json")
Diff two builder configurations
a = client.search.text("alpha").types("alerts").preview().body_dict
b = client.search.text("alpha").types("alerts", "cases").preview().body_dict
import difflib, json
print(
"\n".join(
difflib.unified_diff(
json.dumps(a, indent=2).splitlines(),
json.dumps(b, indent=2).splitlines(),
lineterm="",
)
)
)
Log every search before it fires
search = client.search.text(user_input).types(*allowed_types)
log.info("issuing search", curl=search.preview().to_curl())
results = search.summary(limit=20)
preview() runs locally with no network call, so wrap it freely.
Generate a test fixture
import json, pathlib
from sasvi.search import Q
fixture = (
client.search
.types("supplier")
.query(Q.text('party_name_stnd:"MJ CONSULTING LTD."'))
.connect_to_preview(
client.search.types("supplier").query(Q.text('party_name_stnd:"METAJUMP LLC."')),
hops=4,
)
.to_dict()
)
pathlib.Path("tests/fixtures/mj_metajump_paths.json").write_text(json.dumps(fixture, indent=2))
What is in a RequestPreview
preview = client.search.text("x").around_graph_preview(expansion_limit=5)
preview.method # "POST"
preview.base_url # "https://svi.example.com/svi-sand"
preview.path # "/graphs"
preview.url # base_url + path + URL-encoded query string
preview.query_params # {"calculateMetrics": True, "expansionLimit": 5, ...}
preview.headers # {Accept, Content-Type}. Auth is not here.
preview.body_dict # the JSON body as plain Python data
preview.body_model # typed GraphRequest model for in-Python use
preview.to_dict() # JSON-serializable snapshot of all of the above
preview.to_curl() # runnable curl string
preview.to_httpx() # runnable Python httpx2 code
Render as Python httpx2
When you would rather drop the request into a Python script, test harness, or
notebook than parse curl back into Python by hand, use .to_httpx(). Same data,
different format.
Sync (default)
print(client.search.text("invoice").preview().to_httpx())
import os
import httpx2
response = httpx2.post(
"https://svi.example.com/svi-sand/searches",
headers={
"Authorization": f"Bearer {os.environ['SASVI_ACCESS_TOKEN']}",
"Accept": "application/vnd.sas.sand.search.response+json",
"Content-Type": "application/vnd.sas.sand.search.request+json",
},
json={
"version": 3,
"query": {
"type": "text",
"language": "lucene",
"text": "invoice",
},
"visualizations": {
"summary": {
"type": "summary",
"start": 1,
"limit": 50,
},
},
},
)
response.raise_for_status()
data = response.json()
Async
async_=True emits the same headers and body inside an httpx2.AsyncClient:
print(preview.to_httpx(async_=True))
import os
import httpx2
async def fetch():
async with httpx2.AsyncClient() as client:
response = await client.post(
"https://svi.example.com/svi-sand/searches",
headers={...},
json={...},
)
response.raise_for_status()
return response.json()
Pick a renderer
| Use | Prefer |
|---|---|
| Pasting into a shell, support ticket, or pipeline | .to_curl() |
| Pasting into a Python script, test, or notebook | .to_httpx() |
| Asynchronous Python pipelines | .to_httpx(async_=True) |
| Embedding inside an existing script, with no import boilerplate | .to_httpx(include_imports=False) |
| A reviewer who cannot re-authenticate | either renderer plus token=<literal bearer> |
Explicit *_preview() companions
Some high-traffic methods expose an explicit *_preview() sibling that shows up in
IDE autocomplete right next to the live executor:
| Live method | Explicit preview companion |
|---|---|
Search.execute(...) | Search.preview(*viz), which defaults to SearchVisualization.summary() |
Search.around_graph(...) | Search.around_graph_preview(...) |
Search.expand_graph(...) | Search.expand_graph_preview(...) |
Search.paths_from(ref, ...) | Search.paths_from_preview(ref, ...) |
Search.connect_to(other, ...) | Search.connect_to_preview(other, ...) |
Search.explain_match(ref, ...) | Search.explain_match_preview(ref, ...) |
SearchPattern.find_paths(...) | SearchPattern.preview(), which dispatches to paths_search or related_objects_search to match find_paths |
AlertsService.create(...) | AlertsService.create_preview(...) |
AlertsService.ingest(...) | AlertsService.ingest_preview(...) |
AlertsService.list(...) | AlertsService.list_preview(...) |
Each takes the same kwargs as its live sibling (pagination, expansion limits, and so on) so the rendered curl matches what the live call would fire byte for byte.
For every other method, use client.preview_next() or
client.preview(callable, *args, **kwargs). They cover the whole SDK with no
per-method wiring.
to_curl(...) options
| Argument | Default | Effect |
|---|---|---|
multiline | True | One flag per line, body via heredoc. Set False for a single-line command, which suits log lines. |
include_auth | False | When False, emits Bearer $SASVI_ACCESS_TOKEN as a placeholder. When True, requires token=; the wrapper does not reach into the auth provider. See "Gotchas". |
token | None | An explicit bearer literal. Overrides include_auth. Use it for one-off shares. |
to_httpx(...) options
| Argument | Default | Effect |
|---|---|---|
async_ | False | When True, wraps the call in an async def using httpx2.AsyncClient and await client.<method>(...). |
token | None | An explicit bearer literal. When supplied, the rendered Authorization header carries the literal (Python-escaped) and the os import is dropped. |
env_var | "SASVI_ACCESS_TOKEN" | Name of the environment variable holding the bearer. It matches the placeholder .to_curl() uses, so hopping between formats keeps the same shell variable. |
include_imports | True | When True, emits import os / import httpx2 plus raise_for_status() and .json() boilerplate so the snippet is paste-and-run. False returns just the inline httpx2.<method>(...) call. |
Gotchas
include_auth=Truewithouttoken=raises.RequestPreviewis domain-agnostic and holds no reference to your auth provider. Either keep the$SASVI_ACCESS_TOKENplaceholder (recommended) or passtoken=...explicitly once you have fetched a bearer.- Sensitive payloads.
.to_curl()inlines bodies verbatim. If your search text contains secrets, redact before sharing. - Query string types. Booleans render as
true/false, the Java and SAS convention, notTrue/False.Nonevalues are dropped. Numbers and strings pass throughstr(). - Shell quoting. JSON bodies go out through a
<<'JSON'heredoc. The single-quoted delimiter means no shell interpolation inside the payload, so$,`, backslashes, and quotes are safe. The single-lineto_curl(multiline=False)form falls back toshlex.quoteon the body. - Cross-domain.
RequestPreviewis deliberately domain-agnostic. It lives insasvi._previewand is re-exported fromsasvi.search. The universalclient.preview_next()/client.preview()entry points cover every domain. Explicit*_preview()companions exist for the highest-traffic search and alerts methods, listed above; more get added as demand emerges. - Multi-call methods. Bulk operations, fetch-then-update flows, and any method
that issues several requests under one call raise
PreviewMultiCallErrorfromclient.preview_next()after the first capture. A method that captures a read and then fails before its second request (Document.updatereads the entity type first) raisesPreviewIncompleteErrorwith that read oncaptured. Both messages point at the explicit*_preview()method when one exists. Otherwise invoke the single underlying API call you want to inspect.
Compared to alternatives
| Approach | What you get | When to use |
|---|---|---|
preview.to_curl() | Method, URL, query, headers, and body, runnable as-is | Pre-flight inspection, reproducible shares, fixtures |
preview.body_dict | The JSON body when it is an object, as Python data | Snapshot tests, payload diffing |
preview.body_json | The JSON body in any shape, including a JSON Patch array | Previews of patch and list writes |
preview.body_content | The raw bytes of a body that is not JSON | Uploads, CSV and form bodies |
preview.body_model | Typed SAND request model | Hand-off to lower-level sasvi.api.sand.* calls |
search.raw_dict() | The compiled search body without the visualization block a terminal adds | Call sites that read the query only |
SVIClient(log_http_level="DEBUG", log_http_request_body=True, ...) | The full request after it fires, in the logger | Production debugging, intermittent failures |
Reach for to_curl() when you want to share or reproduce a call. Reach for HTTP
logging when you want to watch production traffic.
Go further
- Search guide. Fluent builder, terminals, graph helpers.
- Search API reference. Every method signature.
RequestPreview. Its renderers and accessors in full.- SVIClient HTTP logging knobs. For after-the-fact request capture across every domain.