Skip to content

Module 23: Serve the graph: HTTP and Arrow Flight

Learning objectives

By the end of this module, you can:

  • O1. Start the HTTP API with ddigraph serve, and send a file to /detect, /preview, /validate and /export.
  • O2. Turn on /load and /jobs with DDIGRAPH_API_TOKEN, queue a load, and follow its job to the end.
  • O3. Set the rate and upload limits, and explain the 401, 403, 413 and 429 answers.
  • O4. Export a graph as Arrow files with ddigraph export --format arrow, and read them with pyarrow.
  • O5. Serve the store with ddigraph serve --flight, and read a dataset's nodes and relationships with a pyarrow.flight client.

Prerequisites: Module 11

Time: 50 min self-paced / 65 min instructor-led.

Needs: No server to install: both servers run on your machine. Install the api and arrow extras. The examples use curl.

New in this module: ddigraph serve, /health, /detect, /preview, /validate, /export, /load, /jobs/{job_id}, DDIGRAPH_API_TOKEN, DDIGRAPH_API_PUBLIC_READS, DDIGRAPH_API_RATE_LIMIT, DDIGRAPH_API_MAX_UPLOAD_MB, ddigraph export --format arrow, ddigraph serve --flight, ddigraph.flight.server, ddigraph.flight.ticket, pyarrow.flight


1. Two ways to serve the graph

So far you ran ddigraph yourself, in Python or at the command line. Often someone else needs it: a web form, a program in another language, or a colleague with no Python. ddigraph has two servers for them:

  • The HTTP API takes a DDI file and answers about it. It detects the flavor, previews the graph, checks the XSD and exports RDF or JSON. With a token, it also loads the file into Neo4j. Anything that can send a web request can use it.
  • Arrow Flight serves the graphs you keep in the store (Module 11) as Arrow tables. Arrow is a column format that pandas, Polars, DuckDB, R and many other tools read with no conversion. Flight sends those tables over the network, fast.

The HTTP API works on files you send it. Flight works on the store it reads. They do different jobs, and you can run both.

Install the two extras. api adds FastAPI, uvicorn and python-multipart. arrow adds pyarrow:

pip install "ddigraph[api,arrow]"

2. Start the HTTP API

This command starts the server. It runs until you stop it with Ctrl-C:

ddigraph serve

It listens on 127.0.0.1:8000, so only programs on your machine can reach it. --host and --port change that. While it runs, http://127.0.0.1:8000/docs lists every endpoint, and lets you try each one in a browser. An endpoint is one address the server answers at, such as /health.

The scripts in this module do not use port 8000. Each one starts its own server on a free port, waits until it answers, uses it, and stops it at the end. So they run on their own, and never clash with a server you left running. The first lines of each script do that:

# Start the server on a free port, and stop it when the script ends
PORT=$(python -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])')
ddigraph serve --port "$PORT" > server.log 2>&1 &
SERVER=$!
trap 'kill "$SERVER"' EXIT
URL="http://127.0.0.1:$PORT"
# Wait until /health answers, for at most 10 seconds
for _ in $(seq 50); do curl -sf "$URL/health" > /dev/null && break; sleep 0.2; done

curl -s "$URL/health"
echo

Expected output:

{"status":"ok","version":"0.6.0","neo4j":"..."}

/health always answers, and needs no token. neo4j is "ok" when the Neo4j of Module 7 answers within 3 seconds, and "unreachable" when it does not. The other endpoints in this section never open the database, so they work either way. server.log keeps what the server printed.

3. Send a file

Every endpoint but /health and /jobs takes one file, sent as the form field file. With curl, -F file=@PATH sends it. Options go in the query string, after ?, as in /validate?max_issues=1:

# Start the server on a free port, and stop it when the script ends
PORT=$(python -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])')
ddigraph serve --port "$PORT" > server.log 2>&1 &
SERVER=$!
trap 'kill "$SERVER"' EXIT
URL="http://127.0.0.1:$PORT"
# Wait until /health answers, for at most 10 seconds
for _ in $(seq 50); do curl -sf "$URL/health" > /dev/null && break; sleep 0.2; done

curl -s -F file=@tests/fixtures/lfs_codebook.xml "$URL/detect"
echo
curl -s -F file=@tests/fixtures/lfs_cdi.xml "$URL/validate"
echo
# A draft of the questionnaire: its question texts say en_CA, where XML wants en-CA
sed 's/<d:Text xml:lang="en">/<d:Text xml:lang="en_CA">/' tests/fixtures/lfs_lifecycle.xml > draft.xml
curl -s -F file=@draft.xml "$URL/validate?max_issues=1"
echo
curl -s -F file=@tests/fixtures/lfs_lifecycle.xml \
  "$URL/export?format=json&dataset_id=m23-survey" -o survey.json
python -c 'import json; print(json.load(open("survey.json"))["summary"]["nodes_by_label"])'
curl -s -X POST "$URL/load"
echo

Expected output:

{"format":"codebook"}
{"valid":true,"flavor":"cdi","version":null,"schema":"ddi-cdi.xsd","issues":[]}
{"valid":false,"flavor":"lifecycle","version":"3_3","schema":"instance_3_3.xsd","issues":[{"line":108,"column":0,"message":"Element '{ddi:datacollection:3_3}Text', attribute '{http://www.w3.org/XML/1998/namespace}lang': 'en_CA' is not a valid value of the atomic type 'xs:language'."}]}
{'Category': 23, 'Code': 23, 'CodeList': 6, 'Concept': 5, 'Dataset': 1, 'IfThenElse': 1, 'Instrument': 1, 'QuestionConstruct': 8, 'QuestionItem': 8, 'Sequence': 2, 'Universe': 2, 'Variable': 7}
{"detail":"Set DDIGRAPH_API_TOKEN to enable /load, /bootstrap and /jobs"}

Each answer is JSON, as ddigraph detect, validate and export would say it:

  • /detect names the flavor.
  • /validate checks the file against its official XSD. The survey's DDI-CDI file is valid. The draft is a copy of its questionnaire with one mistake, made in each of its 8 questions: the question text's language is en_CA, the form a computer's locale uses, where XML wants en-CA. max_issues=1 keeps the first issue only. An invalid file still gets status 200, so read valid, not the status. It is the XSD check only, not SHACL.
  • /export gives back the exported file: Turtle by default, or jsonld, ntriples, rdfxml or json. -o saves it. The JSON summary counts the survey's nodes by label: 8 questions, 6 code lists with their 23 codes and categories, 7 variables, and so on. The formats that write a folder, csv, arrow and neo4j-import, get 400: use ddigraph export for them.
  • /load is off, with 403, while no token is set. Section 4 turns it on.

/preview summarises the graph the file makes. format=mermaid gives a Mermaid diagram, which a web page can draw:

# Start the server on a free port, and stop it when the script ends
PORT=$(python -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])')
ddigraph serve --port "$PORT" > server.log 2>&1 &
SERVER=$!
trap 'kill "$SERVER"' EXIT
URL="http://127.0.0.1:$PORT"
# Wait until /health answers, for at most 10 seconds
for _ in $(seq 50); do curl -sf "$URL/health" > /dev/null && break; sleep 0.2; done

curl -s -F file=@tests/fixtures/lfs_lifecycle.xml "$URL/preview?format=mermaid&dataset_id=m23-survey"

The page draws what the server sent back:

graph LR
    Category["Category<br/>23"]
    Code["Code<br/>23"]
    QuestionConstruct["QuestionConstruct<br/>8"]
    QuestionItem["QuestionItem<br/>8"]
    Variable["Variable<br/>7"]
    CodeList["CodeList<br/>6"]
    Concept["Concept<br/>5"]
    Sequence["Sequence<br/>2"]
    Universe["Universe<br/>2"]
    Dataset["Dataset<br/>1"]
    IfThenElse["IfThenElse<br/>1"]
    Instrument["Instrument<br/>1"]
    Code -->|HAS_CATEGORY 23| Category
    CodeList -->|CONTAINS 23| Code
    Variable -->|REFERENCES_QUESTION 9| QuestionItem
    QuestionConstruct -->|REFERENCES_QUESTION 8| QuestionItem
    QuestionItem -->|USES_CONCEPT 8| Concept
    Sequence -->|HAS_CONSTRUCT 7| QuestionConstruct
    Variable -->|IN_UNIVERSE 7| Universe
    Variable -->|USES_CONCEPT 7| Concept
    QuestionItem -->|USES_CODELIST 6| CodeList
    Variable -->|USES_CODELIST 5| CodeList
    Dataset -->|HAS_ENTRY_POINT 1| Instrument
    IfThenElse -->|ELSE 1| Sequence
    IfThenElse -->|THEN 1| QuestionConstruct
    Instrument -->|HAS_CONSTRUCT 1| Sequence
    Sequence -->|HAS_CONSTRUCT 1| IfThenElse

The diagram is the survey's questionnaire as a graph. The instrument starts a sequence of question constructs, and an IfThenElse sends people who worked last week to HOURS, and the others to the job search questions. Each question uses a concept and, for most, a code list.

The server saves each upload in a temporary folder, and deletes it when the request ends. So a node's source is the path of that temporary copy, such as /tmp/ddigraph-api-.../upload.xml, not your file's name. The HTTP API page lists every parameter of every endpoint.

4. Turn on writes: the token, /load and /jobs

/load writes to Neo4j, so the server asks for a token: a secret string that a client sends to prove it may write. You choose it, and set it in DDIGRAPH_API_TOKEN before you start the server. A client sends it in an Authorization: Bearer header.

Once a token is set, every endpoint but /health needs it, reads included. A missing or wrong token gets 401. The server checks the token before it reads the upload, so a refused file never reaches its disk.

A load can take minutes, so /load does not wait. It answers 202 at once, with a job ID. One worker runs the jobs in the order they arrive. GET /jobs/{job_id} tells you how a job is going: queued, running, succeeded or failed. You ask again until it is done. This is called polling.

The script below uses dry_run=true, which reads and counts the file but writes nothing, so it needs no Neo4j. Without it, the job loads the file into the Neo4j that DDIGRAPH_NEO4J_URI names, as ddigraph load does:

export DDIGRAPH_API_TOKEN="$(python -c 'import secrets; print(secrets.token_urlsafe(32))')"
# Start the server on a free port, and stop it when the script ends
PORT=$(python -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])')
ddigraph serve --port "$PORT" > server.log 2>&1 &
SERVER=$!
trap 'kill "$SERVER"' EXIT
URL="http://127.0.0.1:$PORT"
# Wait until /health answers, for at most 10 seconds
for _ in $(seq 50); do curl -sf "$URL/health" > /dev/null && break; sleep 0.2; done
AUTH="Authorization: Bearer $DDIGRAPH_API_TOKEN"

curl -s -F file=@tests/fixtures/lfs_lifecycle.xml "$URL/detect"
echo
curl -s -H "$AUTH" -F file=@tests/fixtures/lfs_lifecycle.xml "$URL/detect"
echo
curl -s -H "$AUTH" -F file=@tests/fixtures/lfs_lifecycle.xml \
  "$URL/load?dataset_id=m23-survey&dry_run=true" -o job.json
cat job.json
echo
JOB=$(python -c 'import json; print(json.load(open("job.json"))["job_id"])')
# Poll the job until it ends, for at most 10 seconds
for _ in $(seq 50); do
  curl -s -H "$AUTH" "$URL/jobs/$JOB" -o status.json
  grep -qE '"status":"(succeeded|failed)"' status.json && break
  sleep 0.2
done
python -m json.tool status.json

Expected output:

{"detail":"Missing or wrong bearer token"}
{"format":"lifecycle"}
{"job_id":"...","status":"queued"}
{
    "job_id": "...",
    "kind": "load",
    "status": "succeeded",
    "created_at": "...",
    "started_at": "...",
    "finished_at": "...",
    "result": {
        "flavor": "lifecycle",
        "target": "...",
        "dataset_id": "m23-survey",
        "nodes_written": 87,
        "relationships_written": 108,
        "stubs": 0,
        "references": 85,
        "resolved": 85,
        "unresolved": {},
        "conflicts": [],
        "duration_s": ...,
        "dry_run": true,
        "nodes_removed": 0,
        "relationships_removed": 0,
        "generation": null,
        "delta_from": null
    },
    "error": null
}

The result holds what ddigraph load --json prints: the survey's 87 nodes and 108 relationships, and its 85 references, all resolved. A failed job has "result": null and an error that says why. The server keeps the last 100 finished jobs, until it restarts.

