This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 15k traffic Daily!!!

Mock REST APIs with Mockatron




Why Mock APIs?

As a cell / front-end developer, have you ever ever been blocked because of a dependency on a back-end API that’s not available for consumption? This situation may be very frequent in quick paced improvement groups the place a number of front-end and back-end groups work in parallel while striving to resolve dependencies with each other.



What’s Mockatron

I’m constructing Mockatron – a easy instrument that helps front-end / cell builders setup a fast Mock HTTP API Server with out having to put in writing any back-end code. The purpose is to assist parallelize improvement efforts of groups so that after the precise APIs can be found, customers can merely swap to the unique implementation with out having to make a complete lot of adjustments.

By defining a easy set of configuration guidelines, you’ll be able to rise up a mock HTTP server that may return static in addition to dynamic response knowledge.

  • Configure API Routes by defining constraints
  • JSON fashion configuration for requests and responses
  • Handlebars fashion templating to help era of responses from templates. Help for static responses are additionally obtainable.
  • Allow proxy help to mock solely particular routes and redirect others to your precise back-end server.



Instance

Allow us to assume that we’re going to construct a cell / internet utility like Amazon that can record merchandise from a back-end API. Our purpose is to make use of Mockatron and setup a mock API server that can return mock merchandise every time a name to /api/merchandise is named from the front-end / cell app.



Set up Mockatron

Pre-requisities:

Just be sure you have Node and npm put in.

$ npm set up -g mockatron



Setup your mock definitions

Create an empty folder for us to configure our mock server. Give it an arbitrary identify (e.g merchandise).

Contained in the merchandise folder, create a configuration folder named config. We will probably be configuring our mock finish factors and constraints (extra on this later) on this folder.

Contained in the config folder, create a major.json file. Right here is my folder construction that I’ve created

merchandise
└── config
    ├── major.json
Enter fullscreen mode

Exit fullscreen mode

Allow us to begin by writing a easy config in our major.json file.

{
     "contextPath": "/api", 
     "routes": [ 
         { 
             "path": "/products", 
             "method": "GET", 
             "responses": [ 
                 { 
                     "body": "'no results found'", 
                     "statusCode": 200 
                 } 
             ] 
         } 
     ] 
}
Enter fullscreen mode

Exit fullscreen mode

The above configuration must be simple. The contextPath key specifies the place the outlined routes will probably be mounted whereas operating our mock server. For e.g if we’re internet hosting our mock server at localhost:8080, http://localhost:8080/api/merchandise would match the /merchandise route that we’ve got outlined above.

The responses array specifies the totally different response our bodies that this route can doubtlessly return. On this case, we’re going to return a easy string physique with a standing code of 200.



Generate a mock server

Now that we’ve got setup our configuration, go forward and run the beneath command contained in the merchandise listing.

$ mockatron --config config --out output
Enter fullscreen mode

Exit fullscreen mode

If every part went effectively with out errors, an output listing will probably be created within the specified path.



Run the mock server

  1. cd into the output path
  2. $ npm i – This can set up all dependencies for the mock server
  3. $ npm begin – This can run a mock server on port 8080

Ideally, it is best to see the next messages in stdout

> mockatron_server@1.0.0 begin
> node index.js

Began utility on port 8080

Enter fullscreen mode

Exit fullscreen mode

Open a tab in your browser or ship a curl request to http://localhost:8080/api/merchandise and it is best to get no outcomes discovered because the response with a standing code of 200.

And that is it! Now we have a mock API server up and operating in lower than 10 traces of code.



Dynamic responses

The above config returns the identical static textual content each time we hit /api/merchandise. Nevertheless, more often than not whereas constructing a front-end or cell app, we would want to generate variability in our responses to simulate an actual world situation. To realize this return to the configuration folder and create one other file named merchandise.json

merchandise
└── config
    ├── major.json
    ├── merchandise.json
Enter fullscreen mode

Exit fullscreen mode

Contained in the merchandise.json file, we’ll attempt to create a template for our response.

