The World's Smallest Micro Service


Only 276 characters, fits within a single tweet - and you can try this in 2 minutes !


* def id = 0
* def m = {}

Scenario: methodIs('post')
* def c = request
* def id = ~~(id + 1)
* set = id
* eval m[id + ''] = c
* def response = c

Scenario: pathMatches('/cats/{id}')
* def response = m[]

* def response = $m.*

Maybe you have heard of Karate - the web-API test-automation framework and your teams may be even using it already.

But did you know that Karate can act as an HTTP server? I recently realized that not many people know about this yet, so I'd like to spread the word a little more.

The biggest challenge when you write any service is how to manage state. Most API mocking solutions expect you to either record and re-play traffic - which breaks down when you have highly dynamic responses. Or they expect you to think in terms of "state-transitions" which typically results in you having to write this large JSON blob that models all the "states" in your mock. And you somehow need to tell your mock to be in some particular "state" when you run your tests.

Karate takes a very different approach to API mocking compared to other solutions. You just maintain state as JSON objects assigned to variables. Karate has syntax that makes it super-easy to work with the incoming HTTP request, mutate JSON, run JsonPath "queries" and shape the response. And one thing that sets Karate apart is its first-class support for XML.

For more on this, please refer to the documentation. It contains instructions to actually run this service locally and test it using a web-browser - and it will only take 2 minutes. All you need is a Java Runtime Environment.

unsplash-logoPhoto by Thao Le Hoang

Thanks for reading! If you use Karate DSL you can add them to your stack here.

Peter Thomas
Tools mentioned in article