# SPARQL Query Runner (`datamule/sparql-query-runner`) Actor

Point at ANY public SPARQL endpoint (Wikidata, DBpedia, UniProt, government & museum Linked-Open-Data) and run a query over the W3C SPARQL 1.1 Protocol. SELECT flattens to dynamic columns per binding, ASK to a boolean, CONSTRUCT/DESCRIBE to triples. One actor, any knowledge graph. Pay per binding.

- **URL**: https://apify.com/datamule/sparql-query-runner.md
- **Developed by:** [Datamule](https://apify.com/datamule) (community)
- **Categories:** Developer tools, Business
- **Stats:** 2 total users, 0 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.35 / 1,000 bindings

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## SPARQL Query Runner

**Point at ANY public SPARQL endpoint, send a query, get a dataset.** One actor speaks to
every knowledge graph in the Linked-Open-Data world over the W3C **SPARQL 1.1 Protocol** —
no per-site scraper, no host enumeration.

SPARQL is *the* query language of the semantic web. Wikidata, DBpedia, UniProt / EBI (life
sciences), Bio2RDF, the EU / EEA and national-library / museum Linked-Open-Data endpoints,
and thousands of government open-data triplestores all serve the identical protocol. Give
this actor an endpoint URL and a SPARQL query and it turns the result straight into rows.

### What it does

Sends your query to the endpoint with `Accept: application/sparql-results+json` and
flattens the response. The output shape follows the **query form**:

| Query form | Output |
|---|---|
| **SELECT** | One row per result binding. Each SELECT variable becomes a **top-level column** equal to its `.value` — the columns are literally your query's variables. A variable left **unbound** in a binding (e.g. an `OPTIONAL` that didn't match) is `null`. The full typed binding (`uri` / `literal` / `bnode`, `datatype`, `xml:lang`) is preserved losslessly in `_raw`. |
| **ASK** | A single row: `{ "_queryType": "ask", "boolean": true/false }`. |
| **CONSTRUCT** / **DESCRIBE** | Best-effort: the query is sent with `Accept: application/n-triples` and one row is emitted per triple (`subject` / `predicate` / `object`). If the endpoint won't return N-Triples, the source is skipped with a warning (never fabricated). |

Every row carries `_endpoint`, `_queryType`, `_rowIndex` and `_raw`.

### Input

| Field | Description |
|---|---|
| `endpoint` | A SPARQL endpoint URL, e.g. `https://query.wikidata.org/sparql`. Required unless `endpoints` is given. |
| `endpoints` | Optional: run the **same** query across several endpoints (mirrors / cross-KG). Each row is tagged with its `_endpoint`. |
| `query` | Required for custom requests. The ready-to-run example uses `ASK { ?s ?p ?o }`; SELECT / ASK are primary and CONSTRUCT / DESCRIBE best-effort. |
| `method` | `GET` (default) or `POST` (for queries too long for a URL). |
| `maxRecords` | Optional global cap on rows across all endpoints (one billable event per row). |
| `userAgent` | Optional override. A descriptive User-Agent is sent by default — **required in practice for Wikidata**, which blocks blank / generic UAs. |
| `defaultGraphUri` / `namedGraphUri` | Optional SPARQL-protocol dataset graph parameters. |
| `timeoutSecs` | Optional read timeout (default 90s; endpoints enforce their own server-side caps). |
| `bearer` / `extraHeaders` | Optional, for auth-gated deployments. Never required, never logged. |

### Examples

**All-purpose portable query** (works on almost any endpoint):

```json
{ "endpoint": "https://dbpedia.org/sparql", "endpoints": ["https://sparql.uniprot.org/sparql"], "query": "ASK { ?s ?p ?o }", "maxRecords": 2 }
```

**Wikidata — countries and their population** (dynamic columns `country`, `countryLabel`, `population`):

```json
{
  "endpoint": "https://query.wikidata.org/sparql",
  "query": "SELECT ?country ?countryLabel ?population WHERE { ?country wdt:P31 wd:Q3624078 . OPTIONAL { ?country wdt:P1082 ?population } SERVICE wikibase:label { bd:serviceParam wikibase:language \"en\" } } LIMIT 50"
}
```

### Resilience

An endpoint that returns a 4xx/5xx, times out, or answers with a non-SPARQL body (an HTML
error / anti-bot page, a SPARQL syntax-error response) is **skipped with a warning** and the
batch continues. A run where **every** endpoint is skipped **fails** so nothing broken ships.
A reachable endpoint that returns **0 bindings** yields 0 rows and a clean success.

### Pricing

Pay-per-event: one **binding** charge per emitted row.

# Actor input Schema

## `endpoint` (type: `string`):

