Fetch Data From Wikipedia

Hi everyone !!!
What I am having is a site where selected users can post reviews about anything and others can comment like etc (E-End of T-Thinking C-Capacity)


Objective

So what I want is when the user types, for example ‘Ant’, in the input I want to get the primary image from Wikipedia otherwise the user has to upload manually…


Process

So here it is the process or code →
(Keep it in mind that the result always may not be satisfactory…)

import { fetch } from 'wix-fetch';
let name;
$w.onReady(function () {

 var url = "https://en.wikipedia.org/w/api.php";

 var params = {
        action: "query",
        prop: "images",
        titles: "Ant",        //searching for Ant
        format: "json"
    };

    url = url + "?origin=*";
    Object.keys(params).forEach(function (key) { url += "&" + key + "=" + params[key]; });

    fetch(url)
        .then(function (response) { return response.json(); })
        .then(function (response) {
 var pages = response.query.pages;
 for (var page in pages) {
 for (var img of pages[page].images) {
                    name = img.title.slice(5);
                    console.log(name);
                    pop();
                }
            }
        })
        .catch(function (error) { console.log(error); });
});

function pop() {
 var url = "https://en.wikipedia.org/w/api.php";

 var params = {
        action: "query",
        format: "json",
        list: "allimages",
        aifrom: name,
        ailimit: "1"
    };

    url = url + "?origin=*";
    Object.keys(params).forEach(function (key) { url += "&" + key + "=" + params[key]; });

    fetch(url)
        .then(function (response) { return response.json(); })
        .then(function (response) {
 var images = response.query.allimages;
 for (var img in images) {
                console.log(images[img].url);    //here we will get the url of the image...
            }
        })
        .catch(function (error) { console.log(error); });
}

Hope it would be useful !!!

3 Likes