As an Android developer, I spend quite a bit of time integrating existing web services. I typically will find a URI for a web service, and then use a debug console to figure out what params I need to pass it, and what response payload I can expect. Then I go thru the painful process of making network calls to make requests, parse the response, and then turn it into POJOs that I can use in my code! This is just a painful process that just gets repeated  over and over again. And then if I want to make changes to the service, of if it changes, then I have to repeat this process again. I’ve been looking for a lightweight Android friendly way to do this for sometime, and have been on the lookout for an Axis replacement (so to speak). And I’ve found this in the rest2mobile tool from Magnet. As a bonus, it also generates iOS, and JS code to boot!

The rest2mobile Android Studio plugin allows you to generate client side API from REST services directly inside your android project. You can just start w/ a URI for your web service, and put it into the Android Studio plugin, and it will generate client side code, so that you can easily access these services w/out any hand coding, or having to deal w/ marshalling / unmarshalling, or making network calls, etc. It can save a lot of time for mundane, boilerplate code, that you would have to otherwise generate. It’s pretty good at codegen as well; the code that it generates is human readable, and can be refactored. And the plugin is pretty smart about not clobbering unit tests, in case you re-generate the client side code for your web services. This tool does a great job w/ Developer Experience. It integrates w/ whatever flow that you’re used to a developer. For me, I use IDEA, so it works great. But if you use Android Studio, it works great as well. And they’ve got command line tools that you can use to script this stuff as well. And they support generating code for iOS & JS.

The following steps will show you how to get started. If you want to watch the accompanying video that shows you these steps, check this out – https://www.youtube.com/watch?v=_6gtI5v4m8U

STEP 1: Download

Go to the releases page and download the latest installer.

Note: You can find the latest official release on the Magnet developer site too.

STEP 2: Install plugin

In Android Studio or IntelliJ, go to Preferences -> Plugins and click on Install plugin from disk...

It will ask you to choose the location of the installer zip, point to the package that you’ve just downloaded.

Note: the plugin is also distributed on the Jetbrains repository, so instead of clicking on Install plugin from disk…, you can choose Browse repositories... and then look for rest2mobile.

STEP 3: Restart your IDE after loading the plugin


STEP 4: Load or create an android application

It is recommended to use a gradle-based application (if you are still using ant, go here).

Ensure that you use at a minimum the Android API level 15.

STEP 5: Add new API

Once the IDE has restarted, you should see the new R2M menu (or “Magnet” menu in earlier releases):

rest2mobile plugin main menu

Choose “Add new API” from the R2M menu (‘Magnet’ menu for earlier releases). The following describes the wizard options:

image

Alternatively, instead of crafting your own REST invocations, you can load existing examples from the r2m-examples github repo by clicking on the browse icon next to the Class Name box:

STEP 6: Generate code

Click on “Generate”, this generates the code under your <code>src</code> directory. If you have a src/androidTest/java directory, a unit test file is also generated.

Ex: say you selected the GoogleDistance built-in example, you should see the following files in your project pane:

STEP 7: Test

Use the generated unit test generated under src/androidtest/java/

Ex: if you generated the GoogleDistance native API, the unit test can be found at src/androidTest/java/com/magnetapi/examples/controller/api/test/GoogleDistanceTest. Remove the @Supress annotation on testGoogleDistance, and invoke the API with real values:

  /**
    * Generated unit test for {@link GoogleDistance#googleDistance}
    */
  @SmallTest
  public void testGoogleDistance() throws SchemaException, ExecutionException, InterruptedException {
    String origins = "435 Tasso Street, Palo Alto CA";
    String destinations = "1 Embarcadero Street, San Francisco, CA";
    String sensor = "false";
    String mode = "driving";
    String language = "en";
    String units = "imperial";

    Call<GoogleDistanceResult> callObject = googleDistance.googleDistance(
      origins, 
      destinations, 
      sensor, 
      mode, 
      language, 
      units, null); 
    GoogleDistanceResult result = callObject.get(); // Or use a non-null 'StateChangedListener' in 'googleDistance' to be asynchronously called back, once result is avail.
    assertEquals("33.9 mi", result.getRows().get(0).getElements().get(0).getDistance().getText());// actual distance may vary
  }

Notice how the rest2mobile’s java invocation allows you to safely navigate the JSON payload:

Strongly-typed in java:

String distance = result.getRows().get(0).getElements().get(0).getDistance().getText());

Stringly-typed in JSON:

{
   "destination_addresses" : [ "1 Lombard Street, San Francisco, CA 94111, USA" ],
   "origin_addresses" : [ "435 Tasso Street, Palo Alto, CA 94301, USA" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "33.9 mi",
                  "value" : 54605
               },
               "duration" : {
                  "text" : "44 mins",
                  "value" : 2626
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

Feedback

To submit your feedback for existing features, and to make new feature requests, click here.

Blog

Get latest tips, news, and useful information from the rest2mobile blog.