The URL of ANY public SPARQL endpoint (W3C SPARQL 1.1 Protocol). One actor speaks to all of them — Wikidata (https://query.wikidata.org/sparql), DBpedia (https://dbpedia.org/sparql), UniProt (https://sparql.uniprot.org/sparql), Bio2RDF, EU / national-library / museum Linked-Open-Data, government open-data endpoints, and any self-hosted triplestore. Required unless you use "Endpoints" below to run across several. For an auth-gated deployment, add a Bearer token or headers below.

## `endpoints` (type: `array`):

Optional: run the SAME query across multiple SPARQL endpoints (mirrors, or several knowledge graphs at once). Each output row is tagged with its \_endpoint. Use this OR the single "Endpoint" above (at least one is required). An endpoint that is unreachable, auth-gated, or returns a non-SPARQL body is skipped with a warning and the batch continues.

## `query` (type: `string`):

The SPARQL query to run. SELECT and ASK are the primary forms; CONSTRUCT and DESCRIBE are best-effort (emitted as one row per triple via N-Triples). A portable query that works on almost any endpoint: SELECT ?s ?p ?o WHERE { ?s ?p ?o } LIMIT 5. The output COLUMNS of a SELECT are exactly your query's variables, so shape the result by shaping the query.

## `method` (type: `string`):

How to send the query. GET (default) puts the query in the URL — fine for most queries. POST sends it as an application/x-www-form-urlencoded body — use it for queries too long for a URL.

## `maxRecords` (type: `integer`):

A GLOBAL cap on the number of rows emitted across ALL endpoints (each row is one result binding / triple and one billable event). Reached mid-endpoint, the run stops deterministically. Leave empty to emit every binding the query returns — most endpoints also enforce their own server-side LIMIT, and you can add LIMIT to the query itself.

## `userAgent` (type: `string`):

Optional override for the request User-Agent. A descriptive User-Agent is sent by default — REQUIRED in practice for Wikidata, which blocks blank / generic UAs with 403 / 429. Only override if a specific endpoint asks you to identify differently.

## `defaultGraphUri` (type: `string`):

Optional SPARQL-protocol default-graph-uri parameter — sets the default RDF dataset the query runs against on endpoints that expose named graphs. Leave empty for the endpoint's own default.

## `namedGraphUri` (type: `array`):

Optional SPARQL-protocol named-graph-uri parameter(s) — one or more named graphs to add to the dataset the query runs against. Leave empty unless the endpoint documents named graphs.

## `timeoutSecs` (type: `integer`):

How long to wait for the endpoint to answer (default 90). Endpoints also enforce their own server-side query timeouts (Wikidata ~60s), so a very large query may still be cut off by the server.

## `bearer` (type: `string`):

Optional bearer token for an auth-gated SPARQL endpoint (sent as Authorization: Bearer \*\*\*). NOT required for public endpoints. Never logged.

## `extraHeaders` (type: `object`):

Optional extra HTTP headers as a JSON object, e.g. {"X-Api-Key": "..."} for a gateway-fronted endpoint. Not required for public endpoints. Header values are never logged.

## Actor input object example

```json
{
  "endpoint": "https://dbpedia.org/sparql",
  "endpoints": [
    "https://dbpedia.org/sparql",
    "https://sparql.uniprot.org/sparql"
  ],
  "query": "ASK { ?s ?p ?o }",
  "method": "GET",
  "maxRecords": 2
}
```

# Actor output Schema

## `results` (type: `string`):

No description

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "endpoint": "https://dbpedia.org/sparql",
    "endpoints": [
        "https://dbpedia.org/sparql",
        "https://sparql.uniprot.org/sparql"
    ],
    "query": "ASK { ?s ?p ?o }",
    "maxRecords": 2
};

// Run the Actor and wait for it to finish
const run = await client.actor("datamule/sparql-query-runner").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "endpoint": "https://dbpedia.org/sparql",
    "endpoints": [
        "https://dbpedia.org/sparql",
        "https://sparql.uniprot.org/sparql",
    ],
    "query": "ASK { ?s ?p ?o }",
    "maxRecords": 2,
}

# Run the Actor and wait for it to finish
run = client.actor("datamule/sparql-query-runner").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "endpoint": "https://dbpedia.org/sparql",
  "endpoints": [
    "https://dbpedia.org/sparql",
    "https://sparql.uniprot.org/sparql"
  ],
  "query": "ASK { ?s ?p ?o }",
  "maxRecords": 2
}' |
apify call datamule/sparql-query-runner --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,datamule/sparql-query-runner"
        }
    }
}

```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/zkYv0nA7nb4G7CZNH/builds/BqaDPxdPDQXXcfcY8/openapi.json
