User:Lucas Werkmeister/m3api-ApiSandbox-helper

From Meta, a Wikimedia project coordination wiki
Screenshot

The m3api-ApiSandbox-helper (source code) is a user script which extends the API sandbox, adding an option to show the request data as m3api code after a request has been made.

Installation[edit]

Add the following line to your global.js:

mw.loader.load( '//meta.wikimedia.org/w/index.php?title=User:Lucas_Werkmeister/m3api-ApiSandbox-helper.js&action=raw&ctype=text/javascript' );

You can also add it to your common.js on non-Wikimedia wikis, it should work there as well.

Usage[edit]

Use the API sandbox as usual. When you make a request, the “results” panel contains a dropdown to “show request data as”; the default option is “URL query string”. The user script adds an option “m3api code” to the dropdown – select it to see the generated code.

To use the code, install m3api using npm (npm install m3api), then paste the code into a file following a header like the following:

import Session, { set } from 'm3api/node.js';

// generated code goes here

console.log( response ); // example

Change the userAgent request option to an appropriate string (see the User-Agent policy).

Note that the user script tries to be smart about how the code should be generated (e.g. which params are multi-valued, which ones should be default params set in the constructor), but you should still inspect the code and make sure it does what you want before running it.

Example[edit]

If you want to look at the code generated by the script without installing it, here’s an example for this API sandbox URL:

const session = new Session( 'www.wikidata.org', {
	formatversion: 2,
	// (suggestion) errorformat: 'plaintext',
}, {
	userAgent: 'm3api-ApiSandbox-helper', // change this :)
} );
const response = await session.request( {
	action: 'query',
	list: set( 'allrevisions' ),
	arvprop: set( 'ids', 'timestamp' ),
	arvlimit: 10,
	arvnamespace: set(
		0, // (Main)
		10, // Template
	),
} );

Compatibility[edit]

As long as m3api is in the 0.x version range, the generated code only formally supports the latest released version. (Specifically, versions before v0.5.0 definitely won’t work, because the script abbreviates the api.php URL to just the domain if possible, which is a new feature in v0.5.0.) Once m3api 1.0.0 is released, the user script will probably try to support all releases of the latest major version.