Two more settings change who needs the token:

  • DDIGRAPH_API_PUBLIC_READS=true lets /detect, /preview, /validate and /export answer without it. /load and /jobs still need it.
  • A blank DDIGRAPH_API_TOKEN counts as no token, so writes stay off.

The server speaks plain HTTP. Anyone on the network path can read a token sent to it. Before you open the server to a network, put it behind a proxy that adds TLS, the encryption behind https://.

5. Limits: requests and upload size

A server open to others needs limits. ddigraph has two, set like the token, before the server starts:

  • DDIGRAPH_API_RATE_LIMIT is how many requests one client may send in a minute (default 60). A client that has been quiet can send them all at once. After that, it gets one more every 60 / limit seconds. A request over the limit gets 429, and a Retry-After header with the seconds to wait. /health does not count. 0 turns the limit off.
  • DDIGRAPH_API_MAX_UPLOAD_MB is the largest file, in megabytes (default 100). A larger one gets 413.

The script below sets a limit of 3 requests a minute and 1 MB, then sends a 2 MB file and three small ones:

export DDIGRAPH_API_RATE_LIMIT=3 DDIGRAPH_API_MAX_UPLOAD_MB=1
# Start the server on a free port, and stop it when the script ends
PORT=$(python -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])')
ddigraph serve --port "$PORT" > server.log 2>&1 &
SERVER=$!
trap 'kill "$SERVER"' EXIT
URL="http://127.0.0.1:$PORT"
# Wait until /health answers, for at most 10 seconds
for _ in $(seq 50); do curl -sf "$URL/health" > /dev/null && break; sleep 0.2; done

python -c 'open("big.xml", "w").write("<a>" + "x" * 2_000_000 + "</a>")'
curl -s -w ' %{http_code}\n' -F file=@big.xml "$URL/detect"
for _ in 1 2 3; do
  curl -s -w ' %{http_code}\n' -F file=@tests/fixtures/lfs_lifecycle.xml "$URL/detect"
done

Expected output:

{"detail":"Upload is larger than 1 MB. Raise DDIGRAPH_API_MAX_UPLOAD_MB to accept it."} 413
{"format":"lifecycle"} 200
{"format":"lifecycle"} 200
{"detail":"Rate limit reached (3 requests a minute per client). Try again in ... s."} 429

-w ' %{http_code}\n' makes curl print the status code after the body. The big file counts as a request too, so the fourth request is the one over the limit.

Both limits are checked from the request's headers, before the server reads the body. curl states the size of what it sends, so the 413 comes at once, and the 2 MB never reach the server's disk.

The server tells clients apart by their IP address, and it ignores the X-Forwarded-For header, since any client can write it. Behind a proxy, every request then comes from the proxy, so all clients share one limit. The HTTP API page shows how to run uvicorn so that it trusts your proxy.

6. Arrow files

The next two sections move from files sent in to graphs sent out, as Arrow tables. Arrow keeps each column's type: a number stays a number and a list stays a list, where CSV turns them all into text.

ddigraph export --format arrow writes a folder with two Arrow files. nodes.arrow has one row per node, and relationships.arrow one row per relationship. The columns are those of the CSV export: key, node_label, identity, source, flavor, line and unresolved, then one column per property. A relationship names its ends by key, in start and end. pyarrow reads each file into a table:

ddigraph export tests/fixtures/lfs_codebook.xml --format arrow -o m23-arrow \
  --dataset-id m23-codebook
python - <<'PY'
import pyarrow.ipc

nodes = pyarrow.ipc.open_file("m23-arrow/nodes.arrow").read_all()
relationships = pyarrow.ipc.open_file("m23-arrow/relationships.arrow").read_all()
print(nodes.num_rows, "nodes,", relationships.num_rows, "relationships")
print(nodes.column_names[:7])
print(relationships.column_names)

# Join each end to its node's label, then count the shapes
labels = nodes.select(["key", "node_label"])
shapes = (
    relationships.join(labels.rename_columns(["start", "start_label"]), "start")
    .join(labels.rename_columns(["end", "end_label"]), "end")
    .group_by(["start_label", "type", "end_label"])
    .aggregate([("type", "count")])
    .sort_by([("type_count", "descending"), ("type", "ascending"), ("start_label", "ascending")])
)
for row in shapes.slice(0, 4).to_pylist():
    print(f"({row['start_label']})-[{row['type']}]->({row['end_label']}) {row['type_count']}")
