How to fetch Wikidata using JavaScript and SPARQL query

作者: Calpa Liu
字數:1230
出版日期:September 7, 2022
更新日期:September 7, 2022

We can use `wikidata-sdk` to get the data from the Wikidata.

We can use wikidata-sdk to get the data from the Wikidata.

  1. Import the wikidata-sdk package as variable wdk.
const wdk = require('wikidata-sdk')
  1. Write your SPARQL query
const sparql = `
SELECT ?item ?itemLabel
WHERE {
  ?item wdt:P31 wd:Q6256;
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
}
`
  1. Get the url and parsed body
const [baseUrl, body] = wdk.sparqlQuery(sparql).split('?')
  1. Use axios to POST and get the response
const axios = require('axios')

const { data } = await axios.post(url, body)

console.log(data)

So let’s combine the code together.

const axios = require('axios')
const wdk = require('wikidata-sdk')
const sparql = `
SELECT ?item ?itemLabel
WHERE {
  ?item wdt:P31 wd:Q6256;
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
}
`

const [url, body] = wdk.sparqlQuery(sparql).split('?')

const { data } = await axios.post(url, body)

console.log(data)

We can run the above code in runkit and inspect the response:

Or you may click the following link to play with the source code.

https://runkit.com/calpa/example-of-fetching-all-countries-from-wikidata

感謝您閱讀我的文章。歡迎隨時分享你的想法。
關於 Calpa

Calpa 擅長使用 TypeScript、React.js 和 Vue.js 開發Responsive Web Design網站。

此外,Calpa 積極參與香港和台灣的開源社區,曾在2019年的香港開源大會上擔任講者,提供工作經驗和見解。此外,他也在 GitHub 上公開分享個人博客程式碼,已獲得超過300顆星星和60個分支的支持。

更多前端開發技術文章:傳送門