Guide
Notebooks: security and data science on the same data
Your security team triages detections in Logthread. Your data scientists want the same events in pandas or Polars. With the query API both read the same rows, and each team's work feeds the other:
- a pattern found in a notebook becomes a detection;
- the analysts' true and false positive marks become a dataset for tuning the rules.
You need Python 3.9 or later, requests, and pandas or Polars. All three have permissive open-source licences. Reading Parquet with pandas also needs pyarrow.
1. Create a read-only key#
On Developers → Keys → API keys, choose Create API key, then tick Query API (notebooks). The Use from a notebook card on that page shows a snippet built from your own busiest service, checked against your last hour of data.
Keep the key out of the notebook:
export LOGTHREAD_API_KEY=ltk_...2. Read logs into a dataframe#
import os, requests, pandas as pd
API = "https://logthread.com/api/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['LOGTHREAD_API_KEY']}"}
def query(text, language="ltql", max_rows=10_000, **body):
"""All pages of a query (newest first for LTQL records), as a list of rows."""
rows, cursor = [], None
while True:
r = requests.post(f"{API}/query", headers=HEADERS, timeout=60, json={
"language": language, "query": text, "limit": 1000 if language == "ltql" else 10_000,
**body, **({"cursor": cursor} if cursor else {})})
r.raise_for_status()
answer = r.json()
body.update(answer["window"]) # later pages read the same window
rows += answer["rows"]
cursor = answer["next_cursor"]
if not cursor or len(rows) >= max_rows:
return answer, rows[:max_rows]
answer, rows = query("event.action:login_failed", **{"from": "2026-11-28T00:00:00Z"})
logins = pd.json_normalize(rows) # attributes.user, attributes.source.ip, ...stats and SQL answers come as a table:
answer, rows = query("event.action:login_failed | stats count() by source.ip", **{"from": "2026-11-22T00:00:00Z"})
per_ip = pd.DataFrame(rows, columns=[c["name"] for c in answer["columns"]])
answer, rows = query(
"SELECT toStartOfHour(Timestamp) AS hour, ServiceName AS service, count() AS n "
"FROM obs.logs WHERE Timestamp >= {from:DateTime64(3)} AND Timestamp < {to:DateTime64(3)} "
"AND SeverityNumber >= {min:UInt8} GROUP BY hour, service ORDER BY hour",
language="sql", params={"min": 17}, **{"from": "2026-11-22T00:00:00Z"})
errors = pd.DataFrame(rows, columns=[c["name"] for c in answer["columns"]])With Polars, use pl.DataFrame(rows, schema=[c["name"] for c in answer["columns"]], orient="row").
3. Pull a month as Parquet#
Paged JSON is for up to tens of thousands of rows. For more, export:
with requests.post(f"{API}/export", headers=HEADERS, stream=True, timeout=600, json={
"query": "service:checkout", "from": "2026-11-01T00:00:00Z", "to": "2026-11-29T00:00:00Z"}) as r:
r.raise_for_status()
with open("checkout.parquet", "wb") as fh:
for chunk in r.iter_content(65536):
fh.write(chunk)
df = pd.read_parquet("checkout.parquet") # or polars.read_parquet4. Measure and tune your detections#
def table(name, **body):
rows, cursor, columns = [], None, []
while True:
r = requests.post(f"{API}/tables/{name}", headers=HEADERS, timeout=60,
json={**body, **({"cursor": cursor} if cursor else {})})
r.raise_for_status()
page = r.json()
columns, cursor = page["columns"], page["next_cursor"]
rows += page["rows"]
if not cursor:
return pd.DataFrame(rows, columns=[c["name"] for c in columns])
incidents = table("incidents", **{"from": "2026-09-01T00:00:00Z"})
marked = incidents[incidents.is_detection & incidents.outcome.isin(["true_positive", "false_positive"])]
precision = (marked.outcome == "true_positive").groupby(marked.rule_name).mean().sort_values()
print(precision.head(10)) # the noisiest detections first
print(incidents.groupby("rule_name").time_to_ack_s.median())rules gives each rule's query, and situations gives each Situation's score and size.
5. Turn a finding into a detection#
Every answer carries links. Open answer["links"]["alert"] in the app: the alert editor opens with your query and shows its 24-hour backtest and match count. You set the threshold and channels, then turn it on. links["save_search"] saves the query for the team. The key itself never writes.
6. Keep the analysis with the case#
With a key that also has Add analyses to investigation spaces, save the query and its chart in the investigation space that holds the case:
requests.post(f"{API.removesuffix('/v1')}/investigations/spaces/{space_id}/analyses", headers=HEADERS, json={
"title": "Failed sign-ins per source IP", "language": "ltql", "range": "7d", "chart": "bar",
"query": "event.action:login_failed | stats count() by source.ip",
"note": "Three IPs make 80% of failures since Tuesday"}).raise_for_status()The analyst sees it under Analyses in the space, runs it again with one click, and opens it in Explore or as an alert.