TLDR; this article is not about building a fake API server, instead it is about mocking the API calls straight into the project you’re working on.
In software engineering, mocking means faking.
Why would you need to fake an API call?
Here’s a few scenarios you may have already came across:
- you are working on some code that calls an API which is not ready yet. You don’t want to get blocked by whoever is building it;
- you are building a prototype and you want to quickly demonstrate how your app works without having to build the whole system;
- interviews: yes — this is a quite common interview question.
API as a contract
In the end an API is just a contract.
The most you should care about it is:
- the signature: the format of the URL, the parameters and the headers it accepts
- the result, what sort of data you expect the API to return
So once you know what kind of data format you’re expecting from an API you can start building your app which will be calling the API mock and then you’ll be able to switch to the real one once that’s ready.
Let’s start mocking
Let’s say somewhere in your code you want to call
getBooks, an API that returns a list of books.
You can quickly come up with a mock just by defining
getBooks in this way
Leveraging the use of Promises to simulate the asynchronous behaviour of an API call.
Don’t know what a Promise is? Here’s a good article.
Let’s add some delay
Adding some delay is quite useful if you want to test how your app reacts on a loading state. For example you may want to test your form submit button shows a loading loading spinner while fetching the data.
In the snippet above we are using the
setTimeout built-in function which accepts two parameters: the function we want to execute and the delay we want to introduce (in milliseconds).
How to mock API errors?
So far we have mocked an API call that returns some data successfully, by using the
resolve callback exposed by
You may want to simulate the event of an error response like a 404 (Not found) or a 400 (Bad request).
Here’s how you can simulate an error:
Simple, quick and you don’t need to install any additional library as
setTimeout are built-in in the language.