Examples

From BITPlan mediawiki-japi Wiki
Jump to: navigation, search

Intro

Depending on your version of Mediawiki you'll get different API details and help pages:

API usage examples

You might have to change the DEFAULT_SCRIPTPATH depending on your wiki configuration see Issue26

Sample query:get a single page

http://www.mediawiki.org/wiki/API:Query#Sample_query

Mediawiki wiki=new Mediawiki("http://en.wikipedia.org");
String content=wiki.getPageContent("Main Page");

JUnit Test

/**
 * http://www.mediawiki.org/wiki/API:Query#Sample_query
 * http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&titles=Main%20Page&format=xml
 * @throws Exception 
 */
@Test
public void testSampleQuery() throws Exception {
  Mediawiki wiki=new Mediawiki("http://en.wikipedia.org");
  String content=wiki.getPageContent("Main Page");
  assertTrue(content.contains("Wikipedia"));
}

login/logout

http://www.mediawiki.org/wiki/API:Login

Login login=wiki.login("scott","tiger");
wiki.logout();

Junit Test

  /**
   * test Login and logout 
   * see <a href='http://www.mediawiki.org/wiki/API:Login'>API:Login</a>
   * @throws Exception
   */
   @Test
   public void testLogin() throws Exception {
     WikiUser wuser=WikiUser.getUser("mediawiki_org");
     Login login=wiki.login(wuser.getUsername(),wuser.getPassword());
     assertEquals("Success",login.getResult());
     assertNotNull(login.getLguserid());
     assertEquals(wuser.getUsername(),login.getLgusername());
     assertNotNull(login.getLgtoken());
     wiki.logout();
   }

query

Junit Test

Allpages

        /**
	 * test the Allpages API call http://www.mediawiki.org/wiki/API:Allpages
	 * 
	 * @throws Exception
	 */
	@Test
	public void testGetAllPages() throws Exception {
		for (ExampleWiki lwiki : getWikis()) {
			Api api = getQueryResult(lwiki, "&list=allpages&apfrom=Kre&aplimit=3");
			List<P> pageRefList = api.getQuery().getAllpages();
			assertEquals(lwiki.getSiteurl(),3, pageRefList.size());
		}
	}

Edit

https://www.mediawiki.org/wiki/API:Edit

wiki.login("scott","tiger");
wiki.edit("Test Page 1","new content of test page 1","Summary for this edit");

TestAPI_Edit.java JUnit test

Multiple Implementations

0.1.02 supports to use different implementations via the common MediawikiApi Java Interface. E.g. you can use the one-class implementation org.wikipedia.Mediawiki.

  @Test
  /**
   * Test for issue #3
   * @throws Exception
   */
  public void testMultipleImplementations() throws Exception {
    MediawikiApi[] wikiapis = { new Mediawiki(), new org.wikipedia.Mediawiki() };
    for (MediawikiApi wikiapi : wikiapis) {
      wikiapi.setSiteurl("http://en.wikipedia.org");
      String content = wikiapi.getPageContent("Main Page");
      assertTrue(content.contains("Wikipedia"));
    }
  }

TestUsage.java JUnit test