Mocking data for Front-end developers

I like to create software following a simple approach where I first define how clients will interact with it, should it be humans interacting with UIs or other apps interacting with APIs.

Say I want to create an SDK in Go that interacts with a internal service. First, I determine how other apps will interact with that. For example, before starting creating the logic behind the function, I know my function will look like this:

func main() {
  items, err := customSDK.GetItem(id)
  // ...
}

Usually, that also makes my life easier to work with automated tests. During the actual development, I'll probably add a new extra parameter or even make a brutal change to the API, but that's how I like to start.

That's not different for user interfaces, I like to see real information when coding front-end stuff as well. In most cases, the front-end will start after the API is already finished, especially when it comes to rebranding the entire UI and starting a fresh version.

Though, sometimes we need to see the front-end in action even when the back-end is planned to be executed after. Also, there are some cases we want to implement a feature as a test or playground to learn something new, but don't want to implement an entire back-end API.

Serving Mock data

Instead of creating mock objects directly on your front-end, and adding timeouts to ‘fake’ a loading layer that a network request would add, you can simply create a mock server using json-server.

Create a db.json file and add in some resources:

{
  "posts": [
    {
      "id": 1,
      "title": "My post title",
      "views": 100
	}
  ],
  "profile": {
    "name": "My Profile"
  }
}

Simply run:

npx json-server db.json

Once you start your local server, you can run the following command to get a post with ID = 1:

curl -X 'GET' 'http://localhost:3000/posts/1' \
  -H 'Accept: application/json'

That's it! You now have a REST API up and running. Run npx json-server --help for a full list of option or check the documentation.

Share:
Buy Me A Coffee