Skip to main content

Make Your First REST API Request

This page uses a Python script to complete the first API simulation: authenticate, confirm the current user, read the specified model and workspace definition, create a job, wait for the final state within a limited time, and then read the results through WebSocket.

The example does not create, modify, or delete models, but it does create a real job. Please first prepare a model in the test workspace that requires a small amount of calculation and has been verified to be runnable. When you just want to use the Python wrapper, you can read Run Your First Simulation with the Python SDK instead.

Preparation Before Running​

Choose an Authentication Method​

Currently the REST API uses Bearer access tokens. The example selects credentials in the following order:

  1. Use it directly when NEXUSFLOW_ACCESS_TOKEN has been set; if a refresh token is provided at the same time, the safe read request will be refreshed once after receiving 401.
  2. When there is only NEXUSFLOW_REFRESH_TOKEN, call POST /api/token/refresh/ first to obtain the access token.
  3. When neither token is available, use NEXUSFLOW_USERNAME and NEXUSFLOW_PASSWORD to call POST /api/token/ to log in.

Access tokens, refresh tokens, and passwords must not be written to source code, logs, or exception bodies. The production environment should be injected by the secret management service; the username and password method is only suitable for controlled joint debugging. See Authentication and Token Refresh for authentication response and account status errors.

Set Environment Variables​

Environment VariablesIs It Required?Description
NEXUSFLOW_BASE_URLYesPlatform root address, excluding /api; HTTPS should be used first
NEXUSFLOW_MODEL_IDYesThe UUID of the model to be run this time must be explicitly selected by the user or upstream business
NEXUSFLOW_ACCESS_TOKENAccording to authentication methodAlready have access token
NEXUSFLOW_REFRESH_TOKENAccording to authentication methodAlready have refresh token
NEXUSFLOW_USERNAME、NEXUSFLOW_PASSWORDAccording to authentication methodLogin username or email, and password
NEXUSFLOW_POLL_TIMEOUTNoTotal status polling time limit, default 600 seconds
NEXUSFLOW_RESULT_TIMEOUTNoThe total time limit for reading the result stream, default 120 seconds

Do not automatically run "first model in list". The model list is affected by permissions, filtering, sorting and paging, and the first item is not stable. When you need to find a model, read it in pages according to Model and Snapshot APIs, and then write the confirmed UUID into NEXUSFLOW_MODEL_ID.

The examples require Python 3.10 or higher and the requests and websocket-client libraries. Dependencies should be pre-installed in a controlled environment.

Which Interfaces Will This Call Go Through?​

StepsInterface or ConnectionCritical Uses
Confirm identityGET /api/users/me/Verify token and get current user
Read modelGET /api/models/{model_id}/Get model type and current_snapshot
Read space definitionGET /api/meta/{workspace_type}/Obtain components used in this job
Create jobPOST /api/jobs/Submit model diagram and component definition
Query jobsGET /api/jobs/{job_id}/Bounded polling status, progress and number of messages
Get connection ticketPOST /api/jobs/{job_id}/websocket-ticket/Get short-term, one-time results to connect tickets
Read results/ws/{job_id}?offset=...Read and resume in order of result message ID

current_snapshot in the model details is the current model graph data, not the snapshot UUID. When you create the job, put it in data.graph and put the space details components in data.definition.

The example pre-generates the platform job UUID as id for the create request. This way even if the create request times out, there is still an unambiguous UUID available for query. global.taskID in the graph data copy is the underlying computing operation identifier. The two cannot be mixed. For details, see Resource Identifiers.

Complete Python Example​

api_quickstart.py
from __future__ import annotations

import copy
import json
import os
import sys
import time
import uuid
from collections import Counter
from typing import Any
from urllib.parse import quote, urlencode, urlsplit, urlunsplit

import requests
from websocket import WebSocketException, create_connection


TERMINAL = {"success", "fault", "stopped"}
HTTP_TIMEOUT = (5.0, 60.0) # 建连超时、读取超时


class APIError(RuntimeError):
def __init__(self, message: str, status: int | None = None) -> None:
super().__init__(message)
self.status = status