PY

Expected output:

Wrote m23-arrow
Format: arrow
Nodes: 80  Relationships: 48
80 nodes, 48 relationships
['key', 'node_label', 'identity', 'source', 'flavor', 'line', 'unresolved']
['start', 'type', 'end', 'ordinal', 'resolution']
(Variable)-[USES_CATEGORY]->(Category) 21
(Variable)-[IN_FILE]->(DataFile) 7
(Variable)-[USES_CONCEPT]->(Concept) 7
(Variable)-[ASKED_AS]->(Question) 5

join matches rows of two tables on a column, here a relationship's start or end and a node's key. group_by and aggregate count the rows of each shape. The four most common shapes describe the survey's codebook: its 7 variables use 21 categories in all, each sits in the data file and has a concept, and 5 of them were asked as a question. A table's to_pandas() gives a DataFrame, and Polars and DuckDB read the table as it is.

7. Arrow Flight over the store

A file is a copy made once. Arrow Flight serves the store live: a client asks for a dataset, and gets its nodes and relationships as Arrow record batches. A record batch is a slice of a table, so a large dataset arrives a piece at a time. The server only reads the store. It never writes to it.

Add files to a store and start the server with these commands. It listens on grpc://127.0.0.1:8815 until you stop it:

ddigraph store add survey.xml
ddigraph serve --flight

The server gives one flight per dataset. A flight's app_metadata says which generation is HEAD, and how many nodes and relationships it holds. It has two endpoints, one for the nodes and one for the relationships, and each carries a ticket: a short JSON text that says what to read. do_get takes a ticket and streams that part.

The script below fills a store with two datasets, starts ddigraph serve --flight on a free port, and reads it with a pyarrow.flight client:

ddigraph store add tests/fixtures/lfs_lifecycle.xml --dataset-id m23-survey --store m23-store
ddigraph store add tests/fixtures/lfs_codebook.xml --dataset-id m23-codebook --store m23-store
# Start the Flight server on a free port, and stop it when the script ends
PORT=$(python -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])')
ddigraph serve --flight --store m23-store --port "$PORT" > flight.log 2>&1 &
SERVER=$!
trap 'kill "$SERVER"' EXIT
# Wait until it says it is serving, for at most 10 seconds
for _ in $(seq 50); do grep -q Serving flight.log && break; sleep 0.2; done

python - "$PORT" <<'PY'
import json
import sys

import pyarrow.flight as flight

client = flight.connect(f"grpc://127.0.0.1:{sys.argv[1]}")
for info in client.list_flights():
    print(json.loads(info.app_metadata))
    nodes = client.do_get(info.endpoints[0].ticket).read_all()
    relationships = client.do_get(info.endpoints[1].ticket).read_all()
    print("  read", nodes.num_rows, "nodes and", relationships.num_rows, "relationships")
PY

Expected output:

Generation 1 of dataset 'm23-survey': 87 nodes, 108 relationships
Generation 1 of dataset 'm23-codebook': 80 nodes, 48 relationships
{'dataset': 'm23-codebook', 'generation': 1, 'nodes': 80, 'relationships': 48}
  read 80 nodes and 48 relationships
{'dataset': 'm23-survey', 'generation': 1, 'nodes': 87, 'relationships': 108}
  read 87 nodes and 108 relationships

list_flights lists the datasets, sorted by ID. read_all gathers a stream's batches into one table, with the columns of the Arrow export.

The tickets of a flight name HEAD's number, not "the latest". So the nodes and relationships you read come from one generation, even if someone adds a new one in between. To read an older generation, write the ticket yourself. ddigraph.flight.ticket(dataset, generation, part) writes its JSON, and None stands for HEAD.

You can also run the server inside Python: ddigraph.flight.server(store, port=0) starts one on a free port at once, and shutdown() stops it. This script stores a second generation of the survey's Codebook file. In it, the variable HOURS is taken out, as when a quality check finds a problem with a variable before release. Then it reads both generations:

from pathlib import Path

import pyarrow.flight as flight

from ddigraph import ir
from ddigraph.flight import server, ticket
from ddigraph.store import Store

