Skip to main content

Setting up a JSON server

Let's set up our own JSON server with some mock data so we can practice RESTful requests from within our TaskFlow code. Rather than fetching from a remote API, we're going to install a package (json-server) which lets us test fetch requests within our own project.

First, install JSON Server:

npm install -g json-server

Then we'll need to set up a 'database' and add some data. For this we'll create a db.json file in the root of our repository and we'll add the following code:

{
"time-entries": [
{
"client": "Heineken",
"endTime": "2020-03-10T16:30:00.000Z",
"id": 1,
"startTime": "2020-03-10T09:30:00.000Z",
"activity": "Testing"
},
{
"client": "Port of Rotterdam",
"endTime": "2020-03-10T09:30:00.000Z",
"id": 2,
"startTime": "2020-03-10T07:30:00.000Z",
"activity": "Design"
},
{
"client": "Hike One",
"endTime": "2020-03-12T17:30:00.000Z",
"id": 3,
"startTime": "2020-03-12T09:30:00.000Z",
"activity": "Development"
},
],
}

Finally, we'll need to adjust our package.json scripts to make sure our server is running when our development build is also active. Adjust/add the following lines to package.json to make sure the json-server is also started when we run our usual npm run dev command:

    "json-server": "json-server --watch db.json --port 3004",
"dev": "next & npm run json-server",

Now, terminate your current development build and run npm run dev to start our application and json-server.

We're ready to GET our first time entries from our own server! Now if you go to http://localhost:3004/time-entries, you'll see all the time entries in your database. If you want to fetch a specific time entry, you can use the entry's id. So, http://localhost:3004/time-entries/1 will return the following entry:

    {
"client": "Heineken",
"endTime": "2020-03-10T16:30:00.000Z",
"id": 1,
"startTime": "2020-03-10T09:30:00.000Z",
"activity": "Testing"
}

For more advanced options, check out the json-server README!