class TransportError(RuntimeError):
pass


def env(name: str) -> str:
value = os.environ.get(name)
if not value:
raise RuntimeError(f"缺少环境变量:{name}")
return value


def positive_seconds(name: str, default: float) -> float:
value = float(os.environ.get(name, str(default)))
if value <= 0:
raise RuntimeError(f"{name} 必须大于 0")
return value


def message_from(payload: Any, fallback: str) -> str:
if isinstance(payload, dict):
for key in ("detail", "message", "error"):
value = payload.get(key)
if isinstance(value, str) and value:
return value
return fallback


class API:
def __init__(self) -> None:
self.base = env("NEXUSFLOW_BASE_URL").rstrip("/")
parts = urlsplit(self.base)
if parts.scheme not in {"http", "https"} or not parts.netloc:
raise RuntimeError("NEXUSFLOW_BASE_URL 不是有效的 HTTP(S) 地址")
if parts.username or parts.password:
raise RuntimeError("平台地址中不得包含用户名或密码")

self.session = requests.Session()
self.access = os.environ.get("NEXUSFLOW_ACCESS_TOKEN") or None
self.refresh_token = os.environ.get("NEXUSFLOW_REFRESH_TOKEN") or None
self.username = os.environ.get("NEXUSFLOW_USERNAME") or None
self.password = os.environ.get("NEXUSFLOW_PASSWORD") or None

def close(self) -> None:
self.session.close()

def url(self, path: str) -> str:
return f"{self.base}/{path.lstrip('/')}"

def decode(self, response: requests.Response) -> Any:
try:
payload = response.json()
except ValueError as exc:
raise APIError(
f"HTTP {response.status_code}:响应不是有效 JSON",
response.status_code,
) from exc
if not 200 <= response.status_code < 300:
raise APIError(
f"HTTP {response.status_code}:"
f"{message_from(payload, response.reason or '请求失败')}",
response.status_code,
)
# 业务接口通常使用 code/data/message;令牌接口直接返回令牌字段。
if isinstance(payload, dict) and payload.get("code") not in (None, 0):
raise APIError(message_from(payload, "业务请求失败"))
if isinstance(payload, dict) and "data" in payload:
return payload["data"]
return payload

def token_request(self, path: str, body: dict[str, str]) -> dict[str, Any]:
try:
response = self.session.post(
self.url(path), json=body, timeout=HTTP_TIMEOUT
)
except requests.RequestException as exc:
raise TransportError(f"认证连接失败:{type(exc).__name__}") from exc
data = self.decode(response)
if not isinstance(data, dict):
raise APIError("认证接口未返回对象")
return data

def set_tokens(self, data: dict[str, Any]) -> None:
access = data.get("access")
if not isinstance(access, str) or not access:
raise APIError("认证响应缺少 access")
self.access = access
if isinstance(data.get("refresh"), str) and data["refresh"]:
self.refresh_token = data["refresh"]

def refresh(self) -> None:
if not self.refresh_token:
raise APIError("访问令牌失效,且没有刷新令牌", 401)
self.set_tokens(
self.token_request(
"/api/token/refresh/", {"refresh": self.refresh_token}
)
)

def authenticate(self) -> None:
if self.access:
return
if self.refresh_token:
self.refresh()
return
if not self.username or not self.password:
raise RuntimeError("请提供令牌,或同时提供用户名和密码")
self.set_tokens(
self.token_request(
"/api/token/",
{"username": self.username, "password": self.password},
)
)
self.password = None

def request(
self,
method: str,
path: str,
*,
params: dict[str, Any] | None = None,
body: Any = None,
refresh_safe_get: bool = False,
) -> Any:
method = method.upper()
try:
response = self.session.request(
method,
self.url(path),
params=params,
json=body,
headers={"Authorization": f"Bearer {self.access}"},
timeout=HTTP_TIMEOUT,
)
except requests.RequestException as exc:
raise TransportError(f"{method} {path} 连接或等待响应失败") from exc