store = Store("m23-store")
store.write(
    "m23-codebook",
    ir.parse("tests/fixtures/lfs_codebook.xml", dataset_id="m23-codebook"),
    memory_limit=2**26,
)
# Generation 2: the same file, with the variable HOURS taken out
xml = Path("tests/fixtures/lfs_codebook.xml").read_text(encoding="utf-8")
start = xml.index('<var ID="V7"')
end = xml.index("</var>", start) + len("</var>")
Path("smaller.xml").write_text(xml[:start] + xml[end:])
store.write("m23-codebook", ir.parse("smaller.xml", dataset_id="m23-codebook"), memory_limit=2**26)

running = server(store, port=0)  # port 0: any free port
client = flight.connect(f"grpc://127.0.0.1:{running.port}")
print(ticket("m23-codebook", 1, "nodes"))
for generation in (1, None):
    nodes = client.do_get(flight.Ticket(ticket("m23-codebook", generation, "nodes"))).read_all()
    print("generation", generation, "->", nodes.num_rows, "nodes")
running.shutdown()

Expected output:

b'{"dataset":"m23-codebook","generation":1,"part":"nodes"}'
generation 1 -> 80 nodes
generation None -> 73 nodes

HEAD, generation 2, has 7 nodes fewer: the variable, its question, its concept and its universe, and three structure nodes: its place in the data file, and two for its range of 1 to 98 hours.

A ticket for a generation the store does not hold gets a FlightServerError that says why.

8. Keep Flight private

Flight checks no client. It has no password, no token and no TLS. Anyone who can reach its port can read every dataset of the store. So it listens on 127.0.0.1 by default, and refuses any address other machines can reach:

ddigraph serve --flight --host 0.0.0.0 --store m23-store 2>&1 || echo "exit code: $?"

Expected output:

--host 0.0.0.0 lets other machines read the store, and Arrow Flight checks no client: put it behind TLS and authentication, then add --allow-remote
exit code: 1

To share it, put it behind a proxy that speaks gRPC, the protocol under Flight, and adds TLS and a login. nginx and Envoy can do both. Then add --allow-remote. The Arrow Flight page has the details.


Exercises

Scenario

Your team's survey designers use a web form to send DDI files for a check before release. A data scientist on the same team wants the released graphs as tables, in her own tools. You set up both.

Exercise 1 (O1). Start the HTTP API. Send it the survey's three files, tests/fixtures/lfs_codebook.xml, tests/fixtures/lfs_lifecycle.xml and tests/fixtures/lfs_cdi.xml, and the draft of Section 3, for /validate, with all issues. For each, print the file, its flavor, whether it is valid, and how many issues the server found.

Expected output:

tests/fixtures/lfs_codebook.xml codebook True 0
tests/fixtures/lfs_lifecycle.xml lifecycle True 0
tests/fixtures/lfs_cdi.xml cdi True 0
draft.xml lifecycle False 8
Answer
# Start the server on a free port, and stop it when the script ends
PORT=$(python -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])')
ddigraph serve --port "$PORT" > server.log 2>&1 &
SERVER=$!
trap 'kill "$SERVER"' EXIT
URL="http://127.0.0.1:$PORT"
# Wait until /health answers, for at most 10 seconds
for _ in $(seq 50); do curl -sf "$URL/health" > /dev/null && break; sleep 0.2; done

# The draft of Section 3: its question texts say en_CA, where XML wants en-CA
sed 's/<d:Text xml:lang="en">/<d:Text xml:lang="en_CA">/' tests/fixtures/lfs_lifecycle.xml > draft.xml
for path in tests/fixtures/lfs_codebook.xml tests/fixtures/lfs_lifecycle.xml tests/fixtures/lfs_cdi.xml draft.xml; do
  curl -s -F "file=@$path" "$URL/validate?max_issues=0" -o result.json
  python -c 'import json, sys; r = json.load(open("result.json")); print(sys.argv[1], r["flavor"], r["valid"], len(r["issues"]))' "$path"
done
tests/fixtures/lfs_codebook.xml codebook True 0
tests/fixtures/lfs_lifecycle.xml lifecycle True 0
tests/fixtures/lfs_cdi.xml cdi True 0
draft.xml lifecycle False 8

max_issues=0 asks for every issue. Each answer has status 200, valid or not, so the script reads valid. The server picked the right schema for each flavor, as ddigraph validate would. The draft has 8 issues, one for each question text: a designer fixes them all by writing en-CA, or en.

Exercise 2 (O2, O3). Start the server with a token and DDIGRAPH_API_PUBLIC_READS=true. Print the status code of four requests: /detect with no token, /load with no token, /load with the token and dry_run=true, and /jobs/unknown with the token.

Expected output:

detect, no token: 200
load, no token: 401
load, token: 202
jobs/unknown, token: 404
Answer
export DDIGRAPH_API_TOKEN="$(python -c 'import secrets; print(secrets.token_urlsafe(32))')"
export DDIGRAPH_API_PUBLIC_READS=true
# Start the server on a free port, and stop it when the script ends
PORT=$(python -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])')
ddigraph serve --port "$PORT" > server.log 2>&1 &
SERVER=$!
trap 'kill "$SERVER"' EXIT
URL="http://127.0.0.1:$PORT"
# Wait until /health answers, for at most 10 seconds
for _ in $(seq 50); do curl -sf "$URL/health" > /dev/null && break; sleep 0.2; done
AUTH="Authorization: Bearer $DDIGRAPH_API_TOKEN"
FILE=file=@tests/fixtures/lfs_cdi.xml

echo "detect, no token: $(curl -s -o /dev/null -w '%{http_code}' -F "$FILE" "$URL/detect")"
echo "load, no token: $(curl -s -o /dev/null -w '%{http_code}' -F "$FILE" "$URL/load?dry_run=true")"
echo "load, token: $(curl -s -o /dev/null -w '%{http_code}' -H "$AUTH" -F "$FILE" "$URL/load?dataset_id=m23-cdi&dry_run=true")"
echo "jobs/unknown, token: $(curl -s -o /dev/null -w '%{http_code}' -H "$AUTH" "$URL/jobs/unknown")"
detect, no token: 200
load, no token: 401
load, token: 202
jobs/unknown, token: 404

Public reads open the read endpoints only. /load still needs the token, so the request without it gets 401, not 403: writes are on, but this client did not prove it may use them. The server answers 404 for a job it does not know.

Exercise 3 (O4). Export the survey in DDI-CDI, tests/fixtures/lfs_cdi.xml, as Arrow files. Read nodes.arrow with pyarrow, then count the nodes of each label with DuckDB SQL over the pyarrow table. Print the three labels that come first in alphabetical order.

Expected output:

('CDIAgent', 1)
('CDICategory', 21)
('CDICode', 21)
Answer
import duckdb
import pyarrow.ipc

import ddigraph

ddigraph.export("tests/fixtures/lfs_cdi.xml", "m23-cdi-arrow", format="arrow", dataset_id="m23-cdi")
nodes = pyarrow.ipc.open_file("m23-cdi-arrow/nodes.arrow").read_all()
rows = duckdb.sql(
    "SELECT node_label, count(*) FROM nodes GROUP BY node_label ORDER BY node_label LIMIT 3"
)
for row in rows.fetchall():
    print(row)
('CDIAgent', 1)
('CDICategory', 21)
('CDICode', 21)

The agent is the National Statistics Office. The 21 codes of the survey's 5 code lists each denote one of its 21 categories. ddigraph.export is the Python form of ddigraph export. DuckDB finds the table through the Python variable nodes, and reads the Arrow columns in place, with no copy and no conversion.

Exercise 4 (O4, O5). Store tests/fixtures/lfs_codebook.xml as dataset m23-codebook, serve the store from Python, and read HEAD's nodes over Flight. Export the same file as Arrow, and check that the two tables are equal.

Expected output:

80 rows over Flight, 80 rows in the file
equal: True
Answer
import pyarrow.flight as flight
import pyarrow.ipc

import ddigraph
from ddigraph import ir
from ddigraph.flight import server, ticket
from ddigraph.store import Store

path = "tests/fixtures/lfs_codebook.xml"
store = Store("m23-store")
store.write("m23-codebook", ir.parse(path, dataset_id="m23-codebook"), memory_limit=2**26)
running = server(store, port=0)
client = flight.connect(f"grpc://127.0.0.1:{running.port}")
served = client.do_get(flight.Ticket(ticket("m23-codebook", None, "nodes"))).read_all()
running.shutdown()

