OpenCTI Hands-on Handbook繁中

OpenCTI API Tutorial: GraphQL and Python Automation

Query the GraphQL API with Python, supply tokens safely, handle HTTP and GraphQL errors, and understand pagination, filtering and idempotence.

Handbook v1.10.1OpenCTI 7.261124.0About 6 minutes

Begin OpenCTI API automation with one safe read.

When you find yourself repeating the same searches, extracting the same fields, and manually comparing changes for the third time, automation is worth considering. The first script can have a small goal: authenticate a token and retrieve the platform version, then expand to identifiable teaching data. Understanding each step matters more than immediately writing hundreds of lines of import code.

OpenCTI uses GraphQL. Send requests to the platform's /graphql endpoint, with queries and variables in JSON and authentication through a bearer token. If the platform has a path prefix, include it in the API URL. Queries read data and mutations write it; account permissions still determine which records and operations are available. Official API documentation

Protect the token before letting the script sign in.

Create a separate integration account with the capabilities and data scope its work requires. On 7.x, pay particular attention to the role's token-use capability and token expiration. Newer versions display a token only once when it is created; if it is lost, generate a replacement rather than expecting to retrieve the original value from the interface. This differs from the persistent token screens shown in many older articles.

Do not put a practice token in Python source, command-line arguments, or Git. The example below prompts for the platform URL and reads the token with hidden input. That addresses input and storage in this example only; scheduled work still needs appropriate secret management and rotation in your deployment environment.

Minimal read example · Save as api-check.py; output depends on your environment
import getpass
import json
import urllib.error
import urllib.request

base_url = input("OpenCTI URL: ").strip().rstrip("/")
token = getpass.getpass("API token(不顯示): ")
payload = json.dumps({
    "query": "query { about { version } }"
}).encode("utf-8")
request = urllib.request.Request(
    base_url + "/graphql",
    data=payload,
    headers={
        "Content-Type": "application/json",
        "Authorization": "Bearer " + token,
    },
    method="POST",
)
try:
    with urllib.request.urlopen(request, timeout=30) as response:
        result = json.load(response)
except (json.JSONDecodeError, UnicodeDecodeError):
    raise SystemExit("回應不是有效 JSON:請檢查 API 路徑或代理登入頁。")
except urllib.error.HTTPError as error:
    raise SystemExit(f"HTTP 錯誤 {error.code}:請核對 API 路徑與代理設定。")
except (urllib.error.URLError, TimeoutError):
    raise SystemExit("連線失敗:請檢查網址、網路與服務狀態。")

if not isinstance(result, dict):
    raise SystemExit("回應不是預期的 JSON 物件,請核對 API 位址。")
if result.get("errors"):
    raise SystemExit("GraphQL 回報錯誤:請檢查 token、權限與查詢。")
data = result.get("data") or {}
about = data.get("about") if isinstance(data, dict) else None
version = about.get("version") if isinstance(about, dict) else None
if not version:
    raise SystemExit("回應缺少預期欄位,請核對此版本 schema。")
print("平台版本:", version)

Run python3 api-check.py and enter your own platform URL. The public website octi-zh.sectools.tw serves the handbook; it is not the lab platform's API. Success means retrieving a version value. This code is a teaching example. For complete Docker, API, and data-workflow verification, read chapter 13: test records and reproduction steps and compare the actual commands, outputs, and verification boundaries.

HTTP success does not guarantee query success.

For writes, verify both the account's ability to modify that data type and its confidence ceiling. Login does not imply permission to update every object. Handle at least three layers: network reachability, the HTTP response, and GraphQL errors. HTTP 200 can still contain partial data or omit a required field. A script must not declare success merely because it received JSON.

ObservationNext step
Connection refused or timed outCheck service state, URL, port, and proxy before regenerating a token.
The response is an HTML login pageCheck the API path and reverse proxy; do not parse HTML as JSON.
Authentication or permission errorConfirm that the token is unexpired and the account is enabled with the required capabilities.
A field or argument does not existCheck your deployed version's schema instead of copying a query from another version.
Fewer records than expectedCheck pagination, filters, time range, and account visibility.

Retries also need limits. Transient network errors may justify waiting and retrying; an unknown field or invalid token does not justify endless resubmission. Record request times, operation identifiers, error types, and retry counts so another maintainer can investigate, while keeping Authorization headers and sensitive response content out of logs.

Inspect the schema before writing pagination and filters.

Do not invent field names from memory. Choose an object type, then check the matching version's arguments, return fields, and permission requirements. Playground exploration may be restricted by configuration. If introspection is unavailable, consult the schema at the corresponding official repository version instead of weakening production protections for one query.

Use an explicit small batch size for list queries and follow the pagination information the query returns until there is no next page. Preserve the last successfully processed position, distinguishing a successful read from a successful downstream write. Advancing a cursor too early can skip data after a restart; advancing it too late can resend records, so the receiving system also needs a deduplication strategy.

Validate filters on a small scope. For SecTools Lab reports, first confirm one condition finds the expected record, then add dates and markings. Intersections, unions, and nested groups can easily produce an empty result. Build filters using the official FilterGroup format instead of treating visible labels as API keys. Official filter reference

Treat the script as a small product someone else will maintain.

Even if you are its only user today, define its inputs and outputs. Inputs include the platform URL, query scope, time range, and credential source. Outputs should distinguish successful, skipped, and failed counts. If a colleague must read a thousand log lines to determine whether today's run succeeded, the script is not finished.

Start with a test matrix: a valid token returns a version; an invalid token ends unsuccessfully; a wrong URL reports a connection or path problem; an empty list completes normally with a zero count; a missing required field stops processing. Add scheduling after these outcomes are predictable. These form your integration contract, and results must be recorded in the deployment environment.

For writes, add a preview stage that lists objects to create, update, or skip without immediately submitting mutations. Execute only after reviewing the plan, and retain identifiers from before the change. In particular, the API's ability to perform bulk changes or deletion does not imply every search result should be modified.

A failed scheduled run should stop at a position you can explain. Preserve the last successful batch, remaining work, and error reason so recovery is evidence-based. A lone failure message without a record of what was already written makes reruns more likely to amplify the problem.

When should you use PyCTI?

For work involving several object types, relationships, and STIX data, consider the official Python client, PyCTI. Interfaces such as OpenCTIApiClient reduce repetitive request-handling code. Pin a version compatible with your deployment in a virtual environment, retain a dependency list, and consult examples for that version. Do not let an unnoticed package upgrade change integration behavior.Official Python client documentation

Define object identity before writing. When the same source report arrives again, should it update the existing record or create another? Names alone are usually too fragile; retain a mapping between source identifiers and platform IDs. Test repeated identical input, missing fields, interruption, and recovery. Automation quality often becomes clear on the second run.

Chapter acceptance check

You can query the version without exposing a token, distinguish network and GraphQL errors, explain pagination's stopping condition, and plan for reruns and partial failures. Before bulk writes, exercise these scenarios with a small fictional dataset in an isolated lab.

Make one small workflow reliable before expanding it. For another security problem worth automating, continue exploring tools and practical articles at SecTools.tw.

Every step is worth recording

Finished this chapter?

Mark it when you are ready. Opening or scrolling through a chapter does not complete it automatically. You can undo your choice.

View my progress

Progress is saved only in this browser. No account or automatic device sync. Clearing site data also removes progress.

KEEP YOUR CURIOSITY ALIVE

Make sense of intelligence.
Keep exploring real security questions.

Explore incidents, perspectives and tools at SecTools.tw, and find your next question worth investigating.

SecTools.tw

Search the handbook