API:REST API/Extensions

MediaWiki version:
1.34

The MediaWiki REST API allows you to access wiki content and functionality through a RESTful, HTTP interface. MediaWiki extensions can build on the REST API to surface their own extension-specific endpoints. The REST API extension interface is available in MediaWiki 1.34 and later.

Defining routes

edit

An extension can define REST API endpoints in its extension.json file under the RestRoutes scope. RestRoutes is an array of objects, each representing a unique API path. Here's an example of an extension.json file that defines a REST API endpoint accessible at /rest.php/examples/v0/echo_path_param/{value_to_echo}/{text_action}.

{
	"name": "examples",
	"author": [
		"My Name"
	],
	"url": "https://www.mediawiki.org/wiki/Extension:Example",
	"descriptionmsg": "example-desc",
	"license-name": "GPL-2.0-or-later",
	"type": "other",
	"requires": {
		"MediaWiki": ">= 1.34",
		"platform": {
			"php": ">= 7.2"
		}
	},
	"AutoloadNamespaces": {
		"MediaWiki\\Extension\\Example\\": "includes/"
	},
	"RestRoutes": [
		{
			"path": "/examples/v0/echo_path_param/{value_to_echo}/{text_action}",
            "method": "GET",
			"class": "MediaWiki\\Extension\\Example\\RestApiExample"
		}
	],
	"manifest_version": 2
}

RestRoutes configuration properties

property type description
path string The path template. Paths should follow the format:
/<extension>/v<version number>/<resource>/{parameter}

Paths should start with an initial slash, designating the root of the REST API, followed by the extension name and a version number.

  • The extension name should be in lowercase (such as confirmedit or popups) and should not conflict with other extensions.
  • Versions should follow the format v<version number> and comply with the extension endpoint versioning policy.
  • Path parameters should be enclosed in braces (for example: {id}).
method string or array of strings The HTTP request method name or names. The REST API supports standard HTTP request methods such as GET, HEAD, POST, PUT, and DELETE.
class string The fully-qualified class name of the handler. You can assign a handler for the route through either the class property or the factory property. The class should be omitted if a factory is specified. In the example above, RestApiExample is assigned as the handler class for requests to this endpoint.
services array of strings When specifying a class, you can use a services array to inject dependencies into the handler.
factory string A factory function to be called to create the handler for this route. This should be omitted if a class is specified.
args array The arguments passed to the handler constructor or factory

Handling requests

edit

Within MediaWiki, a handler is a code unit responsible for accepting HTTP requests to a given route and returning a response. It is recommended to store handler files within a /Handler directory.

To implement a new handler, you can extend the Handler class. Handler provides accessors such as:

Handler subclasses should implement the execute() function, which is called when the endpoint is invoked. See the generated MediaWiki documentation for accessors available to the Handler class.

For simpler parameter mapping, extend the SimpleHandler class, which derives from Handler. SimpleHandler unpacks parameters from the path template and passes them as formal parameters to run(). SimpleHandler subclasses should implement run() instead of execute(). See the generated MediaWiki documentation for accessors available to SimpleHandler.

For example, here's a handler for a route that applies a text transformation to the value_to_echo provided in the path.

<?php

namespace MediaWiki\Extension\Example;

use MediaWiki\Rest\SimpleHandler;
use Wikimedia\ParamValidator\ParamValidator;

/**
 * Example class to echo a path parameter
 * GET /examples/v0/echo_path_param/{value_to_echo}/{text_action}
 */
class RestApiExample extends SimpleHandler {

	private const VALID_ACTIONS = [ 'reverse', 'shuffle' ];

	public function run( $valueToEcho, $action ) {
		switch ( $action ) {
			case 'reverse':
				return [ 'echo' => strrev( $valueToEcho ) ];

			case 'shuffle':
				return [ 'echo' => str_shuffle( $valueToEcho ) ];

			default:
				return [ 'echo' => $valueToEcho ];
		}
	}

	public function needsWriteAccess() {
		return false;
	}

	public function getParamSettings() {
		return [
			'value_to_echo' => [
				self::PARAM_SOURCE => 'path',
				ParamValidator::PARAM_TYPE => 'string',
				ParamValidator::PARAM_REQUIRED => true,
			],
			'text_action' => [
				self::PARAM_SOURCE => 'path',
				ParamValidator::PARAM_TYPE => self::VALID_ACTIONS,
				ParamValidator::PARAM_REQUIRED => false,
			],
		];
	}
}

Parameter validation

edit

getParamSettings() fetches ParamValidator settings for parameters defined by the API route. Each parameter must be specified with the PARAM_SOURCE (path, query, or post), the PARAM_TYPE, and PARAM_REQUIRED (true or false). The example above defines two path parameters: value_to_echo (a string) and text_action (one of a set of allowed strings specified by the VALID_ACTIONS constant).

Versioning

edit

To ensure stable interfaces, extension endpoints should be versioned separately from the MediaWiki version and the MediaWiki REST API version. The extension API version should be included in the path in the format /v<version number>/ where the version number is 0 or greater.

  • v0 indicates that the API is unstable and may change in backwards incompatible ways without notice.
  • v1 or greater indicates that the API is stable. Changes to API behavior are guaranteed to be backwards compatible within the same version. However, v1 or greater endpoints are not guaranteed to be backwards compatible with other versions.

Once the API is released as v1, increase the version if you need to make a backwards-incompatible change, such as:

  • Removing an endpoint
  • Removing or changing request or response properties

Additive changes to your API do not require a version increase, such as:

  • Adding an endpoint
  • Adding properties to request or response structures

Documenting endpoints

edit

Endpoints provided by an extension should be documented on the extension's main wiki page. See the extension REST API template to get started.

See also

edit