Skip to content

HTTP API

ddigraph serve runs a small web service over the same functions as the CLI. Send it a DDI XML file, and it tells you the format, previews the graph, checks the file against its XSD, exports it, or loads it into Neo4j. Use it when another program, or a person without Python, needs ddigraph.

Install and start

The API is an optional extra. It adds FastAPI, uvicorn and python-multipart:

pip install "ddigraph[api]"

Then start the server:

ddigraph serve

It listens on 127.0.0.1:8000, so only programs on the same machine can reach it. --host and --port change that:

ddigraph serve --host 0.0.0.0 --port 9000

serve has no --neo4j-* flags. It reads the connection settings from the environment or a .env file, as the Configuration page describes. Without the extra, it stops with The HTTP API needs the api extra: pip install 'ddigraph[api]'.

While the server runs, http://127.0.0.1:8000/docs lists every endpoint and lets you try each one in a browser. /redoc shows the same list in another layout, and /openapi.json holds it as JSON. These pages, and /docs/oauth2-redirect that /docs uses, follow the rules of the read endpoints. Once a token is set, they need it too, as the next section explains. A browser cannot send the token to them, so to browse them then, also set DDIGRAPH_API_PUBLIC_READS=true.

The server speaks plain HTTP, so a token sent to it can be read on the way. Before you open it to a network, put it behind a proxy that adds TLS.

The token

/load and /bootstrap write to Neo4j, so they need a token. Set DDIGRAPH_API_TOKEN before you start the server:

export DDIGRAPH_API_TOKEN="$(python -c 'import secrets; print(secrets.token_urlsafe(32))')"
ddigraph serve

A request sends the token in an Authorization: Bearer header. A missing or wrong token gets 401.

Once a token is set, every endpoint but /health needs it. The read endpoints are /detect, /preview, /validate and /export, and the /docs, /redoc and /openapi.json pages count as read endpoints too. To let them answer without the token, also set DDIGRAPH_API_PUBLIC_READS=true. They never open the database.

The server checks the token before it reads the uploaded file. So a refused request gets its 401 or 403 at once, and its file never reaches the disk.

Setup /health Read endpoints /load, /bootstrap, /jobs
No token set open open off (403)
Token set open token token
Token set, DDIGRAPH_API_PUBLIC_READS=true open open token

A blank DDIGRAPH_API_TOKEN counts as no token.

Rate limit

Each client can send DDIGRAPH_API_RATE_LIMIT requests a minute (default 60). The server tells clients apart by their IP address. A client that has been quiet can send them all at once. After that, it gets one more request each 60 / DDIGRAPH_API_RATE_LIMIT seconds.

A request over the limit gets 429. Its Retry-After header says how many seconds to wait. /health does not count. Set DDIGRAPH_API_RATE_LIMIT=0 to turn the limit off.

The server counts a request before it reads the uploaded file, so a client over the limit cannot fill the disk either. The counts live in memory, so they start again when the server restarts.

ddigraph serve ignores the X-Forwarded-For header, because any client can write it. Behind a proxy, every request comes from the proxy's address, so all clients share one limit. To count each client on its own, run uvicorn yourself and tell it which proxy to trust:

uvicorn --factory ddigraph.server:create_app \
  --proxy-headers --forwarded-allow-ips 10.0.0.5

Put the proxy's own address in place of 10.0.0.5. The app reads its settings from the environment, as ddigraph serve does.

Jobs

A load can take minutes, so /load and /bootstrap do not wait for it. Each one answers 202 at once, with a job id:

{"job_id": "8caeca126f2a434183c618a99cd65639", "status": "queued"}

The Location header holds the job's address. Ask GET /jobs/{job_id} how the job is going, with the same token. One worker runs the jobs in the order they arrive, in a thread of their own, so the other endpoints keep answering during a load.

A job's status is queued, running, succeeded or failed. Poll until it is succeeded or failed. Each poll counts toward the rate limit, so wait a few seconds between polls.

At most 10 jobs wait or run at once, since each waiting load keeps its file on disk. Past that, /load and /bootstrap answer 503 with a Retry-After header. The server keeps the last 100 finished jobs. It forgets them all when it restarts. If the server stops during a job, that job fails, and so does every job still in the queue.

Uploads

Every endpoint but /health, /bootstrap and /jobs takes one file, sent as the form field file. Options go in the query string, as in /export?format=jsonld, not in the form.

A file larger than DDIGRAPH_API_MAX_UPLOAD_MB megabytes (default 100) gets 413. When the request states its size, as curl does, and that size is more than 64 KB over the limit, the 413 comes before the server reads the file. The 64 KB leaves room for the form around the file. Otherwise, the server stops reading once the file passes the limit. The server saves each upload in a temporary folder. It deletes the folder when the request ends, or for /load when the job ends.

A node records the path of the file it was read from, as its source provenance. For an upload, that is the path of the server's temporary copy, such as /tmp/ddigraph-api-1q3r9x2d/upload.xml, not your file's name. /load writes it on each IN_DATASET edge and on the Dataset node, and /export in each node's provenance. It changes with every upload, so it does not say where the file came from.

Without a dataset_id, the dataset is named after the uploaded file, as ddigraph load and ddigraph.load() name it: the file name without its extension, with spaces turned into underscores. Labour Force.xml becomes Labour_Force. This goes for every flavor. An RDF file loads into the dataset it holds. The server fetches nothing for it: a JSON-LD upload that names a context by URL or file name, or an RDF/XML upload with a DOCTYPE, is refused.

Endpoints

Endpoint Token What it does
GET /health no Reports the version and whether Neo4j answers
POST /detect when set Names the DDI format of the file
POST /preview when set Summarises the graph the file makes
POST /validate when set Checks the file against its official XSD
POST /export when set Returns the graph as RDF or JSON
POST /load yes Starts a job that loads the file into Neo4j
POST /bootstrap yes Starts a job that creates the Neo4j key constraint and indexes
GET /jobs/{job_id} yes Reports how a job is going

"When set" means the endpoint needs the token once DDIGRAPH_API_TOKEN is set, unless DDIGRAPH_API_PUBLIC_READS is true.

The examples below use the survey.xml file from the other pages. When a token is set, add -H "Authorization: Bearer $DDIGRAPH_API_TOKEN" to the read examples too.

GET /health

curl http://127.0.0.1:8000/health
{"status": "ok", "version": "0.6.0", "neo4j": "ok"}

It always answers 200. neo4j is "unreachable" when Neo4j does not answer within 3 seconds, refuses the connection, or rejects the credentials.

POST /detect

curl -F file=@survey.xml http://127.0.0.1:8000/detect
{"format": "lifecycle"}

format is codebook, lifecycle or cdi. As with ddigraph detect, an XML root it does not know gets 400, with a detail that names the root.

POST /preview

Parameter Default Meaning
format text text, mermaid or html
limit 0 Example nodes to show per type
flavor detected codebook, lifecycle or cdi
dataset_id file name The dataset the graph is read into, for every flavor
curl -F file=@survey.xml 'http://127.0.0.1:8000/preview?format=text'
Preview: /tmp/ddigraph-api-umjyys_m/upload.xml
Nodes: 7   Relationships: 6

Node types
  Category           1
  CodeList           1
  Dataset            1
  Instrument         1
  QuestionConstruct  1
  QuestionItem       1
  Sequence           1

Relationships
  (CodeList)-[:HAS_CATEGORY]->(Category)  1
  (Dataset)-[:HAS_ENTRY_POINT]->(Instrument)  1
...

The first line names the server's temporary copy, not your file. Text and Mermaid come back as text/plain, HTML as text/html.

POST /validate

Parameter Default Meaning
flavor detected codebook, lifecycle or cdi
max_issues 20 Most issues to report; 0 reports all
curl -F file=@survey.xml 'http://127.0.0.1:8000/validate?max_issues=1'
{
  "valid": false,
  "flavor": "lifecycle",
  "version": "3_3",
  "schema": "instance_3_3.xsd",
  "issues": [
    {
      "line": 8,
      "column": 0,
      "message": "Element '{ddi:datacollection:3_3}Instrument', attribute 'id': The attribute 'id' is not allowed."
    }
  ]
}

