r2m
is a command-line tool that generates native Android, iOS, and JavaScript code from REST APIs. Here is a short demo.
Note: If you are developing with Android Studio or IntelliJ, you can use the rest2mobile plugin for Android instead of the CLI. For iOS apps, you can use the rest2mobile plugin for Xcode.
r2m
requires Java 6 or later and supports the following platforms:
- Windows® 7 or later
- Mac® OS X® 10.08 or later
- Linux® Ubuntu® 12
mvn install -DskipTests
./cli-r2m-installer/target/magnet-tools-cli-r2m-installer-<version>/r2m
r2m> gen --interactive
Find universal installers here
Run:
brew install https://raw.githubusercontent.com/magnetsystems/r2m-cli/master/brew/r2m.rb
If you don't have brew, go to: http://brew.sh/
Unzip the rest2mobile zip file and add r2m to the path.
This starts the r2m
shell console. It supports help, completion, and ANSI coloring.
$ r2m
Starting rest2mobile 1.0.0
Run 'gen --interactive' to generate Mobile APIs in interactive mode.
Type '?' for help. Use <TAB> for completion. <Ctrl-D> to abort commands.
r2m> gen
Useful to run single command, or include in script
$ r2m gen -e <file> [-o <outputdir>] [-p <package>] [-j IGNORE] [-n <classPrefix>] [-c <ClassName>] [<target: android|js|ios>] [-flw] [-d <ApiID>]
For the rest of this tutorial r2m
commands will be run in interactive mode. So you need to run r2m
first.
r2m> help -v gen
or check the CLI usage.
Here's a simple example generating the Google distance Mobile API for iOS, Android and Javascript
r2m> gen -d GoogleDistance
You can get a list of examples with:
r2m> gen -l
All examples are available on rest2mobile examples repo
Generate the Android Mobile API from the example myExample.txt
r2m> gen -e myExample.txt -o myapp/src/java android
Same operation for Javascript:
r2m> gen -e myExample.txt -o jscode js
Same operation for iOS and Android only under controllers directory:
r2m> gen -e myExample.txt -o controllers ios android
Delete directory outputDir first, if it exists, with -f
, before generating the API:
r2m> gen -f -e myExample.txt -o outputDir
Open the directory after generation of the Google Distance API with -w
. Default output directory is mobile
:
r2m> gen -d GoogleDistance -f
(Only on 1.1.0+) Ignore invalid values with -j IGNORE
. In the example below, the generator will exclude the properties a, b, c
, and only declare d
in the generated object model FooResult
.
cat << EOF > exampleWithInvalidValues.txt
+name foo
+request
GET http://foo.com/some/path
+response
+body
{ "a": null,
"b": [],
"c": {},
"d": 123
}
EOF
r2m gen -e exampleWithInvalidValues.txt -j IGNORE -f
You can also build your own Mobile API from existing REST examples or documentation. Find out how to create your own example from the REST example wiki page.
Examples are usually text files containing the copy-pasted URL request and response payloads from a REST documentation, curl invocation, or simply your browser. Let's say you want to create a controller using the Google Time Zone API, simple type this in on your browser:
Then you get this JSON response:
{
"dstOffset" : 0,
"rawOffset" : -28800,
"status" : "OK",
"timeZoneId" : "America/Los_Angeles",
"timeZoneName" : "Pacific Standard Time"
}
Now copy-paste request and response in the file example.txt
:
+Name getTimeZone
+Request
https://maps.googleapis.com/maps/api/timezone/json?location=39.6034810,-119.6822510×tamp=1331161200&sensor=true
+Response
+Body
{
"dstOffset" : 0,
"rawOffset" : -28800,
"status" : "OK",
"timeZoneId" : "America/Los_Angeles",
"timeZoneName" : "Pacific Standard Time"
}
With this example file, you can now generate an async Mobile API with a strongly-typed object model for Android, Javascript and iOS
Using the file created above, run r2m
to generate the mobile code.
r2m> gen -e example.txt
This generates the Mobile API for all platforms under the local mobile/
directory. You can customize the location of the output with -o
as well as select one ore more target platforms, for instance android
, with:
r2m> gen -e example.text -o myproject/myapp/src/main/java android
First, install the rest2mobile Android SDK by modifying your app's build.gradle, as described in Step 3 of using the android studio plugin. If you are using ant, go to setup ant project
Then call the method in mobile/android/com/magnet/controller/api/RestController.java
:
Call<TimeZoneResult> getTimeZone(
String location,
String timestamp,
String sensor,
StateChangedListener listener
);
For example, with:
MagnetMobileClient client = MagnetMobileClient.getInstance(this.getApplicationContext());
RestControllerFactory factory = new RestControllerFactory(client);
RestController controller = factory.obtainInstance();
Call<TimeZoneResult> resp = controller.getTimeZone("39.6034810,-119.6822510", "1331161200", "true", null);
TimeZoneResult result = resp.get();
resp.dispose(true);
// assert result.getStatus().equals("OK");
// assert result.getTimeZoneId().equals("America/Los_Angeles");
// assert result.getTimeZoneName().equals("Pacific Standard Time");
// assert result.getDstOffSet() == 0;
// assert result.getRawOffset() == -28800;
First, install the rest2mobile iOS SDK
Then call the method in RestController.h
-(MMCall *)getTimeZone:(NSString *)location
timestamp:(NSString *)timestamp
sensor:(NSString *)sensor
success:(void (^)(TimeZoneResult *response))success
failure:(void (^)(NSError *error))failure;
For example, with:
// Create an instance
RestController *controller = [[RestController alloc] init];
// Call the controller
[controller getTimeZone:@"39.6034810,-119.6822510"
timestamp:@"1331161200"
sensor:@"true"
success:^(TimeZoneResult *response) {
// NSLog(@"time zone name is %@", response.timeZoneName);
}
failure:^(NSError *error) {
// NSLog(@"error is %@", error);
}];
First set up your Phonegap or NodeJS app following the instructions for the rest2mobile JS SDK
Then call the generated function in RestController.js
MagnetJS.Controllers.RestController.prototype.getTimeZone = function(data, options){
return MagnetJS.Method.call(this, data, options, {
params : {
name : 'getTimeZone',
path : '/maps/api/timezone/json',
baseUrl : 'https://maps.googleapis.com',
method : 'GET',
produces : ['application/json'],
returnType : 'TimeZoneResult'
},
schema : {
"location" : {
style : 'QUERY',
type : 'string',
optional : true
},
"timestamp" : {
style : 'QUERY',
type : 'string',
optional : true
},
"sensor" : {
style : 'QUERY',
type : 'string',
optional : true
}
}
});
};
Here's how you can call it:
var controller = new MagnetJS.Controllers.RestController();
var requestData = {
location : "39.6034810,-119.6822510", timestamp : "1331161200", sensor : "true",
}
controller.getTimeZone(requestData, {
success : function(responseData, details){
// do something with response data
},
error : function(error, details){
// handle errors
}
});
We are constantly adding features and welcome your feedback. Please, ask questions or report issues here
Licensed under the [Apache License, Version 2.0] license (the "License"); you may not use this software except in compliance with the License.
Copyright © 2014 Magnet Systems, Inc. All rights reserved.