{
    "productList": [
            {{#array 5 20}}
            {
                "price": "{{float 50.0 5000.0}}",
                "rating": {{int 1 5}},
                "id": {{@index}},
                "sku": "{{uuid}}",
                "name": "{{word 2}}"
            }
            {{/array}}
    ]
}
Enter fullscreen mode

Exit fullscreen mode

We are going to use the productList object to return an array of merchandise primarily based on the template that we’ve got outlined above.

The #array helper generates a random variety of objects (between 5 & 20) that it encompasses. The array is closed out with the {{/array}} tag.

Every object within the array can once more be randomized. The float and int helpers take min and max arguments and generate a random quantity in between. Equally there are helpers for producing a random uuid, random textual content utilizing the phrase helper and so forth. A whole record of response helpers could be discovered here.

To hook up the productList definition array to our /api/merchandise route, head again to our major.json file and modify the present config like so.

{
     "contextPath": "/api", 
     "routes": [ 
         { 
             "path": "/products", 
             "method": "GET", 
             "responses": [ 
                 { 
                     "body": "{{{def 'products' 'productList'}}}", 
                     "statusCode": 200 
                 } 
             ] 
         } 
     ] 
}
Enter fullscreen mode

Exit fullscreen mode

Now we have solely modified the physique to load the productList definition that we outlined within the merchandise.json file as a substitute of static textual content. For this, we use the {{{def <json-file-name> <definition>.

Now, lets rebuild our mock server. Return to the foundation folder (the merchandise listing) and run the next command

$ mockatron --config config --out output

$ cd output

$ npm i && npm begin
Enter fullscreen mode

Exit fullscreen mode

Now open a browser and take a look at hitting http://localhost:8080/api/merchandise a number of occasions. You will note that you just get a special response every time!

Mockatron rendering dynamic responses



Including Constraints to Routes

Now that we’re capable of generate dynamic response knowledge, allow us to have a look at including constraints that decide when the response must be generated.

Constraints are synonymous to if (situation) then return response in Mockatron. Consider a constraint as logical blocks that we’ll put inside an if block.

Constraints could be added to every component of the responses key inside a route.

For example, assume that the merchandise API that we’re constructing mandates a search question parameter within the URL and we should always return a response provided that the search question parameter will not be null.

Let’s head again to our major.json file and add the above rule as a constraint.

{
  "contextPath": "/api",
  "routes": [
    {
      "path": "/products",
      "method": "GET",
      "responses": [
        {
          "constraint": "{{neq (query 'search') undefined}}",
          "body": "{{{def 'products' 'productList'}}}",
          "statusCode": 200
        },
        {
          "body": "'No Results found'",
          "statusCode": 200
        }
      ]
    }
  ]
}
Enter fullscreen mode

Exit fullscreen mode

We see that the responses array now incorporates 2 components. The primary component incorporates a constraint key that evaluates if the incoming request’s question parameter – search !== undefined. Provided that this situation is happy, will the physique get executed.

In any other case, Mockatron will fall again to the subsequent object within the responses array which principally returns a static string like earlier than.

Keep in mind: Contents within the responses array are evaluated within the order through which they’re listed within the configuration

Mockatron response with constraints

A full record of Mockatron constraint helpers can be found here .



Nesting Constraints

We will nest a number of constraints right into a single constraint. For e.g what if we need to return the response provided that the search question param will not be null and the worth param > 0?

Modify the constraint part like so.

"constraint": "{{and 
                    (neq (question 'search') undefined)
                    (gt (question 'value') 0) 
               }}",
Enter fullscreen mode

Exit fullscreen mode



Static Response Information

Typically we could not need to cope with templating or needing dynamic response knowledge for all our routes and a easy plain JSON object could be adequate. To return static JSON content material as response, use the {{file <json_file_name>}} helper as a substitute of the {{def}} helper that we had been utilizing until now.

Let’s assume that we add a brand new route known as /static-product to our record of routes. In major.json, lets add the next configuration to the present routes array.

{
  "path": "/static-product",
  "methodology": "GET",
  "responses": [
     {
       "statusCode": 200,
       "body": "{{file 'static-products'}}"
     }
   ]
}
Enter fullscreen mode

Exit fullscreen mode

All you want is a legitimate JSON response outlined in a file named static-products.json within the config folder alongside the major.json file.



What’s subsequent

Strive including a number of routes, responses and constraints and see what works for you. If you wish to report a bug / talk about a brand new characteristic request, attain out to me / elevate a problem in Github.

Within the subsequent submit, I’ll speak about configuring proxy help in Mockatron. This may very well be actually highly effective if you wish to use Mockatron as a proxy server that can mock solely particular routes whereas proxying different requests to your precise back-end APIs. Keep tuned!

The Article was Inspired from tech community site.
Contact us if this is inspired from your article and we will give you credit for it for serving the community.

This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 10k Tech related traffic daily !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?