ddigraph.export(path, "m23-arrow", format="arrow", dataset_id="m23-codebook")
exported = pyarrow.ipc.open_file("m23-arrow/nodes.arrow").read_all()
print(served.num_rows, "rows over Flight,", exported.num_rows, "rows in the file")
print("equal:", served.equals(exported))
80 rows over Flight, 80 rows in the file
equal: True

A part read whole is the table the export writes for the same graph, row for row and type for type. So a client can switch from files to Flight, or back, without changing how it reads the tables.


Quiz

Question 1 (O1): You send an invalid DDI file to /validate. What do you get back?

A. Status 400, with the first error in detail.

B. Status 422, because the file does not match the schema.

C. Status 200, with "valid": false and the issues.

D. Status 500, because the XSD check failed.

Answer

C. The check worked; its answer is "not valid". So the server answers 200, and the result says valid: false. A is tempting, but 400 means the request itself was wrong, such as XML that does not parse at all. A script must read valid, not the status.

Question 2 (O2): No DDIGRAPH_API_TOKEN is set. A client sends POST /load with a valid file. What happens?

A. The file loads, since no token is needed.

B. The server answers 403: writes are off until a token is set.

C. The server answers 401, and asks for a token.

D. The server queues the job, and the job fails.

Answer

B. With no token, there is no way to tell who may write, so the server turns /load, /bootstrap and /jobs off. 401 (C) is the answer when a token is set and the client sent none or the wrong one. A would let anyone who reaches the server write to your database.

Question 3 (O3): A client sends a 500 MB file, and DDIGRAPH_API_MAX_UPLOAD_MB is 100. When does it get its 413?

A. After the server has saved the whole file, and measured it.

B. At once, when curl states the size in its headers, before the body is read.

C. Never: the server cuts the file to 100 MB and reads that.

D. After the job that loads it fails.

Answer

B. The server reads the Content-Length header first, and refuses a body that is too large before reading it. That keeps big files off its disk. A client that states no size is cut off once the body passes the limit. A would let a client fill the disk before being refused.

Question 4 (O3): Your server sits behind a proxy, and every client gets 429 far too soon. Why?

A. The proxy sends each request twice.

B. The server counts requests per IP address, and every request comes from the proxy's address.

C. /health checks count toward the limit.

D. The limit counts bytes, not requests.

Answer

B. ddigraph serve ignores X-Forwarded-For, since any client can write that header. Behind a proxy, all clients share the proxy's one limit. Run uvicorn yourself with --proxy-headers and the proxy's address in --forwarded-allow-ips to count them apart. C is wrong: /health never counts.

Question 5 (O4): A client asks /export?format=arrow. What happens, and why?

A. It gets the nodes table as one Arrow file.

B. It gets 400: Arrow writes a folder of two files, which one answer cannot carry. Use ddigraph export, or Flight.

C. It gets a ZIP file of the folder.

D. It gets JSON, the closest format the endpoint knows.

Answer

B. arrow, csv and neo4j-import each write a folder, and /export answers with one file. For tables over the network, Flight is the tool: it streams both parts, in Arrow. A would lose the relationships.

Question 6 (O5): Why do the tickets of a flight name HEAD's number, such as generation 1, instead of null?

A. null is not valid JSON.

B. So that the nodes and the relationships you read come from the same generation, even if a new one is added between the two reads.

C. Because Flight cannot read HEAD.

D. To make the ticket longer, and so harder to guess.

Answer

B. You read the two parts with two do_get calls. If HEAD moved in between, null would give you nodes of one generation and relationships of another. A is wrong: you can send null yourself, and it reads HEAD as it is at that moment. A ticket is no secret either: Flight checks no client, which is why it listens on 127.0.0.1 alone.


Check yourself

  • I can start the HTTP API with ddigraph serve, and send a file to /detect, /preview, /validate and /export. (O1)
  • I can turn on /load and /jobs with DDIGRAPH_API_TOKEN, queue a load, and follow its job to the end. (O2)
  • I can set the rate and upload limits, and explain the 401, 403, 413 and 429 answers. (O3)
  • I can export a graph as Arrow files with ddigraph export --format arrow, and read them with pyarrow. (O4)
  • I can serve the store with ddigraph serve --flight, and read a dataset's nodes and relationships with a pyarrow.flight client. (O5)

Back to the course overview