Jump to content

API:Search/Sample code 1

From mediawiki.org
Revision as of 22:44, 17 January 2023 by Izno (talk | contribs) (removed fixed width)

Python

#!/usr/bin/python3

"""
    search.py

    MediaWiki API Demos
    Demo of `Search` module: Search for a text or title

    MIT License
"""

import requests

S = requests.Session()

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

SEARCHPAGE = "Nelson Mandela"

PARAMS = {
    "action": "query",
    "format": "json",
    "list": "search",
    "srsearch": SEARCHPAGE
}

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

if DATA['query']['search'][0]['title'] == SEARCHPAGE:
    print("Your search page '" + SEARCHPAGE + "' exists on English Wikipedia")

PHP

<?php
/*
    search.php

    MediaWiki API Demos
    Demo of `Search` module: Search for a text or title

    MIT License
*/

$searchPage = "Nelson Mandela";

$endPoint = "https://en.wikipedia.org/w/api.php";
$params = [
    "action" => "query",
    "list" => "search",
    "srsearch" => $searchPage,
    "format" => "json"
];

$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 );

if ($result['query']['search'][0]['title'] == $searchPage){
    echo("Your search page '" . $searchPage . "' exists on English Wikipedia" . "\n" );
}

JavaScript

/*
    search.js

    MediaWiki API Demos
    Demo of `Search` module: Search for a text or title

    MIT License
*/

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

var params = {
    action: "query",
    list: "search",
    srsearch: "Nelson Mandela",
    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) {
        if (response.query.search[0].title === "Nelson Mandela"){
            console.log("Your search page 'Nelson Mandela' exists on English Wikipedia" );
        }
    })
    .catch(function(error){console.log(error);});

MediaWiki JS

/*
	search.js

	MediaWiki API Demos
	Demo of `Search` module: Search for a text or title

	MIT License
*/

var params = {
		action: 'query',
		list: 'search',
		srsearch: 'Nelson Mandela',
		format: 'json'
	},
	api = new mw.Api();

api.get( params ).done( function ( data ) {
	if ( data.query.search[ 0 ].title === 'Nelson Mandela' ) {
		console.log( "Your search page 'Nelson Mandela' exists on English Wikipedia" );
	}
} );