WireMock : Mock your REST APIs


WireMock

                            As we are extensively working on “OmniChannel” applications with REST APIs approach, mocking the REST services is essential in our day to day development. As part of our development first, we are going to identify the REST APIs to expose and the request and response details. Once we finalize these details the backend development team used to create sample request/response (i.e XML/JSON response) for each API and the same can be consumed by the front end team and the native app development team. Till the backend development team provides the APIs the other teams use to hardcode the sample request and responses to complete the development. The “WireMock” provides an elegant way to mock the REST APIs. The below diagram depicts how “WireMock” fits in our development environment.

WireMock

                                   We can run WireMock  as “Standalone mode” or “deployed into servlet container”. In this article, we will see running WireMock as standalone mode. To setup, WireMock follows the below steps.

Step 1: Download the WireMock standalone jar from here.

Step 2: Run the standalone jar by giving below command.

java -jar wiremock-1.57-standalone.jar --verbose

There are several command line options available. You can find the same here. If you are not passing –port option by passing the port number, by default it will run on 8080.

After running the WireMock, you will see the below folder structure from where the WireMock standalone app is running.

WireMock_Folder_Structure

Now, if you send the request to http://localhost:8080/_admin, then you will empty mappings.

WireMock Mappings

Step 3: Now, we will create mapping files for GET and POST requests. Here I want to simulate GET product and CREATE product requests. Now we will see GET request and response mappings.

WireMock_GET_Request

Create product.json file under “mappings” folder depicted in step2. Make sure that the body content is properly formatted by keeping the content in a single line and the double quotes are escaped.

{
 "request":
 {
 "urlPattern": "/product/p0001",
 "method": "GET"
 },

 "response":
 {
 "status": 200,
 "headers":
 {
 "Content-Type" : "application/json"
 },
 "body": "{ \"_id\" : \"p0001\", \"product_display_name\" : \"Brother - MFC-J4320DW Wireless All-In-One Printer - Black/Gray\", \"category_ids\" : [ \"pcmcat247400050001\" ], \"is_active\" : true, \"on_sale\" : true, \"price\" : { \"list_price\" : 149.99, \"sale_price\" : 123.99 }, \"upc\" : \"012502637677\", \"mpn\" : \"MFC-J4320DW\", \"manufacturer\" : \"Brother\", \"product_short_description\" : \"4-in-1 functionalityBuilt-in wireless LAN (802.11b/g/n)Prints up to 20 ISO ppm in black, up to 18 ISO ppm in color (Print speeds vary with use. See mfg. for info on print speeds.)150-sheet tray2.7\\\"\" }"
 }
}

Step 4: Now, restart the WireMock and send the request to http://localhost:8080/product/p0001. You will get the product details JSON response.

WireMock GET Response

Step 5: We will see how to create POST request and response mapping.

WireMock POST Request

Place the mapping JSON file under “mappings” folder and restart the server.

The mapping JSON is given below.

{
 "request":
 {
 "urlPattern": "/createProduct",
 "method": "POST",
 "bodyPatterns" : [{
 "equalToJson" : "{ \"product_display_name\" : \"Brother - MFC-J4320DW Wireless All-In-One Printer - Black/Gray - New Product\", \"category_ids\" : [ \"pcmcat247400050001\" ], \"is_active\" : true, \"on_sale\" : true, \"price\" : { \"list_price\" : 149.99, \"sale_price\" : 123.99 }, \"upc\" : \"012502637677\", \"mpn\" : \"MFC-J4320DW\", \"manufacturer\" : \"Brother\", \"product_short_description\" : \"4-in-1 functionalityBuilt-in wireless LAN (802.11b/g/n)Prints up to 20 ISO ppm in black, up to 18 ISO ppm in color (Print speeds vary with use. See mfg. for info on print speeds.)150-sheet tray2.7\\\"\" }"
 }]
 },

 "response":
 {
 "status": 200,
 "headers":
 {
 "Content-Type" : "application/json"
 },
 "body": "{\"_id\" : \"p0002\", \"product_display_name\" : \"Brother - MFC-J4320DW Wireless All-In-One Printer - Black/Gray - New Product\", \"category_ids\" : [ \"pcmcat247400050001\" ], \"is_active\" : true, \"on_sale\" : true, \"price\" : { \"list_price\" : 149.99, \"sale_price\" : 123.99 }, \"upc\" : \"012502637677\", \"mpn\" : \"MFC-J4320DW\", \"manufacturer\" : \"Brother\", \"product_short_description\" : \"4-in-1 functionalityBuilt-in wireless LAN (802.11b/g/n)Prints up to 20 ISO ppm in black, up to 18 ISO ppm in color (Print speeds vary with use. See mfg. for info on print speeds.)150-sheet tray2.7\\\"\" }"
 }
}

Step 6: Send the POST request by using any request poster. Here I used “POSTMAN” and send the request by passing request body.

WireMock POST Response

By following the above steps you are equipped to mock the services and WireMock is handy to that. There are similar alternative tools to try.

Stay Hungry to learn!!!

Advertisement

Siva Janapati is an Architect with experience in building Cloud Native Microservices architectures, Reactive Systems, Large scale distributed systems, and Serverless Systems. Siva has hands-on in architecture, design, and implementation of scalable systems using Cloud, Java, Go lang, Apache Kafka, Apache Solr, Spring, Spring Boot, Lightbend reactive tech stack, APIGEE edge & on-premise and other open-source, proprietary technologies. Expertise working with and building RESTful, GraphQL APIs. He has successfully delivered multiple applications in retail, telco, and financial services domains. He manages the GitHub(https://github.com/2013techsmarts) where he put the source code of his work related to his blog posts.

Tagged with: ,
Posted in General
2 comments on “WireMock : Mock your REST APIs
  1. Ravi Anneboina says:

    Hi Prasad,

    This is Ravi, I also worked on the same steps as you explained. Now I want to use other supported wiremock fields, especially “basicAuth” or “basicAuthCredentials”.

    Could you please give the example on this with JSON configuartion and its relevant request ?

    Thanks,
    Ravi Anneboina.

    • Hi Ravi,

      Presently I don’t have setup to test it out with basicAuth. Here is the reference http://wiremock.org/docs/request-matching/ to setup basic auth in the request json with Wiremock. After that when you make request to that mock endpoint from any REST client you can send authorization header with basicAuth with the credentials you have given in Wiremock. If you are using postman, then you can set Authorization by selecting BasicAuth as type. Then whenever you make request from postman, it will send Authorization header along with request to Wiremock.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Dzone.com
DZone

DZone MVB

Java Code Geeks
Java Code Geeks
OpenSourceForYou
%d bloggers like this: