Search code examples
jsonmediawiki-apimediawiki-extensions

MediaWiki API Extension JSON


I have developed a MediaWiki extension that gets a (JSON) string from an external service using cURL.

Now I'm looking for a way to retrieve just that string from the MediaWiki system. (This URL will be used for AJAX calls.)

First, I thought that MediaWiki API was the way to do that. However, I can't seem to be able to output just that string.

What would be the right way to achieve this?

UPDATE

Thank you, that did the trick. For your information, here's how far I got:

$this->getResult()->addValue(null, null, array( 'autocomplete' => array( 'server', 'servers' ) ) );

returns [{"autocomplete":["server","servers"]}] when appending format=json to the API URL. Instead of the above JSON string, the JavaScript client I'm working with needs {"autocomplete":["server","servers"]} in order to work correctly. In other words, I needed to get rid of [ and ].

Just out of curiosity, is a custom printer still the way to go?


Solution

  • In your API module, override getCustomPrinter():

    public function getCustomPrinter() {
        return new ApiFormatRaw(
            $this->getMain(),
            $this->getMain()->createPrinterByName( 'json' )
        );
    }
    

    (the nested createPrinterByName() call is for fallback format in case of errors, you can change it to some other format)

    Then, in your execute() method or wherever you need to return the value:

    $this->getResult()->addValue( null, 'text', $data_you_want_to_return );
    $this->getResult()->addValue( null, 'mime', 'application/json' );