Jump to content

API:Tags/Sample code 1

From mediawiki.org

Python

[edit]
#!/usr/bin/python3

"""
    get_tags.py

    MediaWiki API Demos
    Demo of `Tags` module: Get the first three change tags and their hitcounts.

    MIT License
"""

import requests

S = requests.Session()

URL = "https://en.wikipedia.org/w/api.php"

PARAMS = {
    "action": "query",
    "format": "json",
    "list": "tags",
    "tgprop": "hitcount",
    "tglimit": "3"
}

R = S.get(url=URL, params=PARAMS)
DATA = R.json()

TAGS = DATA["query"]["tags"]

for t in TAGS:
    print(t["name"])

PHP

[edit]
<?php
/*
    get_tags.php

    MediaWiki API Demos
    Demo of `Tags` module: Get the first three change tags and their hitcounts.

    MIT License
*/

$endPoint = "https://en.wikipedia.org/w/api.php";
$params = [
    "action" => "query",
    "format" => "json",
    "list" => "tags",
    "tgprop" => "hitcount",
    "tglimit" => "3"
];

$url = $endPoint . "?" . http_build_query( $params );

$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$output = curl_exec( $ch );
curl_close( $ch );

$result = json_decode( $output, true );

foreach( $result["query"]["tags"] as $k => $v ) {
    echo( $v["name"] . "\n" );
}

JavaScript

[edit]
/*
    get_tags.js

    MediaWiki API Demos
    Demo of `Tags` module: Get the first three change tags and their hitcounts.

    MIT License
*/

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

var params = {
    action: "query",
    format: "json",
    list: "tags",
    tgprop: "hitcount",
    tglimit: "3"
};

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 tags = response.query.tags;
        for (var t in tags) {
            console.log(tags[t].name);
        }
    })
    .catch(function(error){console.log(error);});

MediaWiki JS

[edit]
/*
	get_tags.js

	MediaWiki API Demos
	Demo of `Tags` module: Get the first three change tags and their hitcounts.

	MIT License
*/

var params = {
		action: 'query',
		format: 'json',
		list: 'tags',
		tgprop: 'hitcount',
		tglimit: '3'
	},
	api = new mw.Api();

api.get( params ).done( function ( data ) {
	var tags = data.query.tags,
		t;
	for ( t in tags ) {
		console.log( tags[ t ].name );
	}
} );