if (
response.status_code == 401
and method == "GET"
and refresh_safe_get
and self.refresh_token
):
self.refresh()
return self.request(method, path, params=params, body=body)
return self.decode(response)

def websocket_url(self, job_id: str, ticket: str, offset: int) -> str:
parts = urlsplit(self.base)
scheme = "wss" if parts.scheme == "https" else "ws"
path = f"{parts.path.rstrip('/')}/ws/{quote(job_id, safe='')}"
query = urlencode({"offset": offset, "batch": 200, "ticket": ticket})
return urlunsplit((scheme, parts.netloc, path, query, ""))


def poll_job(api: API, job_id: str, timeout: float) -> dict[str, Any]:
deadline = time.monotonic() + timeout
last = None
while time.monotonic() < deadline:
job = api.request(
"GET",
f"/api/jobs/{quote(job_id, safe='')}/",
params={
"fields": "id,status,progress,msg_num,result_status,finished_at"
},
refresh_safe_get=True,
)
current = (job.get("status"), job.get("progress"), job.get("msg_num"))
if current != last:
print(f"job={job_id} status={current[0]} progress={current[1]}")
last = current
if job.get("status") in TERMINAL:
return job
time.sleep(2)
raise TimeoutError(f"轮询超时,任务仍可能运行:{job_id}")


def ticket_for(api: API, job_id: str) -> str:
path = f"/api/jobs/{quote(job_id, safe='')}/websocket-ticket/"
try:
data = api.request("POST", path)
except APIError as exc:
# 票据短期且一次性;401 时刷新后重新申请,不复用旧票据。
if exc.status != 401 or not api.refresh_token:
raise
api.refresh()
data = api.request("POST", path)
if not isinstance(data, dict) or not isinstance(data.get("ticket"), str):
raise APIError("连接票据响应缺少 ticket")
return data["ticket"]


def read_results(
api: API, job_id: str, total: int, timeout: float
) -> tuple[int, Counter[str], list[dict[str, Any]]]:
deadline = time.monotonic() + timeout
offset = 0
failures = 0
counts: Counter[str] = Counter()
samples: list[dict[str, Any]] = []

while offset < total:
remaining = deadline - time.monotonic()
if remaining <= 0 or failures > 3:
raise TimeoutError(f"结果未读完整:offset={offset}, total={total}")

socket = None
try:
ticket = ticket_for(api, job_id)
socket = create_connection(
api.websocket_url(job_id, ticket, offset),
timeout=max(1.0, min(15.0, remaining)),
)
while offset < total:
frame = socket.recv()
if frame in (None, ""):
break
batch = json.loads(frame)
if isinstance(batch, dict):
batch = [batch]
if not isinstance(batch, list):
raise APIError("结果帧不是 JSON 数组或对象")
for item in batch:
message_id = item.get("id") if isinstance(item, dict) else None
if not isinstance(message_id, int):
raise APIError("结果消息缺少整数 id")
if message_id < offset: # 重连后的重复消息
continue
if message_id != offset:
raise APIError(
f"结果消息有缺口:预期 {offset},收到 {message_id}"
)
counts[str(item.get("type", "unknown"))] += 1
if len(samples) < 5:
samples.append(
{
"id": message_id,
"type": item.get("type"),
"key": item.get("key"),
}
)
offset += 1
failures = 0
except (WebSocketException, OSError):
failures += 1
finally:
if socket is not None:
socket.close()
return offset, counts, samples


def main() -> None:
model_id = env("NEXUSFLOW_MODEL_ID")
poll_timeout = positive_seconds("NEXUSFLOW_POLL_TIMEOUT", 600)
result_timeout = positive_seconds("NEXUSFLOW_RESULT_TIMEOUT", 120)
api = API()
job_id = str(uuid.uuid4())

try:
api.authenticate()
me = api.request(
"GET",
"/api/users/me/",
params={"fields": "id,username"},
refresh_safe_get=True,
)
print(f"authenticated user={me['username']} id={me['id']}")

