DEV Community

Cover image for Quickly and easily mock a REST API with Restapify
johannchopin
johannchopin

Posted on • Updated on

Quickly and easily mock a REST API with Restapify

Hey devs 👋

Often when you start developing a new frontend project that consume a REST API, the backend is not yet ready. However, very often this one is at first basic and you only want to receive faked data to see how the application behaves. That's when you decide to use a tool to mock your API like postman or library like json-server, mocker-api or http-fake-backend. These tools are really good but there still have some negative points. Postman for example is not entirely free to use and needs to login, mocker-api define all routes in a single javascript file and json-server is at some point very restrictive for edge-cases.

So I decided to work on a new API mocker tool that should be able to handle all cases and that within a nice developer experience flow: Restapify.

Restapify is a nodejs based CLI that allows you to quickly and easily deploy a local REST API by using an intuitive and developer friendly JSON file structure like you will see in NextJS or Sapper. Lets describe how it works by creating a simple mocked API that should serve the following:

GET  /me
GET  /posts
GET  /users
GET  /users/:userid
POST /users/:userid
DEL  /users/:userid
GET  /users/:userid/comments
Enter fullscreen mode Exit fullscreen mode

Create the endpoints

The starting point is the creation of the folder that will contain your route json file, I will call it /api. Then we can add some routes to be served. Creating a route means to add a .json file where its filename describe the endpoint, the method and the status code and its content the response body. So to create the GET /me endpoint with the status code 200 just create the following file:

📂 api
┣ 📜 me.GET.200.json
Enter fullscreen mode Exit fullscreen mode

Since GET and 200 are the default value for the method and the status code, you can simplify the filename to:

📂 api
┣ 📜 me.json
Enter fullscreen mode Exit fullscreen mode

The response should contain a firstname, a lastname and an email, so the file content of /api/me.json would be something like:

{
  "firstname": "Janie",
  "lastname": "Hermann",
  "email": "Jo.Kessler@yahoo.com"
}
Enter fullscreen mode Exit fullscreen mode

Then lets add the endpoints for /users. Since there are a few of them we can group them in the same folder users

📂 api
┣ 📂 users
┃ ┗ 📜 _.json
┃ ┣ 📂 [userid]
┃ ┃ ┗ 📜 _.json
┃ ┃ ┗ 📜 _.POST.201.json
┃ ┃ ┗ 📜 _.DELETE.201.json
┣ 📜 me.json
Enter fullscreen mode Exit fullscreen mode

The folder [userid] indicate that this route is dynamic. You can then in the JSON file content consume this variable by using the syntax [userid]. Example in the file /api/users/[userid]/_.json:

{
  "id": "[userid]",
  "email": "Jo.Kessler@yahoo.com"
}
Enter fullscreen mode Exit fullscreen mode

If you call then GET /users/42 you will get the response:

{
  "id": "42",
  "email": "Jo.Kessler@yahoo.com"
}
Enter fullscreen mode Exit fullscreen mode

Here to get the id as a number, just cast the variable by using the syntax n:[var] like "id": "n:[userid]". Variable casting docs

Restapify provide a syntax to use the famous fakerjs library to easily populate your response's body (checkout the docs):

{
  "firstname": "[#faker:name:firstName]",
  "lastname": "[#faker:name:lastName]",
  "email": "[#faker:internet:email]"
}
Enter fullscreen mode Exit fullscreen mode

You can also easily create a waste amount of data by using the for-loop syntax. So if you want to get 10 comments with the request GET /users/:userid/comments just write this in the JSON file /api/users/[userid]/comments.json:

[
  "#for i in range(10)",
  {
    "id": "n:[i]",
    "creatorId": "n:[userid]",
    "content": "[#faker:lorem:sentences]"
  },
  "#endfor"
]
Enter fullscreen mode Exit fullscreen mode

So now we have created all the endpoints of the API that send a succeeded response. But what if we want to test the behaviour of the application when the user doesn't exist in GET /users/:userid for example. A real API would probably return a 404 without any content. To mock this behaviour, Restapify implement the concept of endpoint states. To do this you just have to create a new file for each different state by adding at the end of the file the syntax {STATE_NAME} separated by a dot. So lets create a new state for GET /users/:userid:

📂 api
┣ 📂 users
┃ ┣ 📂 [userid]
┃ ┃ ┗ 📜 _.json
┃ ┃ ┗ 📜 _.404.{NOT_FOUND}.json
Enter fullscreen mode Exit fullscreen mode

To return no-content in Restapify you have to use this syntax as file content:

[null]
Enter fullscreen mode Exit fullscreen mode

An empty file would be more convenient but it's not valid for a JSON file according to the ECMA-404 standard.

Now that you have created your endpoints, it's time to serve the mocked API. For that install the Restapi CLI...

yarn global add restapify 
# or npm install -g restapify
Enter fullscreen mode Exit fullscreen mode

...and then serve the api/ folder:

restapify serve api/
Enter fullscreen mode Exit fullscreen mode

It will then open a dashboard in your browser that give you an overview of the mocked API.

dashboard screenshot

You can in this dashboard consult the endpoints and their content, fetch them and more important select which state of the endpoints you want to serve.

So if you click on the state button NOT_FOUND, it will update the API to serve this state of the endpoint, so if you directly after request GET /users/42 you will receive a 404. This is really helpful to test your frontend (for example a login forms) and you can create so much several state as you want to fit all you need and edge cases.

So I presented the most important features of Restapify but I really encourage you to check the official documentation of it to see other use cases like query string, route variable in for-loops or the fakerjs integration in more details.

You can find some prepared examples of mocked API in https://restapify.vercel.app/examples so that you can directly play and see how it feel. If you have any question or feedback feel free to post it in the discussion and if you want to checkout the source code, here is the GitHub repository:

GitHub logo johannchopin / restapify

Quickly and easily deploy a mocked REST API by using an intuitive and developer friendly JSON file structure

Have a good day ⭐

Top comments (11)

Collapse
 
flippingflapping profile image
flippingflapping

Great library, very simple and quick to use, thanks!

Is it possible to inject my own fake data across multiple fields in an array of objects? I see I can use the for-loop's array sequence and can inject each array value, but is it limited to iterating over an array of strings? Say, could I iterate over an array of objects so that I can use each prop and inject multiple values per iteration?

Collapse
 
johannchopin profile image
johannchopin

You are welcome thanks a lot for your comment 👍

So sadly there is no actual way to achieve such a thing with the for loop syntax 😥 However if you are motivated to help I could suggest you to open an issue and add some idea of implementation. It's not there yet but we can build it 💪

Collapse
 
michelemauro profile image
michelemauro

Isn't the "*" a problematic char to have in a filename?
do you think that would "_" be a good alternative?

Collapse
 
johannchopin profile image
johannchopin

Ah damn you are right it's not valid for the windows OS (and not really recommended for other OS ). Yeah I would fix that by using _ instead thanks for the hint 👍

Collapse
 
johannchopin profile image
johannchopin

Version 1.0.0 of restapify fix this issue by replacing the star selector with the underscore one 🚀 Thanks again for your comment 👍

Collapse
 
vasilyshelkov profile image
Vasily Shelkov

nice one on creating open source :) thanks for creating a post as well on it.

I know it's not quite the same, but I have found MSW (github.com/mswjs/msw) useful for mocking services on the frontend. I'm pointing it out in case there might be something useful that your project could use from it.

Collapse
 
johannchopin profile image
johannchopin

No problem thanks for the support. I never used this tool but it sadly still belong to the list of mocker where you have to write js code for each endpoints. It's really nice when you want to have the closest feeling to a real API but cost more time to build.

Collapse
 
leandroiwai profile image
leandroiwai

This is brilliant. It fit like a glove to the project I'm working now.

Collapse
 
johannchopin profile image
johannchopin

Thanks a lot 😊 Can't wait to have some feedbacks about it from other projects 💪

Collapse
 
saheb24027824 profile image
Uifoxes

JSON in very important for REST apis and name time we have to prepare the json for POST, PUT call in such case you can use this tool it will make your life easy onlinejsontool.com/json-editor

Collapse
 
johannchopin profile image
johannchopin

Nice tool but please stop spamming massive posts with the same comment 🙂