Skip to content
alexz-enwp edited this page Jan 1, 2015 · 8 revisions

The APIRequest object is used to handle communication with the wiki. All functions that interact with the wiki use one or more APIRequests. Each object is designed to handle one API query. All HTTP requests are done via POST.

Constructor

APIRequest has 3 constructor parameters, 2 of which are required:

  • site - A Wiki object corresponding to the site to communicate with (required)
  • data - A Python dictionary of key:value options for the API query (required)
  • write - Specifies whether the request is making a change on the wiki or not, HTTP error handling is different for write queries. For errors on non-write queries, wikitools will print the error info, wait, then try again (the number of retries is set by Wiki.maxwaittime). For write queries, to avoid potentially writing the same data multiple times, it will not retry and will raise the exception. The default value is False.
  • file - A file object to upload with the request. Default: None

Methods

changeParam

changeParam(param, value)

Change the value of a parameter, param (or add a new parameter) in the request parameters. It will raise an APIError if you try to change the "format" parameter (which must always be "json" and is set automatically).

query

query(querycontinue=True)

Do the HTTP request and return a result.

The querycontinue parameter is deprecated and will be removed in the future. It is kept "True" by default for backwards-compatibility. If querycontinue is set to True (the default), and a query-continue value is found in the results, the query will be automatically continued with the value until a query is done that does not have a query-continue. The returned result will include the results from all queries combined. This method for continuing queries is deprecated within MediaWiki and the functions that attempt to combine the result sets can be inefficient and unreliable.

To get data that requires multiple continued queries, you should either handle the continuation in your own code or use the queryGen() function described below.

queryGen

queryGen()

queryGen implements an improved way to retrieve continued queries introduced in MediaWiki 1.20. Rather than attempting to hold the entire result set in memory and return it all at once, it is a Python generator function that will yield each result set.

In many cases, replacing query(querycontinue=True) with queryGen will be as simple as:

Before (deprecated)

##Set up query params
request = api.APIRequest(site, params)
result = request.query(True)
## Process results

After

##Set up query params
request = api.APIRequest(site, params)
for result in request.queryGen():
    # Process results

Private methods

  • __longQuery - (Deprecated) Implements the querycontinue option by searching for query-continue values and re-running queries with them. Will be removed whenever the querycontinue option is removed.
  • __getRaw - Gets the raw JSON text from the server, handles HTTP errors
  • __parseJSON - Transforms the JSON object into a Python object, handles maxlag errors.

Instance variables

Public

  • sleep - Controls how long to sleep before trying a request again after an HTTP error. Automatically incremented by __getRaw. This should not be changed and it may be made private in a future release.
  • data - A shallow copy of (not a reference to) the data parameter passed during construction. This can be read and changed using changeParam.
  • iswrite - The value of the write parameter passed during construction. Can be changed, though there isn't much reason to do so.
  • headers - The HTTP headers for the HTTP request. This can be changed if you really know what you're doing.
  • site - The value of the site parameter passed during construction. This cannot be changed and it may be made private in a future release.
  • response - Contains a requests.models.Response object with headers and other information after query is called. Set to None before the request is made.
  • authman - None, or a requests.auth.HTTPDigestAuth if using HTTP Auth

Private

  • _continues - Used in __longQuery, otherwise unset.
  • _generator - Used in __longQuery, otherwise unset.

Examples

See the MediaWiki API documentation for information about what information is available from the API and what parameters to use. "format=json" is automatically applied to each request and cannot be overridden.

Get some information about a wiki:

import pprint # Used for formatting the output for viewing, not necessary for most code
from wikitools import wiki, api
site = wiki.Wiki("https://www.mediawiki.org/w/api.php")
params = {'action':'query',
    'meta':'siteinfo',
    'siprop':'general'
}
req = api.APIRequest(site, params)
res = req.query(querycontinue=False)
pprint.pprint(res)

This will return something like:

{'query': {'general': {'articlepath': '/wiki/$1',
                       'base': 'http://www.mediawiki.org/wiki/MediaWiki',
                       'case': 'first-letter',
                       'dbtype': 'mysql',
                       'dbversion': '10.0.13-MariaDB-log',
                       'extensiondistributor': {'list': 'https://gerrit.wikimedia.org/mediawiki-extensions.txt',
                                                'snapshots': ['master',
                                                              'REL1_24',
                                                              'REL1_23',
                                                              'REL1_22',
                                                              'REL1_21',
                                                              'REL1_20',
                                                              'REL1_19']},
                       'fallback': [],
                       'fallback8bitEncoding': 'windows-1252',
                       'favicon': '//bits.wikimedia.org/favicon/mediawiki.ico',
                       'generator': 'MediaWiki 1.25wmf13',
                       'git-branch': 'wmf/1.25wmf13',
                       'git-hash': 'f6b99be872201a324d96e480c982abc814a08503',
                       'hhvmversion': '3.3.1',
                       'imagelimits': [{'height': 240, 'width': 320},
                                       {'height': 480, 'width': 640},
                                       {'height': 600, 'width': 800},
                                       {'height': 768, 'width': 1024},
                                       {'height': 1024, 'width': 1280}],
                       'imagewhitelistenabled': '',
                       'lang': 'en',
                       'langconversion': '',
                       'legaltitlechars': ' '
                                          '%!"$&\'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z~\\x80-\\xFF+',
                       'linkprefix': '',
                       'linkprefixcharset': '',
                       'linktrail': '/^([a-z]+)(.*)$/sD',
                       'logo': '//upload.wikimedia.org/wikipedia/mediawiki/b/bc/Wiki.png',
                       'mainpage': 'MediaWiki',
                       'maxuploadsize': 1048576000,
                       'misermode': '',
                       'phpsapi': 'srv',
                       'phpversion': '5.6.99-hhvm',
                       'script': '/w/index.php',
                       'scriptpath': '/w',
                       'server': '//www.mediawiki.org',
                       'servername': 'www.mediawiki.org',
                       'sitename': 'MediaWiki',
                       'thumblimits': [120, 150, 180, 200, 220, 250, 300],
                       'time': '2014-12-29T20:13:40Z',
                       'timeoffset': 0,
                       'timezone': 'UTC',
                       'titleconversion': '',
                       'variantarticlepath': False,
                       'wikiid': 'mediawikiwiki',
                       'writeapi': ''}}}
Clone this wiki locally