Search code examples
http-redirectmediawikimediawiki-api

How to resolve redirects from MediaWiki


I'm currently trying to read the content of a MediaWiki site for which I only know only a generic URL which would redirect me to the 'real' content:

e.g when I want to read the explainxkcd content for comic 2423, I can use 2423 as a title and request

https://www.explainxkcd.com/wiki/api.php?action=query&prop=revisions&rvprop=content&formatversion=2&format=json&titles=2423

Which gives me

{
  "batchcomplete": true,
  "query": {
    "pages": [
      {
        "pageid": 23828,
        "ns": 0,
        "title": "2423",
        "revisions": [
          {
            "contentformat": "text/x-wiki",
            "contentmodel": "wikitext",
            "content": "#REDIRECT [[2423: Project Orion]]"
          }]}]}}

I can now parse 2423: Project Orion from "#REDIRECT [[2423: Project Orion]]" and manually turn it into titles=2423:_Project_Orion giving me

https://www.explainxkcd.com/wiki/api.php?action=query&prop=revisions&rvprop=content&titles=2423:_Project_Orion

But this feels strange and uselessly manual. Unfortunately I'm not so much into MediaWiki or web APIs in general - can you give me a hint how I should come from

2423 (a generic index I know)

to

https://www.explainxkcd.com/wiki/api.php?action=query&prop=revisions&rvprop=content&titles=2423:_Project_Orion (the URL I want to query)

without having to manually synthesize the title from the MediaWiki answer?


Solution

  • Add &redirects=1 to your query string:

    https://www.explainxkcd.com/wiki/api.php?action=query&prop=revisions&rvprop=content&formatversion=2&format=json&titles=2423&redirects=1

    redirects: Automatically resolve redirects in query+titles, query+pageids, and query+revids, and in pages returned by query+generator.

    Type: boolean (details)