25 January 2016

Using a mock RESTful API with Android OkHttp and getSandbox

I recently stumbled across a really cool service called getSandbox.com. This is a API mocking service which can mimic RESTful or SOAP webservices. This is incredibly useful for knocking up quick testing tools or as an endpoint for unit tests.

This has huge advantages as it allows you to protect your server from unit test bombarding, however I'm more interested in just being able to use it just to quickly setup a few examples for prototyping. You can deploy it on your server or using their cloud, but they offer a free tier just for a low number of requests.

So I decided to setup a getsandbox account and use it with okHttp on Android to see if I can do some simple REST get and post requests.

First I created a new sandbox, I didn't have an Apiary account and this is a test API so I've no WSDL nor a RAML and I don’t know what Swagger is. So I picked blank. This is great, it gives you a temporary one hour sandbox with a few simple get and post methods.

  • GET/hello - Respond hello world
  • GET/users - Show all users
  • POST/users - Add new user

Sandbox even gives you some form of storage, so anything you add is persistent.

With my new endpoints I created a form (see below) to test the POST and in a browser hit the main url to get all users. Magic, everything is responding wonderfully. Sandbox is really that simple and easy to use! I'm super impressed.

Next we’re over to Android and I wanted to use OkHttp for this one. OkHttp is a neat little library that handles http requests for you and easily deals with any problems. Plus it can make synchronous and asynchronous calls with ease.

I created a new Android Studio project and added in the okhttp gradle compile:

compile 'com.squareup.okhttp3:okhttp:3.0.1'

Then I put INTERNET permissions in the manifest, a ListView in my activity view and started the java code. First I made my activity implement okhttp3.Callback, most tutorials will tell you to put the callback inside the method call, but personal preference, I like implements.
Here’s the simple OkHttp code:

OkHttpClient client = new OkHttpClient();
//Create a simple get request
Request request = new Request.Builder().url(sUrl).build();
//Execute with call back

You don’t get much simpler than that. The request is a fairly self evident GET request, nothing in the body and nothing fancy.
Next you have a choice,

client.newCall(...).execute or .enqueue.

Execute is a blocking synchronous call whilst enqueue is an asynchronous call. We’ll use enqueue as we can’t do a blocking call on the UI thread anyway.

So my Activity now overrides onFailure onResponse

public void onResponse(Call call, Response response) throws IOException {
  Log.i("http", "onResponse");

  int j = 0;
  String[] users = null;

  try {
     //Read string in as json array
     JSONArray jsonArray = new JSONArray(response.body().string());

     users = new String[jsonArray.length()];
     //add each element in array to string array
     for (int i = 0; i < jsonArray.length(); i++) {
        if(jsonArray.get(i) != null) {
           users[j] = jsonArray.get(i).toString();
  } catch (JSONException e) {

  if (users != null){
     //Create adapter of users
     mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, users);

     //listview needs to be updated on ui thread.
     runOnUiThread(new Runnable() {
        public void run() {

That's pretty much it. The code in onResponse isn't rocket science. We take the response from OkHttp and parse it as a json array. We can now loop through it and create a normal String array. We could do a bit more error checking here and clean some dodgy input, but for sake of speed that's your lot. The only slight oddity is having to set the listview using runOnUi because we can't change the UI elements outside of the UI thread. The again....now I think, I didn't really need to set that after the data did I? I could have done that in the Acivity onCreate....oh well, next time!

So look what we've done in just a few lines of code and a few clicks. We've done some web interaction without any need for asyncs or checking if we have a connection. Plus we've got a fantastic test API which responds quickly, updates instantly and is super easy to use.

Just in case you need to submit to a POST, here's my mega javascript form:

<!DOCTYPE html>
        <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {

                        url: "http://**myid**.getsandbox.com/users",
                            username: $('#username').val()
                        success: function(msg){

                    return false;

            <input type="text" name="username" id="username" value="" />
            <button name="go" id="submit">Submit</button>

No comments: