Creating meaningful API mocks — without re-writing the whole API
A Little Background
Recently, I was given the task of creating one of my company’s RESTful API specifications, along with providing a “sandbox” or API mocking service to our customers. One of the things that I wanted to accomplish in this project was to use some of the new tooling for Open API Specification 2.0 (formerly known as Swagger), since I had read that there were offerings that could automagically scaffold up mocking services based on the specification. Anything that saves me having to write code unnecessarily is a plus in my book, so I looked at a number of tools, including Apiary, Mulesoft, and Mashery. Most of the tools, however, were trying to be all-encompassing solutions that were frankly too feature-laden for my purposes.
I wasn’t willing to sell my soul to Oracle, Tibco, or Apigee by adopting their turnkey solutions, so I turned to a little company out of Austin TX called Stoplight.io. Stoplight is primarily a hosted solution (they have on-prem offerings too, but you have to ask…) that allows you to author RESTful API specifications in OAS, write and publish accompanying documentation, performed automated testing, and (drumroll…) stand up mocking services.
The vision that I had for my new API was that I could use Stoplight to author the OAS spec, hang some associated documentation around it using their “Hubs” CMS, and magically publish it out with a developer sandbox included. I didn’t want to stand up even a skeleton of my API for the sandbox if I didn’t have to since the objective was to be able to iterate the spec a lot prior to having the development team start coding the actual API.
Out of the Box — Almost There
The newest release of Stoplight has just recently dropped, and I jumped on it right away to see if it could achieve the above vision. And of course, it did! Almost. The specification authoring features — superb. The CMS — basic but definitely up to the level of documentation that I wanted to produce. The API mocking —close, but...
While I could create example responses for each HTTP response code (200, 404, 500 etc.) I had no way of returning example responses that were specific to the data that was being submitted to the API endpoint. This really became evident when I tried to produce multiple examples for a POST method’s error 400 response. You know, when you have half a dozen validations specified in your POST method, you would expect that the mocking service would be able to validate the body of the request, and select an appropriate example response if one of the validations failed. Well, out of the box Stoplight v3 didn’t have that feature. Not to worry though, TOM TO THE RESCUE!!
Tom’s the guy at Stoplight who wrote their mocking and testing engine called Prism. When I started whining about not being able to fulfil my deepest desires with Stoplight, Tom reached out to me, looked at what I wanted to achieve with the mocking features, and promptly wrote an update for Prism to support exactly what I wanted to do. All this took about two weeks, which is a testament to the level of commitment that this small company has towards its customers — something that is greatly lacking in the industry as a whole today IMHO. (Quick disclaimer, I’m not getting any special consideration from Stoplight for writing this. I’m just a customer, and a pretty small one at that.)
The Good Stuff — How to Do It
The rest of this post assumes that you have a Stoplight.io account, and you are using the most recent version (v3 or better). I have published a simple API spec on Stoplight to illustrate this mocking an API spec with meaningful responses. You can find it here:
Create Context-specific Response Examples
The first thing you need to do is to create an API spec that has an operation that would return contextual responses based on the request payload, such as a POST or a PUT method. Here’s the POST /todos method from my example:
If you take a look at that operation, you will see that there is a response created with an HTTP 400 response code. Since both “name” and “completed” are required per the schema, I want to mock back an error message that reflects the correct validation failure if either one of these is omitted.
So if you look at the response examples for the error 400 response in the spec, you will see not only the “application/json” standard example, but also a “name” example and a “completed” example. Each of these custom examples return information to the caller that is specific to each case.
Create Your Mocking Server
The next thing you need to do is to wire up a Prism instance to your specification. I suggest creating a new one in your project so that you have the original one that gets created with the project as a reference.
Note: There is currently a limitation on the length of the name of the prism instance due to sub-domain name length limits. To avoid trouble getting your spec connected to your Prism instance, try to keep the name of your Prism instance to 16 characters or less.
In the project files menu, click the plus sign next to the Servers heading. Create yourself a new server and name it accordingly. In my example, I created the instance called “meaningfulmock.prism”
Select the new server and add an API to it by clicking the + beside the APIs header. Name the API “main” (just a suggestion) and connect it to your main.oas2 file. We’ll be using main.oas2 to author a couple of test endpoints to demonstrate the mocking validation.
Then add a Rule to the server by clicking the + beside the Rules header. Name the new rule “mocker” (again, just a suggestion) by updating the “id” field, and add the “main” API to it by pulling down the drop-down in the “apis” field and selecting the item “main”.
Next, you‘re going to pull in the “secret sauce” from the Stoplight public support project. In your “mocker” rule, there are three phases that you can add items to — “before”, “after”, and “done”. Click the Add button in the “before” section, then click the drop-down of the leftmost field. From the list, select the “External URL” item. In the next field to the right, enter the following URL:
In the last field on that line, again pull down the drop-down list and select the item named “[Before Rule] Power Mock — b-mock”.
Then in the “after” phase, perform the same actions as above, except that the last item to choose is called “[After Rule] Power Mock — a-mock”
Save all your changes to the mock server by clicking the Save button at the top of the UI.
Wire Up the Spec to the Mock Server
Finally, you will need to connect the spec back to the server so that we can use the “Send A Test Request” functionality in the documentation hub.
Click the Home icon on your Prism instance. It will show a field labelled “Send Test Requests” with a URL below it. Copy this URL to your Clipboard, excluding the protocol (https://) portion. For my project, I would copy the following text to my clipboard:
Now select your main.oas2.yml file from the project’s file list and select Design mode. You should be looking at the main metadata page for your API. Find the field labelled “ api host” and paste the value from your clipboard.
Save your file, and you *should* be ready to go.
Try It Out
I think the best way to test your implementation is by trying it out on my example project first to get a feel for how the behaviour of the Stoplight mocking and validation works, then try the same actions on your project and see if you get the same behaviours.
On my project (again http://meaningful-mocking.docs.stoplight.io), find the operation for POST /todos, and click on the Send button in the Send a Test Request section at the bottom of the page. You should get back an HTTP 200 status with some sample data.
Now, click on the Body tab of the request. You will see two parameters in the body. Delete one of them and click Send again. You should see an HTTP 400 status with a parameter-specific error message.
Creating meaningful mocking features for your REST API can be a major PITA — especially if you have a lot of POSTs and PUTs (and PATCHes for those of that persuasion). It can almost be as involved to create mocking services for your API as it is to write the whole API in the first place.
Using Stoplight’s Prism mocking services along with properly crafted OAS API specifications allows you to stand up a rich developer sandbox environment without having to deploy a whole stubbed-out API. Additionally, once you have this setup completed, any changes to the API spec and its examples are immediately reflected properly in the developer sandbox.
Have fun out there!