We can use `wikidata-sdk` to get the data from the Wikidata.
We can use wikidata-sdk
to get the data from the Wikidata.
- Import the
wikidata-sdk
package as variablewdk
.
const wdk = require('wikidata-sdk')
- Write your SPARQL query
const sparql = `
SELECT ?item ?itemLabel
WHERE {
?item wdt:P31 wd:Q6256;
SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
}
`
- Get the url and parsed body
const [baseUrl, body] = wdk.sparqlQuery(sparql).split('?')
- 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
感謝您閱讀我的文章。歡迎隨時分享你的想法。