An invalid file still gets 200, so read valid. This is the XSD check only. For SHACL, use ddigraph validate.

POST /export

Parameter Default Meaning
format turtle turtle, ntriples, jsonld, rdfxml or json
flavor detected codebook, lifecycle or cdi
dataset_id file name The dataset the graph is read into, for every flavor
curl -F file=@survey.xml 'http://127.0.0.1:8000/export?format=turtle' -o survey.ttl

The body is the exported file:

@prefix dcat: <http://www.w3.org/ns/dcat#> .
@prefix dcterms: <http://purl.org/dc/terms/> .
@prefix ddigraph: <https://pbisson44.github.io/ddigraph/ns/1.0/> .
...
<urn:ddi:test.org:inst1:1.0> a disco:Instrument,
        ddigraph:Instrument ;
    rdfs:label "Test Instrument" ;
    dcterms:identifier "urn:ddi:test.org:inst1:1.0" ;
    dcterms:isPartOf <urn:ddigraph:scoped:survey:%3Adataset> ;
    dcterms:publisher "test.org" ;
    owl:versionInfo "1.0" ;
    ddigraph:ddiId "inst1" ;
    ddigraph:hasConstruct <urn:ddi:test.org:seq1:1.0> ;
    ddigraph:key "b9b08bc64ac37197ea2b4ca9db3b6b96" ;
    ddigraph:name "TestInstrument" .

Each subject is the node's identity. The export also holds the Dataset node, a ddigraph:Membership for each node, and an rdf:Statement for each relationship, with its ordinal and resolution. See the RDF backend.

The media types are text/turtle, application/n-triples, application/ld+json, application/rdf+xml and application/json. The RDF formats need the rdf extra on the server. format=csv, format=arrow and format=neo4j-import get 400, because each writes a folder of files: use ddigraph export for them.

POST /load

Parameter Default Meaning
dataset_id file name The dataset this file is loaded as
replace false Purge the dataset_id dataset first
dry_run false Parse and count, but write nothing
resolve exact How a versioned reference finds its end: exact, latest-declared or fail
curl -H "Authorization: Bearer $DDIGRAPH_API_TOKEN" \
  -F file=@survey.xml 'http://127.0.0.1:8000/load?replace=true'
{"job_id": "8caeca126f2a434183c618a99cd65639", "status": "queued"}

When the job succeeds, its result holds what the load did, as GET /jobs/{job_id} shows.

replace=true follows the same rules as --replace, for every format: it purges only the dataset_id dataset, as Replacing a file explains. The server does not read DDIGRAPH_REPLACE, so pass replace=true. If the server runs with DDIGRAPH_DRY_RUN=true, every load is a dry run. With DDIGRAPH_STRICT_PARSING=true, a file with key conflicts fails before anything is written. resolve=fail works the same way for a file with a reference it cannot resolve. See Node identity.

POST /bootstrap

Parameter Default Meaning
drop_legacy false First drop every constraint and index not named ddigraph_* (the 0.5 schema, and your own)
dry_run false Run nothing, and return the statements that would run
curl -X POST -H "Authorization: Bearer $DDIGRAPH_API_TOKEN" \
  'http://127.0.0.1:8000/bootstrap?drop_legacy=true&dry_run=true'
{"job_id": "745000fd3b06484fbcdf49ac89f616d7", "status": "queued"}

When the job succeeds, its result is {drop_legacy, dry_run, statements}, with the statements in the order they ran, or would run:

{
  "drop_legacy": true,
  "dry_run": true,
  "statements": [
    "CREATE CONSTRAINT ddigraph_DDINode_key IF NOT EXISTS\nFOR (n:DDINode) REQUIRE n.key IS UNIQUE",
    "CREATE RANGE INDEX ddigraph_DDINode_urn IF NOT EXISTS\nFOR (n:DDINode) ON (n.urn)",
    "..."
  ]
}

Like ddigraph bootstrap, it applies DDIGRAPH_TRANSACTION_TIMEOUT to each schema statement. See Upgrading to 0.6 before you use drop_legacy=true.

GET /jobs/{job_id}

curl -H "Authorization: Bearer $DDIGRAPH_API_TOKEN" \
  http://127.0.0.1:8000/jobs/8caeca126f2a434183c618a99cd65639
{
  "job_id": "8caeca126f2a434183c618a99cd65639",
  "kind": "load",
  "status": "succeeded",
  "created_at": "2026-11-04T01:34:38.350223+00:00",
  "started_at": "2026-11-04T01:34:38.350647+00:00",
  "finished_at": "2026-11-04T01:34:38.611943+00:00",
  "result": {
    "flavor": "lifecycle",
    "target": "bolt://localhost:7687",
    "dataset_id": "survey",
    "nodes_written": 7,
    "relationships_written": 6,
    "stubs": 0,
    "references": 5,
    "resolved": 5,
    "unresolved": {},
    "conflicts": [],
    "duration_s": 0.26024599199990917,
    "dry_run": false
  },
  "error": null
}

The result has the fields of LoadResult, as ddigraph load --json prints them.

kind is load or bootstrap. The times are in UTC. started_at and finished_at are null until the job starts and ends.

A failed job has "result": null and an error. For bad input, such as XML that does not parse or a reference that resolve=fail cannot resolve, error is the same message a 400 would carry:

{
  "job_id": "ca1297b0be494121867823a524294e72",
  "kind": "load",
  "status": "failed",
  "created_at": "2026-11-04T01:34:38.973729+00:00",
  "started_at": "2026-11-04T01:34:38.974073+00:00",
  "finished_at": "2026-11-04T01:34:38.978911+00:00",
  "result": null,
  "error": "/tmp/ddigraph-api-evtavqge/upload.xml:140: <Code_denotes_Category> refers to urn:ddi:example.org:cat-unemployed:2.0, which is not in the file (version_not_in_file)"
}

For anything else, such as Neo4j going down during a load, error only says the server log has the details. That way the answer shows no internal detail. An unknown job id, or one the server has forgotten, gets 404.

Status codes

An error comes back as JSON with a detail field.

Code When
200 It worked. /validate also answers 200 for an invalid file
202 /load or /bootstrap queued a job
400 Bad input: XML that does not parse, an unknown format, a format that writes a folder (csv, arrow, neo4j-import), or an extra missing on the server
401 The token is needed, and the request sent none or the wrong one
403 /load, /bootstrap or /jobs while DDIGRAPH_API_TOKEN is not set
404 /jobs/{job_id} for a job the server does not know
413 The file is larger than DDIGRAPH_API_MAX_UPLOAD_MB
422 The file field is missing, or a parameter has the wrong type
429 The client went over DDIGRAPH_API_RATE_LIMIT; see Retry-After
500 Anything else
503 /load or /bootstrap while 10 jobs wait or run; see Retry-After

A job that fails still answers 200 on /jobs/{job_id}. Read its status.

Settings

serve reads these settings from the environment or a .env file. The Configuration page lists them with their types.

Variable Default Meaning
DDIGRAPH_API_TOKEN none The bearer token. Unset turns /load, /bootstrap and /jobs off
DDIGRAPH_API_PUBLIC_READS false Let the read endpoints answer without the token
DDIGRAPH_API_RATE_LIMIT 60 Requests a minute per client; 0 turns the limit off
DDIGRAPH_API_MAX_UPLOAD_MB 100 Largest upload, in megabytes
DDIGRAPH_XML_HUGE_TREE false Raise the XML parser's limits for /load, /detect, /validate, /preview and /export

Leave DDIGRAPH_XML_HUGE_TREE off on a server that takes files from other people. Very large XML files explains why.

From Python

ddigraph.server.create_app(settings) returns the FastAPI app, for your own uvicorn or for tests. It reads Settings() when you give no settings. The job worker starts and stops with the app's lifespan. uvicorn runs the lifespan for you. With fastapi.testclient, use the client in a with block, or /load and /bootstrap cannot start jobs.

The test client needs the httpx2 package, which the api extra does not install. Without it, importing fastapi.testclient fails with RuntimeError: The starlette.testclient module requires the httpx2 package to be installed. (Starlette still takes the older httpx, with a warning.) Install both:

pip install "ddigraph[api]" httpx2