Walkthrough: Creating a Virtual Service with Ready! API

Once your API is defined, client developers want to start using it. What if you’re not done coding it though? How can you test it and give your consumers the ability to start work on their apps before the endpoint is up and running? How often do you find yourself trying to launch a REST API under tight deadlines? How can you find bugs in your client code by running automated builds as a part of your Continuous Integration (CI) process without having your API up and running at all times? These can be challenging questions — ones that must be answered if you’re going to deliver a high quality API with top notch client SDKs.

Developers have been expressing a desire for better tooling support that helps them with these problems. SmartBear has been listening, and has recently launched a new product called Ready! API. It is designed to help you solve these problems quickly and easily. Largely an evolution of their existing product, SOAP UI, this new tool includes a simpler interface and tool chain.

Although Ready! API has lots of cool, new features, in this this step-by-step tutorial, we will focus on one called ServiceV. This feature allows you to create new virtual services or so called “Virt.” With it, you can mock the endpoint of a REST API. By doing so, you can start developing applications before the actual endpoint is up and running. This can potentially reduce the time between an API being released and an API being used. You can also launch it from a CI server to ensure that integration test cases continually pass. With this feature, SmartBear has made it a lot easier to test APIs.

To see this for yourself first hand, follow this walkthrough to learn how to:

  • Combine Ready! API’s ServiceV with the more commonly known SOAP UI Pro
  • Setup a virtual service to mock a REST API
  • Setup a REST client to mock calls to the REST API

Creating a New Virtual Services

Start with a New Virtual Service Project

The first thing you need to do is create the Virt project. To do this in Ready! API, follow these steps:

  1. Go to the Service V tab and select New project from the File menu.
    Step1.1
    This will open the New Project dialog.

  2. In this dialog, select Create empty project and click OK.
    Step1.2

This will create a new project in ServiceV [Projects]
. Now that you have a project, let’s add a virtual API to it!

Adding a New Virt

With the new project in hand, you can now add a virtual service to it. This will be used by the client later on. To add a Virt, do the following:

  1. Right-click on ServiceV [Projects] and select New Virt.
    Step2.1

  2. On the left hand side of the New Virt dialog box, choose Empty REST as the type of Virt you’d like to create. Then, give it a name (I named mine RESTMock), and click OK.
    Step2.2

Now you have a project and a virtual service. Not hard, but also not too useful yet. Let’s put it to work by creating some actions to simulate the behavior of our fictitious API.

Emulating Behavior with VirtActions

We now we have a project and a virtual service that does nothing. The next step is to add a virtual action. To do this, follow these steps:

  1. Right-click on the name you gave to your Virt, and select Add new VirtAction from the context menu.
    Step3.1
    This will bring up the Add new virt action dialog box.

  2. In this window, select the Method and type in a Resource path (i.e., the URI of your virtual API). For the sake of this walkthrough, select GET as the HTTP method and Login as Resource path.
    Step3.2

  3. Ready! API has different ways of simulating the behavior. In this walkthrough, we’ll demonstrate the use of a script to simulate mock behavior. To do this, change the Dispatch Style from SEQUENCE to SCRIPT in the resulting VirtAction that you created in the previous step.
    Step4.1

  4. Now, you need to define the outgoing response. To do this, press the + button under the Outgoing column. Add the responses that you’d like to simulate. For this tutorial, add LoginOK and LoginFAIL outputs. (You can name them with or without spaces, but it’s important that the name describes the different response types that will be returned.)
    Step4.2

  5. Define the response by selecting each output. Do this, for example, by selecting LoginOK. In this Edit area, verify that the HTTP Status Code is 200 - OK. Then, change Content | Media type to application/json. 
Add the following snippet of JSON as the result that will be returned for the LoginOK case:

{
    "access_token" : "1/fFAGRNJru1FTz708zhT3Zg"
    "expires_in" : 3920,
    "token_type" : "Bearer"
}

If you’re following along, you should now have something that looks like this:
Step5.1

Do the same for the LoginFAIL
, but change the HTTP Status Code to 400 – Bad Request. 
Step5.2

We can potentially add more things here like a redirect URL.
 You may also want to add an error message, so you’re client knows what went wrong. Experiment. Keep following along with this guide, but play around too!

Now that you’ve defined the VirtAction, you’re almost done. Just a little bit of coding, and you’re all set.

Coding and Returning Information

Now that we have defined outputs for our two simulated actions, LoginOK and LoginFail, we need to add some logic for deciding which of the two responses to send back in different scenarios. To do this, follow these steps:

  1. 
Firstly, we need to get the request parameters. I have copied the first few rows of code from another example that SmartBear has provided. 
This code picks up the request query string and splits it into an array of variables.
    def queryString = mockRequest.getRequest().getQueryString();
   
    String[] fields = queryString.split("&");
    String[] kv;
   
    HashMap params = new HashMap();

    for (int i = 0; i < fields.length; ++i){
        kv = fields[i].split("=");
        if (2 == kv.length)
         params.put(kv[0], kv[1]);
    }


If we have an parameter called scope, for example, we can simply say params.get("scope"), and we will get the value of that parameter. It's a nice and clean way to solve the problem. There might be other ways to do this as well, so feel free to experiment :-)

2. The next step is to define and populate all the variables. The result will then be validated. We will return the output of our different VirtActions depending on whether the result was successfully validated or not. There is an error in the code which I left in there intentionally; I'll covered this in next step, so stick with me.
    def response_type = params.get("response_type");
    def client_id = params.get("client_id");
    def scope = params.get("scope");

    if (response_type == "code") && client_id == "812741506391"  &&
       (scope == "admin scope" || scope == "admin%20scope")){
        return "LoginOK"
    }

    return "LoginFAIL"

If you run the code above, you'll get the following error when you call the virtual service:

Step6.3a

In the Transaction Log of the Virt, you'll see this error: Dispatch error; Missing response
. Step6.3b The error was an extra ) character in the code. 
How can we validate the code and get debug messages about the code? 
It's quite easy actually. Let me show you:

Step6.4

In the image above, you see I outlined three important areas of the UI: the green arrow button, the error in the code, and the error message received after pressing the green arrow button. These three together will allow you to debug your virtual service with relative ease.

3. To fix the error (if you have not done it already), remove the extra ) character.

4. Start your server by pressing the Green arrow (run server).
Step6.6

NOTE You might need to configure your Virt to use another port than the default. You can change the port by selecting the service's name (e.g., RESTMock) in the explorer. This will give you an option to define the port and default path. Step6.6a

Hosting the Mock API

You've created a virtual service, added some behavior, and even written a little code to dispatch to the different responses that should be output under different circumstances. This is really helpful -- once you host it somewhere. You need to run the Virt on some address, port, etc. To create a host for the make-believe API, do the following:

  1. Navigate to the Projects tab in the upper left corner.
    Step7.1
  2. Right-click your Virt, and select New REST Services from URI.
    Step7.2
  3. Add a URI where you want to run the virtual endpoint. In my case, I used localhost and port 8081. My full URI was https://localhost:8081/login.
    Step7.3
  4. Go to the Request tab. This is where we define the parameters for our REST service.
    Step7.4
  5. Press the + button, and add your request parameters. You can see in the screenshot above that I added two and a default value as well.
    Step7.5

Now our service is up and running! Great job!

Test the Mock API

Lastly, we just need a client to test our virtual API. Of course, you'll probably write these yourself from scratch, as that's the point of mocking the service. Before getting to that though, it's helpful to ensure that the Virt is working as expected. To do this, switch to the Soap UI NG PRO tab and follow these steps:

  1. Right-click and select New TestSuite.
    Step8.1
  2. Type in a suitable name for this test suite (e.g., Oauth2).
    Step8.2
  3. Right-click the test suite, and press New TestCase. Type in a suitable name for the test (e.g., TestCase).
    Step8.3
    Step8.4

  4. Right-click the test case, and select Add Step, and then REST Test Request.
    Step8.5

  5. In the New TestStep dialog, add Login Success.
    Step8.6
  6. Then, select the REST method called Login.
    Step8.7
  7. Finally, add the parameter values, and press the green arrow to run the test.
    Step8.8

Congratulations you've done it!

Conclusion

In this walkthrough, you have:

  • Created a virtual service
  • Started the virtual service
  • Handled errors in your virtual service's code
  • Scripted both an error and success outputs
  • Created a REST client to test your Virt

That's pretty good. With the basics down, you can now setup all sorts of test services. This API-centric approach to Test Drive Development (TDD) will make your development process more agile and decouple your client and service developers. It will also help you ensure that your APIs are of the highest quality.

If you get stuck going through this guide or have feedback, leave a comment below or tweet to us on Twitter.

[Editor's note: Nordic APIs is an independent publication. Unlike most of our posts, however, this one was sponsored by SmartBear, the makers of Ready! API and SOAP UI.]