User:GautamSudhanshu/Module/PredefinedWikidataList

local p = {}

-- Define predefined queries with property and value pairs local predefinedQueries = { ["Humans"] = {property = "P31", value = "Q5"}, ["Countries"] = {property = "P31", value = "Q6256"}, ["Cities"] = {property = "P31", value = "Q515"}, }

-- Function to fetch items from Wikidata based on the predefined query type function p.fetchItemsFromWikidata(frame) local args = frame:getParent.args local queryType = args["query"] local limit = tonumber(args["limit"]) or 10

if not queryType or not predefinedQueries[queryType] then return "Invalid or no query type specified." end

local property = predefinedQueries[queryType].property local value = predefinedQueries[queryType].value

local sparqlQuery = 'SELECT ?item ?itemLabel WHERE {' .. '?item wdt:' .. property .. ' wd:' .. value .. ' .' ..                       'SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }' ..                       '} LIMIT ' .. limit

local url = 'https://query.wikidata.org/sparql?format=json&query=' .. mw.uri.encode(sparqlQuery) local raw_json = mw.text.jsonDecode(mw.http.fetch(url).body) local results = raw_json.results.bindings

local result = mw.html.create result:tag("h2"):wikitext("Items for query: " .. queryType)

local ul = result:tag("ul") for _, item in ipairs(results) do       ul:tag("li"):tag("a"):attr("href", item.item.value):wikitext(item.itemLabel.value) end

return tostring(result) end

return p