API:FAQ/ru

Внимание: эта страница находится в стадии разработки

Также прочтите краткое руководство пользователя. Оно отвечает на некоторые вопросы, на которые здесь не ответили, и направляет на другие полезные страницы.

получить помощь?

 * 1) Прочтите этот FAQ
 * 2) Попробуйте найти ответ на свой вопрос в документации по API здесь или на самодокументируемой странице по API
 * 3) Если Вы не можете найти ответ на свой вопрос в интернете,
 * 4) * Вы можете задать свой вопрос на mediawiki api почтовый список рассылки.
 * 5) * Create a Wikimedia account (if you don't have one already) and add a new topic on the API discussion page.
 * 6) Задайте вопрос в IRC на канале  в сети Freenode.

отправить отчёт об ошибке или запрос на введение возможности?
If you have found a bug in the API or have a feature request, report it in Phabricator. Search for existing bugs first (please don't file duplicate bugs) and enter MediaWiki-API as the project when reporting a new bug against the API. If the functionality you're requesting or reporting a bug against is offered by an extension (e.g. AbuseFilter, FlaggedRevs), add that extension's project, e.g. "MediaWiki-extensions-AbuseFilter".

figure out what action or submodule to call?
The MediaWiki API is big, and extensions further enlarge it. Some suggestions:


 * If you're trying to get information about a page, you probably will use a prop= submodule of . Other query submodules return lists of pages and meta-information about the wiki. [ View] the generated API help of all query submodules.
 * If you see a wiki page doing something interesting after initial page load, it must be making an API request.
 * Open your browser's developer console and look for its network requests to.
 * All the code running on Wikimedia wikis is open source, so you can read the source code making API requests. One strategy to locate source code is to append  to the wiki page URL to see the message keys near where API results are presented, then you can search for this message key in the localized message files i18n/en.json of core and extensions.
 * You can view the entire expanded generated API help on one page by appending, [ here it is].

The links to generated API help above go to English Wikipedia You should browse the generated API help on the wiki where you'll be making API requests, since different wikis have different configurations and different sets of extensions.

вызвать API?
Send HTTP requests to api.php. For example, on the English Wikipedia, the URL is https://en.wikipedia.org/w/api.php. Most wikis have api.php at a similar URL: just use api.php in place of index.php in page actions. From 1.17 onwards, MediaWiki supports Really Simple Discovery; the HTML source of every page has an RSD link pointing to an RSD descriptor which indicates where to find the API. If you can't figure out the URL of api.php on a third-party (non-Wikimedia-operated) wiki, contact its owner. The wiki may not enable the MediaWiki API, see.

To play with the API


 * use Special:ApiSandbox
 * enable your browser's developer console and watch net requests to api.php as you interact with the wiki

контролировать выходной формат?
Передайте  в строке запроса. См. список форматов вывода для большей информации. Обратите внимание, что в процессе удаление всех форматов, кроме JSON, так что старайтесь использовать JSON всегда, когда это возможно.

check if an API module is available?
You can use  to request information about the API modules and submodules (such as  ) that you want to invoke. The  array in the response must contain a   key for each module and submodule, anything missing is not available.

If an API module isn't available and you know which extension implements it, you can check if that extension is loaded by querying the siteinfo meta information for  and look for its name in the returned list.

Even if a module appears to be available, you must always handle API errors.

обнаружить ошибки?
See Errors and warnings.

An error response from the API will set the  HTTP header and return an   structure. For an example error response, visit https://en.wikipedia.org/w/api.php?action=blah.

получить содержимое страницы (wikitext)?
If you just want the raw wikitext without any other information whatsoever, it's best to use index.php's action=raw mode instead of the API: https://en.wikipedia.org/w/index.php?action=raw&title=Main_Page. Note that this will output plain wikitext without any formatting. See also the action=raw documentation

Чтобы получить больше информации о странице и о последней версии, используйте API: https://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles=Main_Page. См. также документацию к модулю prop=revisions.

Вы можете получить до 50 страниц за запрос к API: https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&titles=Main_Page|Articles. Это работает также с генераторами.

получить содержимое страницы (HTML)?
Если вы хотите только HTML, лучше использовать режим  index.php вместо API: https://en.wikipedia.org/wiki/Main_Page?action=render. См. также документацию action=render.

With the advent of RESTBase, on Wikimedia wikis you can instead request the cached HTML of a page, for example https://rest.wikimedia.org/en.wikipedia.org/v1/page/html/Main_Page (for performance this is also available at https://en.wikipedia.org/api/rest_v1/page/html/Main_Page to reuse an existing network connection to the wiki). Unlike  this returns a complete HTML document (i.e.    various metadata  ...  ); you could use an HTML parsing library to get the inner HTML of the   tag (see the documentation).

To get more information distilled from the wikitext at parse time (links, categories, sections, etc.), you can:


 * Query the property submodules that provide the information you need (links, categories, etc.).
 * Use the  API module:

deal with 2015's API changes?
The default continuation behavior changed in MediaWiki 1.26. If you request additional data based on continue information from an API response, you must update your code. Either
 * add  to your API requests to continue to get the confusing old query-continue behavior
 * or add  to your API requests and update to the cleaner continue processing that has been available since MediaWiki 1.21.

Also, since MediaWiki 1.25 an improved output structure for JSON and PHP formats has been available if you add   to your requests. As of July 2015, this is still considered experimental because a few API modules may get further improvements in this mode. If you're willing to risk needing to make future changes to adapt, it's much nicer to process API results with.

я получаю HTTP 403 ошибки?
Это может означать, что вы не указываете заголовок HTTP, или что ваш   пуст или внесён в чёрный список (User-Agent policy). См. справку для большей информации. Также это может означать, что вы указываете  в строке GET-запроса: Викимедиа блокирует все такие запросы, используйте для них POST.

я получаю readapidenied ошибку?
Вики, к которой вы обращаетесь, содержит необщедоступное содержимое и требует, чтобы участники вошли в учётную запись, чтобы они могли читать все страницы. Это означает, что клиенту требуется войти в учётную запись, чтобы запросить какую-либо информацию через API. Для большей информации см. руководство по быстрому старту.

я получаю badtoken ошибки?
This is usually because you're either not passing a token at all (read about tokens in the documentation of the module you're using) or because you're having trouble staying logged in. It's also possible you're reusing a type of token that can't be reused (see module documentation for details) or that you're using a token that's associated with an expired session. In general, when using cached tokens, refetch the token (see API:Tokens) and try again before giving up.

