DEV Community

Nabil Kazi
Nabil Kazi

Posted on • Updated on • Originally published at instamobile.io

Mocking APIs while Development using Mockoon

This article was originally shared on InstaMobile

Are you a mobile app developer? Do you work in a team along with Web developers? Does your app depend on APIs provided by the Web team? Have you ever faced issues with the unavailability of APIs to develop or test a certain feature in your app? If your answer to all the above questions was yes, then this article is for you.

Hello everyone, It’s been a while since I wrote my last article where I talked about easing off your App distribution process via Firebase App Distribution. You can find it here.

Now let’s move to the topic which we would be discussing in this article. I would be touching in on a topic or rather we can call it as a difficulty which almost every mobile app developer regardless of the domain, be it Android, iOS or Hybrid faces when working with APIs. Let’s break this article into the 3 parts –

  1. The Problem
  2. The Solution
  3. The Solution - Demonstrated

So let’s begin…

The Problem

While working in a fast-paced environment where everyone is rushing towards completing their tasks & features, we often encounter a dependency on web teams for providing us with APIs. It can be a certain feature like login or getting a list of items from the web to display them in List View or post something on the web, it can be anything.

Let’s take an example of building a List-View which is powered by content from API. To implement List-Views, Recycler Views or Table Views, we need data to simulate and test our development. If the APIs are not ready by that time, we end up creating mock functions which returns an array and pass that as a data source to our views. While this may help you test your flow or views, below are some downsides of this approach –

  • Unnecessary Code – Adds unnecessary code which we would have to clean up when connecting to actual APIs.
  • Incomplete Code – We don’t write our actual Networking code: the API methods & functions that would be fetching us the data and hence a lot of code remains to be actually written when we are to connect with the actual APIs.
  • Incomplete features – Since your features depend on the API and you just mocked it in your code to test, your actual feature implementation is incomplete and you would have to come back at a later stage to pick up where you left and start developing the remaining part again.
  • 2x Lost Effort – Both the Android and iOS teams would have to do this in their respective codebases and hence when you look from a Lead’s perspective, the time lost is actually 2x.

The Solution

What if..? What If..? What If I told you there is a way to avoid all the above. A way wherein you can write all your networking code – the actual production level networking code in the app. A way wherein you can write your exact functions to fetch you the data from API. Write your entire API Models, DB Models exactly the way it should have been written. A way where you don’t have to write mock functions to get you the data.

Yes! You heard it right, you can mock the APIs and this would not be in your app’s code-base. We would be utilising a 3rd party tool to create these APIs and provide us with the data and we would be doing it only once and the same can be accessed by both our Android and iOS teams.

Now there are a lot of Mock API service providers, some are paid, some are free, maximum is online while some are offline apps. To name a few – Mockoon, Postman, Swagger, TestAPI, Mocky etc.

I wouldn’t be comparing these services in this article, that would have to be a separate article in itself & I would like to know if you, the readers would be interested in that. For now, I’ll just use what I have been using for a while and really like – Mockoon. I’ll go ahead and demonstrate how easy it is to set up, create Endpoints, enter your response and start using them in your app.

The Solution - Demonstrated

The tool I would be using to demonstrate building your API and connecting it with your app is Mockoon. It is a free app available for all the platforms – Mac, Linux and Windows with unlimited Mocking. Also yes it ain’t an online web app so your data and API structure remains to yourself. That’s great right?

So let’s begin by installing Mockoon from https://mockoon.com/

Open the app and start creating your first mock API. I’ll be creating a sample Login API wherein I’ll set up both success and failure response for our login flow.

Creating your first Mock API :

https://user-images.githubusercontent.com/13706140/72914194-53ca1d00-3d64-11ea-9117-853c3e7951ce.png

  1. Add your Environment

    Your Environment is your single Project. So if you are working on 2 different apps/projects, you would be creating a separate environment for that other project.

    In short : 1 Environment = 1 Project

  2. Add your Environment route

    This is that part of URL which goes after your base URL and before your API Endpoint. Example: https://www.sampleapp.com/api/v1/loginThe api/v1 would be your environment route over here. You can add a custom route to your base URL to keep your mock API structure as close to your actual API URLs. I usually keep it similar to our backend route structure so when I actually have to replace my mockoon API endpoint with our actual APIs, I just have to update the host URL.

  3. Add your API route

    This is your actual API Endpoint. Examples of this would be /login, /movies etc. Over here I would be creating an API endpoint named — login

  4. Set your API method

    This would be your API method — GET, POST, PUT, DELETE.

  5. Add your header

    You can add custom headers for your API. The most common is setting the content type for the response. It can easily be set by clicking on Headers -> Add Header -> Add Header Name (Eg. Content-Type) -> Set Value (Eg. application/json)

  6. Add your response

    Type your response JSON here that you would want to return from the API. I am returning a sample Login Success Response with a User object and Access Token. This can also be an array of JSON objects if the API is, for example, GET/Movies.

  7. Start Mockoon server to access your API

    All that remains is to start your server and start hitting the APIs and accessing the response. To quickly test if my API works and returns the intended response, I'll change the API method from POST to GET and try accessing it from the browser.
    A05I02
    VOILA! It worked!

    Now I’ll change it back to POST to connect this with my App and start working.

Note: For this API to be accessible from your mobile app while developing/testing, your Mockoon server and your mobile should be connected to the same network. I had connected both my Macbook and iPhone to the same WiFi network to make this work.

But wait! What about testing your error workflow? How can you test your error conditions and validate your UIs for certain workflows when your API fails? What happens when your Login fails? What happens when your GET API returns an empty array? You definitely would have to handle those scenarios in-app and there would be appropriate UIs & functionalities developed to handle the same. Thanks to Mockoon’s latest update (v1.5.0 at the time of writing this article) we can now add rules to API routes and return different responses for the same API endpoint. How cool is that??

Setting Rules in your API :

Let's add a rule to this same API wherein if I send password = demo in my POST request, it will return an HTTPS Status - 401 (Unauthorized Access) response.

Although it would have been better had Mockoon provided an option to change the operator in Rule from “=” to “!=” or “>” or “<”. That would have added more power to rules and also made it more closer to actual scenarios. I could have set my success response only if username=demo & password=demo else return 401-Unauthorized Access. But for now lets go ahead with the flow, hope this feature would be available in the future releases.

I would be sending the below POST request to the same /login API -

{
    "username" : "nabil",
    "password" : "demo"
}

Lets go through the steps to setup the trigger rules and vary responses based on the same -

https://user-images.githubusercontent.com/13706140/72914806-45303580-3d65-11ea-9ad3-ef40a3899b5e.png

  1. Click on Add Response
  2. Add your Rule
    This the place where you would be actually adding your Rule. I won’t go into much detail about the possibilities here. Mockoon’s official feature page does a wonderful job of explaining that in depth. You can find it here
    Here I am adding a Rule to check if the value of API request parameter “password” is set as “demo”. Basically, we are setting the Trigger Condition here. The Action would be set up in the subsequent steps.

    https://user-images.githubusercontent.com/13706140/72915072-bbcd3300-3d65-11ea-94bf-f9634a30c375.png

  3. Update the response HTTP status code
    This is the first part of setting the Action to our Rule i.e If the above rule is met, what should be the Status code of API Response?
    You can change the HTTP status code of the response and test them accordingly in your app. Over here I would be keeping it to 401 for invalid password rule to return an Unauthorized Access error in the API.

  4. Add JSON response
    This is the second part of setting the Action to our Rule i.e If the above rule is met, what should be the Body of API Response? This is optional, but would be extremely helpful for setting up HTTP Status 200 Success responses like an empty list, returning different API objects based on certain criteria, etc.

Now test these Conditions and Rules by varying your Request parameters from your app and see the magic happen!

Final Notes…

I have barely scratched the surface here. You can do a lot with Dynamic Variables, Templating, Latency, HTTPS, CORS etc with Mockoon. You can find a list of all its features here - https://mockoon.com/features/

Also, Guillaume has done a great job by providing a series of tutorials for you to learn these features and easily get started with them. You can access them here - https://mockoon.com/tutorials/

I am certain this article would have given you a fair idea of mocking your own APIs and a realization that there is no need to depend on web APIs anymore to develop and test our API dependent functionalities.

Tip: In cross-domain teams, it is always advisable to decide on an API structure with the Web team before even developing your Mock APIs. This can be done by aligning yourself with the web team on the API structure, finalizing the basics and then start Mocking them. This can be a small task before the actual development but would save a huge amount of rework in the code at a later stage. Trust me on this one!

If you enjoyed reading this article and learned something, share it amongst your developer friends/colleagues and spread the love! If you have anything to discuss regarding Mocking APIs or any other topic related to Mobile Apps, Development, Designing, Engineering… Drop a comment below or DM me on Twitter :)

If you find this interesting, chances are you’ll find my twitter feed too! I keep sharing articles and stuff related to development, design and productivity on a daily basis. So hop on, follow me on Twitter and enjoy the learning ride!

Till the next Article…

Latest comments (1)

Collapse
 
its_junaid715 profile image
Junaid Khan

Super amazing :-)