DevBox: Mocking a Web API fast

I feel the need, the need for speed! Those Top Gun guys were right. To have your front end development stalled by a Web API that suddenly goes down (using a dependency that we don't own for example), or to simulate different response content from the Web API, without setting up a whole chain of test data in a system, can be really frustrating. Oh, maybe the Web API is under development, but the data contract is known and decided?

To be able to fake this communication has many benefits for frontend-developers creating new features or stomping out bugs.

How can we set up a fake Web API that we can control the output from, Top Gun-style!? This is the fastest way I found so far, maybe you guys know of a faster and more flexible way? In that case please let me know! Here we go ...

Firstly, setup a directory to play around in.

mkdir fakewebapiexample
cd fakewebapiexample

Next install these two packages globally using npm. (There is a yarn way to, check out the link at the end).

npm install -g yo
npm install -g generator-http-fake-backend

Then make sure you are inside the directory created earlier and run

yo http-fake-backend

Just follow the guide and answer the questions. These were my answers:

image.png

The example data we are going to use is from Statistics Sweden's Open API. Information about the API can be found here scb.se/en/About-us/about-the-website-and-te..

The endpoint we are going to fake is this one api.scb.se/OV0104/v1/doris/en/ssd, which returns a small amount of JSON-data. The data returned will be copied later to a local file. Shown here, is a sample request made with Postman.

image.png

OK. Time to setup the fake endpoint. Executing the command will result in a small guide asking questions about how the endpoint and routes should be setup. I'm gonna use a GET which returns "application/json" through a local file. There are more options, follow the link at the end to learn more.

yo http-fake-backend:endpoint

image.png

Before starting the fake-backend server, copy the JSON response from Postman into the generated file /response-files/ssdexample.json. Then...

npm run start:dev

The server will start, and you can now do your frontend-development offline if you want! This only took a couple of minutes! Is there a faster way? :)

image.png

For more information checkout the project on GitHub github.com/micromata/http-fake-backend

Enjoy!