я получаю предупреждения вместо токенов (Action 'edit' is not allowed for the current user)?
У вас или нет прав исполнить запрошенное вами действие, и ли у вас проблемы с тем, чтобы оставаться залогинившимися.

do I get mustposttoken error?
The action you're attempting must be requested using HTTP POST. You probably clicked on  URL in a browser or modified an existing URL in the browser's location field, but that results in an HTTP GET request. You have to use a library (such as the mediawiki.api ResourceLoader module) or utility that can make POST requests; usually you also have to provide it your session cookies and an API:token so MediaWiki can verify that you are the logged-in user with rights to perform the action. As a hack, you might be able to use the cURL command-line utility, providing it each API parameter with  and the necessary browser cookies with. The Network panel of the browser developer tools window (Ctrl+Shift+I) in Firefox and chromium has a "Copy as cURL" menu item that can help, but it's still fiddly.

Depending on what you want to do it's easier to learn how to use a bot or library that handles the details of login, cookies, and tokens for you.

X не доступно через API?
Не все возможности, доступные в пользовательском интерфейсе, доступны в API. Такие возможности не были реализованы, поскольку либо никто не добрался до этого, либо никто этого не запрашивал. Для информации об отправке запросов на введение возможностей, см. выше.

мой вызов API на вики Викимедиа просто возвращает ошибку HTML?
If you use API calls with POST requests make sure that these requests don't use Content-Type: multipart/form-data. This happens for instance if you use CURL to access the API and you pass your POST parameters as an array. The Squid proxy servers which are used at frontend servers at the Wikimedia wiki farm don't handle that correctly, thus an error is returned.

Instead, use the "value1=key1&value2=key2..." notation to pass the parameters as a string, similar to GET requests.

On other wikis which you access directly it doesn't make a difference.

In addition, some software (such as cURL) send an  header for longer POST requests (>1024 bytes). The wikimedia wikis that go through Squid servers can't cope with this. If you are still getting HTML errors with post requests, and are not logged in, try setting a blank Expect header (e.g. using cURL on the command line, use the option ).

do really long API urls not work?
There is a maximum limit of the url size that can be used with the API when making GET requests. This limit varies depending on the website. Wikimedia's limit is roughly around 8100 characters. To get around this limit use POST requests instead (you may also need to set the Expect header, as described above)