API:확장 기능

From mediawiki.org
This page is a translated version of the page API:Extensions and the translation is 22% complete.

확장 기능에서 API 모듈을 어떻게 생성하는지에 대해 설명합니다. 미디어위키 1.30 이상 버전에서 사용 가능합니다.

모듈 생성과 사용

모든 API 모듈은 ApiBase 의 하위클래스입니다. 하지만 몇 가지 유형의 모듈은 자식 클래스를 사용합니다. 이들에 대한 사용 방법은 모듈 유형에 따라 달라집니다.

action 모듈
action에 대한 결과값을 반환하는 모듈들은 ApiBase 의 하위 클래스입니다. 해당 모듈들은 APIModulesextension.json에서 사용할 수 있습니다.
format 모듈
format에 대한 결과값을 반환하는 모듈들은 ApiFormatBase의 하위 클래스입니다. APIFormatModules에서 extension.json을 사용할 수 있습니다. format 모듈이 필요한 경우는 그다지 많지 않습니다.
query 하위 모듈
query의 하위 모듈들에는 prop, list, meta, action=query가 있습니다. 이들은 제너레이터(generator)를 사용할 경우 ApiQueryGeneratorBase으로, 사용하지 않을 경우 ApiQueryBase의 하위 클래스로 사용됩니다. APIPropModules, APIListModules, APIMetaModules에서 이용하기 위해선 형식이 extension.json이어야 합니다.

In all cases, the value for the registration key is an object with the module name (i.e. the value for the parameter) as the key and the class name as the value. Modules may also be registered conditionally using the ApiMain::moduleManager (for action and format modules) and ApiQuery::moduleManager (for query submodules) hooks.

구현

범위 지정 연산자(scope resolution operator) 사용

In the constructor of your API module, when you call parent::__construct() you can specify an optional prefix for your module's parameters. (In the generated documentation for a module this prefix, if any, appears in parentheses in the heading for the module.) If your module is a query submodule then a prefix is required, since a client can invoke multiple submodules each with its own parameters in a single request. For action and format modules, the prefix is optional.

매개 변수

Most modules require parameters. These are defined by implementing getAllowedParams(). The return value is an associative array where keys are the (unprefixed) parameter names and values are either the scalar default value for the parameter or an array defining the properties of the parameter using the PARAM_* constants defined by ApiBase.

The example illustrates the syntax and some of the more common PARAM_* constants.

	protected function getAllowedParams() {
		return [
			// An optional parameter with a default value
			'simple' => 'value',

			// A required parameter
			'required' => [
				ApiBase::PARAM_TYPE => 'string',
				ApiBase::PARAM_REQUIRED => true,
			],

			// A parameter accepting multiple values from a list
			'variable' => [
				// The default set of values
				ApiBase::PARAM_DFLT => 'foo|bar|baz',
				// All possible values
				ApiBase::PARAM_TYPE => [ 'foo', 'bar', 'baz', 'quux', 'fred', 'blah' ],
				// Indicate that multiple values are accepted
				ApiBase::PARAM_ISMULTI => true,
				// Use standard "per value" documentation messages
				ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
			],

			// A standard "limit" parameter. It's generally best not to vary from this standard.
			'limit' => [
				ApiBase::PARAM_DFLT => 10,
				ApiBase::PARAM_TYPE => 'limit',
				ApiBase::PARAM_MIN => 1,
				ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
				ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2,
			],
		];
	}

Parameters are documented using MediaWiki's i18n mechanism. See #Documentation for details.

Execution and output

The code actually implementing the module goes in the execute() method. This code will generally use $this→extractRequestParams() to get the input parameters, and will use $this→getResult() to get the ApiResult object to add any output to.

Query prop submodules should use $this→getPageSet() to access the set of pages to operate on.

Query submodules that can be used as generators will also need to implement executeGenerator() which is passed and ApiPageSet that should be filled with the generated pages. In this case, the ApiResult should generally not be used.

Caching

By default API responses are marked as not cacheable ('Cache-Control: private')! For action modules, you can allow caching by calling $this→getMain()→setCacheMode(). This still requires clients pass the maxage or smaxage parameters to actually enable caching. You can force caching by also calling $this→getMain()→setCacheMaxAge().

For query modules, do not call those methods. You can allow caching by instead implementing getCacheMode().

In either case, be sure that private data is not exposed.

토큰 처리

If your action module changes the wiki in any way, it should require a token of some kind. To have this handled automatically, implement the needsToken() method, returning the token that your module requires (probably the 'csrf' edit token). The API base code will then automatically validate the token that clients provide in API requests in a token parameter.

If you don't want to use a token that is part of core, but rather a custom token with your own permission checks, use ApiQueryTokensRegisterTypes hook to register your token.

Master database access

If your module accesses the master database, it should implement the isWriteMode() method to return true.

Returning errors

ApiBase includes several methods for performing various checks, for example,

  • If the user is blocked (and that matters to your module), pass the Block object to $this→dieBlocked().

But you will often run into cases where you need to raise an error of your own. The usual way to do that is to call $this→dieWithError(), although if you have a StatusValue with the error information you could pass it to $this→dieStatus() instead.

If you need to issue a warning rather than an error, use $this→addWarning() or $this→addDeprecation() if it's a deprecation warning.

문서화

The API is documented using MediaWiki's i18n mechanism. Needed messages generally have default names based on the module's "path". For action and format modules, the path is the same as the module's name used during registration. For query submodules, it's the name prefixed with "query+".

Every module will need a apihelp-$path-summary message, which should be a one-line description of the module. If additional help text is needed, apihelp-$path-extended-description may be created as well. Each parameter will need a apihelp-$path-param-$name message, and parameters using PARAM_HELP_MSG_PER_VALUE will also need a apihelp-$path-paramvalue-$name-$value for each value.

More details on API documentation are available at API:지역화 .

Extensions may also document their extra API modules on mediawiki.org. This should be located on the extension's main page or, if more space is required, on pages named Extension:<ExtensionName>/API or subpages thereof (e.g. CentralAuth , MassMessage , or StructuredDiscussions ). The API namespace is reserved for the API of MediaWiki core.

Extending core modules

Since MediaWiki 1.14, it's possible to extend core modules' functionality using the following hooks:

List of extensions with API functionality

See 분류:API 확장 기능 for examples of extensions that add to or extend the API.

당신의 확장기능 테스트하기

  • Visit api.php and navigate to the generated help for your module or query submodule.

Your extension's help information should be correct.

    • The example URLs you provided in getExamplesMessages() should appear under "Examples", try clicking them.
    • Omit and mangle URL parameters in the query string, check your extension's response.
  • To see additional information about your extension: