Damjan Pavlica
Damjan Pavlica

Reputation: 34043

How to read MediaWiki API JSON response

I am trying to search images on Wikimedia Commons, using MediaWiki API. Here is my requested URL with search params:

https://commons.wikimedia.org/w/api.php?action=query&list=allimages&format=json&aifrom=Dada

I am succeed to get response in JSON format, but I could not read it programmatically because:

No 'Access-Control-Allow-Origin' header is present on the requested resource.

Any advice?

UPDATE:

I have added one more param to the url: callback=JSON_CALLBACK, which transforms response to jsonp format. Now it possible to use angular $http.jsonp() method also.

Upvotes: 3

Views: 863

Answers (2)

Rainer Rillke
Rainer Rillke

Reputation: 1321

If you are accessing the Wikimedia Commons API from a Wikimedia wiki, you can use the origin parameter of the API and this way make the API setting CORS headers. E.g. on en.wikipedia.org, you could access the Commons API this way:

$.get('https://commons.wikimedia.org/w/api.php?' +
    $.param({
        format: 'json',
        action: 'query',
        list: 'allimages',
        aifrom: 'Dada',
        origin: location.protocol + '//' + location.host
    })).done(function() { /*...*/ });

It is generally safer to use JSON (a pure data format) than loading and executing JavaScript (JSONP) file that could, in theory, do evil with your visitors. I would probably set up a proxy server for this purpose, instead of using JSONP. A simple web search for set up a proxy json may result in plenty of useful results.

Upvotes: 1

davidkonrad
davidkonrad

Reputation: 85558

use jsonp1 as dataType to prevent the "No 'Access-Control-Allow-Origin' header is present on the requested resource." error. Then it works :

$.ajax({
    dataType: 'jsonp',
    url : 'https://commons.wikimedia.org/w/api.php?action=query&list=allimages&format=json&aifrom=Dada',
    success : function(json) {
        json.query.allimages.forEach(function(item) {
            $('<img/>', { src : item.url }).appendTo('#images');
        })    
    }     
})    

Here I add each image to a #images <div> just for demonstration purposes.

demo -> http://jsfiddle.net/52g2Lazw/

1) JSONP stands for “JSON with Padding” and it is a workaround for loading data from different domains. It loads the script into the head of the DOM and thus you can access the information as if it were loaded on your own domain, thus by-passing the cross domain issue cite.

Upvotes: 3

Related Questions