Wikidata API Using SPARQL Queries
Wikidata is a free, collaborative, and multilingual knowledge base that functions as the central structured data repository for the Wikimedia ecosystem, including projects like Wikipedia, Wikivoyage, and Wiktionary. Launched in 2012, its mission is to create a common source of open data that can be used by anyone, anywhere. Unlike Wikipedia, which contains prose articles, Wikidata stores information in a machine-readable format structured around items (representing any concept or object), which are described by properties (like “population” or “author”) and corresponding values. For example, the item for “Earth” has a property “instance of” with the value “planet”. This structured approach allows for data consistency across hundreds of language editions of Wikipedia and enables powerful, complex queries through its SPARQL endpoint. By providing a centralized, queryable, and interlinked database of facts, Wikidata not only supports Wikimedia projects but also serves as a crucial resource for researchers, developers, and applications worldwide that require reliable and openly licensed structured information.
Example Code
This code in file wikidata.ss provides a client for interacting with the Wikidata Query Service, a powerful public SPARQL endpoint for accessing the vast, collaboratively edited knowledge base of Wikidata. The code encapsulates the entire process of querying this service, starting with a raw SPARQL query string. It properly formats the request by URL-encoding the query, constructs the full request URL, and sets the appropriate HTTP headers, including the Accept header for the SPARQL JSON results format and a User-Agent header, which is a requirement for responsible API usage. Upon receiving a response, the module parses the JSON data and then transforms the verbose, nested structure of the standard SPARQL results format into a more convenient and idiomatic Gerbil Scheme data structure: either a list of hash tables or a list of association lists. The file also includes several example functions that demonstrate how to query for specific facts, such as Grace Hopper’s birth date, and how to perform more complex, multi-stage queries, like first finding the unique identifiers for entities like Bill Gates and Microsoft and then discovering the relationships that connect them within the knowledge graph.
1 ;; File: wikidata.ss
2 (import :std/net/request
3 :std/text/json
4 :std/net/uri
5 :std/format)
6
7 (export query-wikidata query-wikidata/alist alist-ref test1 test2 default-user-agent)
8
9 ;; Default User-Agent following WDQS etiquette policy:
10 ;; https://meta.wikimedia.org/wiki/User-Agent_policy
11 (def default-user-agent
12 (or (getenv "WDQS_UA")
13 "GerbilSchemeBookClient/1.0 (https://github.com/mark-watson/gerbil_scheme_book; contact@markwatson.com)"))
14
15 ;; Convenience: look up a key in an alist. Accepts symbol or string keys.
16 ;; Usage: (alist-ref 'var row [default])
17 (def (alist-ref key row . default)
18 (let* ((sym (if (symbol? key) key (string->symbol key)))
19 (p (assq sym row)))
20 (if p (cdr p) (if (pair? default) (car default) #f))))
21
22 ;; Process SPARQL JSON results into a list of hash tables mapping symbol variable names to values.
23 (def (process-sparql-results json-data)
24 (let* ((results (hash-ref json-data 'results))
25 (bindings (hash-ref results 'bindings)))
26 (map (lambda (binding)
27 (let ((result-hash (make-hash-table)))
28 (hash-for-each
29 (lambda (var-name value-obj)
30 (let ((sym (if (symbol? var-name) var-name (string->symbol var-name)))
31 (val (hash-ref value-obj 'value)))
32 (hash-put! result-hash sym val)))
33 binding)
34 result-hash))
35 bindings)))
36
37 ;; Process SPARQL JSON results into a list of alists: ((var . val) ...)
38 ;; Also preserves datatype and xml:lang attributes when present.
39 (def (process-sparql-results-alist json-data)
40 (let* ((results (hash-ref json-data 'results))
41 (bindings (hash-ref results 'bindings)))
42 (map (lambda (binding)
43 (let ((row '()))
44 (hash-for-each
45 (lambda (var-name value-obj)
46 (let* ((sym (if (symbol? var-name) var-name (string->symbol var-name)))
47 (val (hash-ref value-obj 'value))
48 (dtype (hash-get value-obj 'datatype))
49 (lang (hash-get value-obj 'xml:lang)))
50 (set! row (cons (cons sym val) row))
51 (when dtype
52 (set! row (cons (cons (string->symbol (string-append (symbol->string sym) "-datatype")) dtype) row)))
53 (when lang
54 (set! row (cons (cons (string->symbol (string-append (symbol->string sym) "-lang")) lang) row)))))
55 binding)
56 (reverse row)))
57 bindings)))
58
59 ;; Query the Wikidata Query Service (WDQS)
60 ;; - Uses GET with URL-encoded query and JSON format
61 ;; - Sends a User-Agent per WDQS guidelines; callers can override via user-agent:
62 ;; - Handles HTTP 429 rate-limiting responses using Retry-After
63 (def (query-wikidata sparql-query
64 user-agent: (user-agent default-user-agent)
65 as: (as 'hash))
66 (let* ((endpoint "https://query.wikidata.org/sparql")
67 (encoded-query (uri-encode sparql-query))
68 (request-url (string-append endpoint "?query=" encoded-query "&format=json"))
69 (headers `(("Accept" . "application/sparql-results+json")
70 ("User-Agent" . ,user-agent))))
71 (let loop ((retries 1))
72 (let ((response (http-get request-url headers: headers)))
73 (cond
74 ((= (request-status response) 200)
75 (let ((response-json (request-json response)))
76 (if (eq? as 'alist)
77 (process-sparql-results-alist response-json)
78 (process-sparql-results response-json))))
79 ((and (= (request-status response) 429) (> retries 0))
80 (let* ((headers-alist (request-headers response))
81 (retry-after (or (assoc "retry-after" headers-alist)
82 (assoc "Retry-After" headers-alist)))
83 (wait-secs (if retry-after (string->number (cdr retry-after)) 5)))
84 (thread-sleep! (or wait-secs 5))
85 (loop (- retries 1))))
86 (else
87 (error "SPARQL query failed"
88 status: (request-status response)
89 body: (request-text response))))))))
90
91 ;; Alist variant returning rows as association lists
92 (def (query-wikidata/alist sparql-query (user-agent default-user-agent))
93 (query-wikidata sparql-query user-agent: user-agent as: 'alist))
94
95 ;; Test2: fetch birth date and birthplace label for Grace Hopper (wd:Q11641)
96 (def (test2 (user-agent default-user-agent))
97 (let ((query
98 (string-append
99 "PREFIX wd: <http://www.wikidata.org/entity/>\n"
100 "PREFIX wdt: <http://www.wikidata.org/prop/direct/>\n"
101 "PREFIX wikibase: <http://wikiba.se/ontology#>\n"
102 "PREFIX bd: <http://www.bigdata.com/rdf#>\n"
103 "SELECT ?birthDate ?birthPlaceLabel WHERE {\n"
104 " wd:Q11641 wdt:P569 ?birthDate .\n"
105 " wd:Q11641 wdt:P19 ?birthPlace .\n"
106 " SERVICE wikibase:label { bd:serviceParam wikibase:language \"en\". }\n"
107 "}")))
108 (let ((results (query-wikidata/alist query user-agent)))
109 (for-each
110 (lambda (result)
111 (display (format "Birth Date: ~a\n" (alist-ref 'birthDate result)))
112 (display (format "Birth Place: ~a\n\n" (alist-ref 'birthPlaceLabel result))))
113 results))))
114
115 ;; Test1: find URIs for Bill Gates and Microsoft; then list relationships
116 (def (test1 (user-agent default-user-agent))
117 (let* ((find-uris
118 (string-append
119 "PREFIX wd: <http://www.wikidata.org/entity/>\n"
120 "PREFIX wdt: <http://www.wikidata.org/prop/direct/>\n"
121 "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
122 "SELECT ?bill ?microsoft WHERE {\n"
123 " ?bill rdfs:label \"Bill Gates\"@en .\n"
124 " ?bill wdt:P31 wd:Q5 .\n"
125 " ?microsoft rdfs:label \"Microsoft\"@en .\n"
126 " ?microsoft wdt:P31/wdt:P279* wd:Q4830453 .\n"
127 "} LIMIT 1"))
128 (rows (query-wikidata/alist find-uris user-agent)))
129 (if (null? rows)
130 (display "No URIs found for Bill Gates/Microsoft.\n")
131 (let* ((row (car rows))
132 (bill (alist-ref 'bill row))
133 (microsoft (alist-ref 'microsoft row))
134 (rel-query
135 (string-append
136 "PREFIX wikibase: <http://wikiba.se/ontology#>\n"
137 "PREFIX bd: <http://www.bigdata.com/rdf#>\n"
138 "SELECT ?prop ?propLabel ?dir WHERE {\n"
139 " VALUES (?bill ?microsoft) { (<" bill "> <" microsoft ">) }\n"
140 " ?wdprop wikibase:directClaim ?prop .\n"
141 " { BIND(\"Bill->Microsoft\" AS ?dir) ?bill ?prop ?microsoft . }\n"
142 " UNION\n"
143 " { BIND(\"Microsoft->Bill\" AS ?dir) ?microsoft ?prop ?bill . }\n"
144 " SERVICE wikibase:label { bd:serviceParam wikibase:language \"en\". }\n"
145 "}\n"
146 "ORDER BY ?propLabel"))
147 (rels (query-wikidata/alist rel-query user-agent)))
148 (display (format "Bill Gates URI: ~a\n" bill))
149 (display (format "Microsoft URI: ~a\n" microsoft))
150 (if (null? rels)
151 (display "No direct relationships found.\n")
152 (for-each
153 (lambda (r)
154 (display (format "~a: ~a\n"
155 (alist-ref 'dir r)
156 (or (alist-ref 'propLabel r)
157 (alist-ref 'prop r)))))
158 rels))))))
The core of this example is built around the query-wikidata procedure (and its convenience wrapper query-wikidata/alist). This procedure handles the HTTP communication with the Wikidata SPARQL endpoint. It takes a SPARQL query string, URI-encodes it, and embeds it into a GET request URL. It sets a User-Agent string, a requirement under Wikidata Query Service guidelines that helps service operators identify traffic; the default can be set via the WDQS_UA environment variable or passed explicitly via the user-agent: keyword argument. It also automatically handles HTTP 429 rate-limiting responses by waiting and retrying if a Retry-After header is provided. After a successful request, the raw JSON response is parsed into either a list of hash tables or a list of association lists mapping variable names (as symbols) to values, preserving datatype and language tags.
The included test functions, test1 and test2, serve as practical examples of this code’s capabilities. The test2 function is a straightforward lookup, retrieving the birth date and birthplace for a specific Wikidata entity (Grace Hopper, wd:Q11641). In contrast, test1 demonstrates a more powerful, dynamic pattern. It first runs a query to find the URIs for “Bill Gates” and “Microsoft” based on their English labels and types (human and business, respectively). It then uses these dynamically discovered URIs to construct a second query that finds all direct properties linking the two entities. Note that matching on rdfs:label scans the full label index; in high-throughput applications, the wikibase:mwapi EntitySearch service is faster.
The following architecture diagram provides an overview of the Wikidata client’s structure, showing how SPARQL queries are URL-encoded, sent as HTTP GET requests to the Wikidata Query Service endpoint, and how the JSON results are parsed and transformed into idiomatic Gerbil Scheme data structures.

Example Output
We use a Makefile target to start a Gerbil Scheme REPL with the example code loaded:
Here is the Makefile:
1 run:
2 gxi -L wikidata.ss -
3
4 test:
5 gxi -L wikidata.ss -e "(test2)"
6
7 test1:
8 gxi -L wikidata.ss -e "(test1)"
9
10 run-agent:
11 WDQS_UA="$${WDQS_UA:-YourApp/1.0 (https://your.site; you@site)}" gxi -L wikidata.ss -e "(test2)"
12
13 run-agent1:
14 WDQS_UA="$${WDQS_UA:-YourApp/1.0 (https://your.site; you@site)}" gxi -L wikidata.ss -e "(test1)"
15
16 clean:
17 rm -rf .gerbil *~
And sample output:
1 $ make run-agent1
2 WDQS_UA="${WDQS_UA:-YourApp/1.0 (https://your.site; you@site)}" gxi -L wikidata.ss -e "(test1-ua)"
3 Bill Gates URI: http://www.wikidata.org/entity/Q5284
4 Microsoft URI: http://www.wikidata.org/entity/Q2283
5 Microsoft->Bill: http://www.wikidata.org/prop/direct/P112
6 Bill->Microsoft: http://www.wikidata.org/prop/direct/P1830
7 $ make
8 gxi -L wikidata.ss -
9 > (test1)
10 Bill Gates URI: http://www.wikidata.org/entity/Q5284
11 Microsoft URI: http://www.wikidata.org/entity/Q2283
12 Microsoft->Bill: http://www.wikidata.org/prop/direct/P112
13 Bill->Microsoft: http://www.wikidata.org/prop/direct/P1830
14 > (test2)
15 Birth Date: 1862-02-14T00:00:00Z
16 Birth Place: Venice
Optional Practice Problems
- Large City Query: Write a SPARQL query using
query-wikidata/alistto find all cities with a population greater than 1 million, and print their names and populations in descending order. - In-Memory Cache: Implement an in-memory query cache that maps SPARQL query strings to their parsed JSON results, avoiding redundant API calls for duplicate requests.
- URI Parser Helper: Implement a helper function
extract-entity-idthat extracts the alphanumeric entity identifier (such as"Q11641") from a full Wikidata entity URI (like"http://www.wikidata.org/entity/Q11641").