model = api.request(
"GET",
f"/api/models/{quote(model_id, safe='')}/",
params={"fields": "id,name,type,current_snapshot"},
refresh_safe_get=True,
)
if not isinstance(model.get("current_snapshot"), dict):
raise APIError("指定模型没有可运行的 current_snapshot")

workspace_type = model.get("type")
workspace = api.request(
"GET",
f"/api/meta/{quote(str(workspace_type), safe='')}/",
refresh_safe_get=True,
)
if not isinstance(workspace.get("components"), dict):
raise APIError("工作台空间响应缺少 components")

graph = copy.deepcopy(model["current_snapshot"])
global_data = graph.setdefault("global", {})
if not isinstance(global_data, dict):
raise APIError("模型快照中的 global 不是对象")
global_data["taskID"] = str(uuid.uuid4())

body = {
"id": job_id,
"workspace_type": workspace_type,
"model_id": model["id"],
"data": {"graph": graph, "definition": workspace["components"]},
}
try:
created = api.request("POST", "/api/jobs/", body=body)
except TransportError as exc:
raise TransportError(
"任务创建结果无法确认;请先查询 "
f"job_id={job_id},不要直接重复创建"
) from exc
if str(created.get("id")) != job_id:
raise APIError("任务创建响应中的 id 与请求不一致")
print(f"created job={job_id} model={model['name']}")

job = poll_job(api, job_id, poll_timeout)
total = int(job.get("msg_num") or 0)
if job.get("result_status") == "expired":
raise APIError("任务结果已过期,无法读取结果流", 410)
if total > 0 and job.get("result_status") != "available":
raise APIError(f"任务结果流不可读取:{job.get('result_status')}")

received, counts, samples = read_results(
api, job_id, total, result_timeout
)
print(f"received={received} by_type={dict(counts)} samples={samples}")
if job.get("status") != "success":
raise RuntimeError(f"任务以非成功终态结束:{job.get('status')}")
finally:
api.close()


if __name__ == "__main__":
try:
main()
except Exception as exc:
# 不打印令牌、密码、请求头、完整模型或完整结果。
print(f"api quickstart failed: {type(exc).__name__}: {exc}", file=sys.stderr)
raise SystemExit(1)

How to Judge Results and Failures​

Bounded Wait, No Automatic Stop​

Polling has a total time limit, and a single HTTP request also has connection establishment and read timeouts. The polling timeout only means that the script has stopped waiting, not that the server job has stopped. Keep job_id and continue querying; only call POST /api/jobs/{job_id}/terminate/ when the business explicitly requires cancellation. Stop requests are also write operations. After timeout, you should check the status first and cannot blindly resend.

Create Timeout First Query​

The script generates the platform job UUID before creation. POST /api/jobs/ When the connection is interrupted or the wait for response times out, the server may have created a job. Use the UUID to query details first, and then decide on subsequent actions. There will be a conflict if the same UUID is created again, which does not mean that a second job is created.

The actual error HTTP status of each detail endpoint is not completely uniform, and "not found" cannot be written as 404. The caller should also check the HTTP status, code in the business response, and the endpoint document; 2xx but code is not 0 and still fails. See API Conventions and Status and Error Reference for complete pagination, timeout, retry and error classification.

The Result Is Continued by Offset​

msg_num in the job details is the total number of result messages. The top level of the resulting message id increments from 0 and continues from offset=19 after reading message 18. The connection ticket is short-term and can only be used once; after disconnection, a new ticket should be applied for according to the latest offset, duplicate messages should be skipped, and processing should be stopped when an ID gap occurs.

When result_status is expired, connecting to the ticket interface will return 410 Gone. The final state of the job may still be success, but the expired results cannot be recovered through repeated reading. Large results should be saved while reading. Only the count and the first five summaries are retained on this page; see Real-Time Job Data Over WebSocket and Job, Control, and Result APIs for production-level consumption strategies.

Close Local Resources​

The script always closes the HTTP session and each resulting connection also closes the WebSocket. The token is only saved in process memory and is not written to a file. Jobs, results or source models will not be deleted when the script ends; server resources are managed by the platform retention policy, and external programs are not allowed to directly clean up the platform's internal storage.

Next Steps​