Building APIs with Json-Server, Faker and Lodash

gikwegbu

George Ikwegbu Chinedu

Posted on August 24, 2020

Building APIs with Json-Server, Faker and Lodash

Photo by Pixabay from Pexels

Table Of Contents

NB: This article, will be based on the premise that you are already familiar with 
1. JSON
2. API
3. JavaScript
4. Package Manager (in this case, NPM)
5. Postman
Enter fullscreen mode Exit fullscreen mode

Install Packages

Let's start with installing our packages with the help of our package manager (npm). I am using node v10.16.0. To check which version you're using run the below code in your shell.

 node --version
// v10.16.0
Enter fullscreen mode Exit fullscreen mode

To install all the packages at once , navigate to your Project's root folder and type the below code

 npm install faker json-server lodash
Enter fullscreen mode Exit fullscreen mode
NB: '位' should not be included, I use (https://cmder.net/) for my shell
Enter fullscreen mode Exit fullscreen mode

Create Generator.js File

To properly arrange things, create a folder in the root directory of your project (same 
level as you node_modules). Say 'db', where you will store your Generator.js and 
Database.json files.
Enter fullscreen mode Exit fullscreen mode

Folder Structure for Generator.js and Database.json

  1. The Generator.js will serve as a schema (template) for building our Database structures. Unless you plan on writing out the data yourself, heck!!!, you could as well buy finger massage cream before you start 馃槀. The Generator.js would be a default exported module (Kinda turned it up-side-down) js file, within will be where you will require the faker and lodash package we installed earlier. Then we return an object, containing our endpoint-schema.

Generator.js Config

Schema Structure

With the faker and lodash required (NB: as at the time of writing this article, Node.js, uses require, instead of import syntax), the returned object, will have a first layer key-value pair, which would serve as the endpoint (like; www.localhost:8080/people) when we are done.

Lodash, A JavaScript utility library delivering consistency, modularity, 
performance, & extras (https://lodash.com/)

Faker is a JavaScript library that generates fake data for you. Whether 
you need   to bootstrap your database, create good-looking XML documents, 
fill-in  your persistence to stress test it, or anonymize data taken from 
a  production service, Faker is for you.  
(https://github.com/marak/Faker.js/)
Enter fullscreen mode Exit fullscreen mode
people: lodash.times(100, (n) => {
    return{
       id: n + 1,
       name: faker.name.findName(),
       avatar: faker.image.avatar(),
       phone: faker.phone.phoneNumber(),
       email: faker.internet.email()
     }
}),
// lodash.times(100) performs a 100th time loop with n as the counter.
/* faker.name.findName() is a method found in faker docs, for providing random names.
*/
Enter fullscreen mode Exit fullscreen mode

Editing Package.json File

It's time to run our script to do the softwork for us, i.e generating our data. Find your package.json file, also found in your root directory. Move down to the scripts section, add the below code.

"gen" : "json-server ./db/generate.js", 

// "gen" is just a fancy name I used (you could legit come up with yours 馃槑)
/* json-server, our third (actually first 馃榿) package installed
 will be automatically picked by node.
*/
// Then comes the ./db/generate.js, which is the directory and the generator file. 

Enter fullscreen mode Exit fullscreen mode

Package.json config

NB: Please forgive me, Just found out my project bears 'generate.js' 
instead of 'generator.js', they are still same procedure. And 'db.json' 
instead of 'dashboard.js'
Enter fullscreen mode Exit fullscreen mode

Ok, With the Package config done, go to your shell, and run the below code

 npm run gen

// This will executes the script action we configured in the package.json file // and generate our data
Enter fullscreen mode Exit fullscreen mode
NB: Hey, if you had taken my advice and name yours another thing, edit the 
above code and enter your own name. (Let's save ourselves headaches from 
debugging 馃槈)
Enter fullscreen mode Exit fullscreen mode

Testing with Postman 1

If everything went well, without errors, you will receive a Url for your endpoints like below

Url for Generated endpoints

YES!!! we did it 馃帀馃帀馃帀馃帀馃帀馃帀 
Enter fullscreen mode Exit fullscreen mode

Now, open your postman, use a GET request on the available endpoints. Your result should look like the below image.
Postman Image on Get method endpoint for people

Create Database.json File

NB: In my own project, I used 'db.json'
Enter fullscreen mode Exit fullscreen mode

Create a database.json file, copy your response from the postman result, as seen in the above section's image, and paste inside the database.json

NB: Just for tips, json is just lovely, so I will show you how to paste 
and format fro json.
Enter fullscreen mode Exit fullscreen mode
/* First, have your curly braces, then the key(endpoint, and <b>must</b> 
be in  <b>Double</b> quate), and then what you 
copied from postman.
*/
{
   "people": [
       {
          "id": 1,
          "name": "Kiana Gulgowski Sr.",
          "avatar":"https:// 128.jpg",
          "phone": "120.085.7363 x3143",
          "email": "Daren2@yahoo.com"
        },
       ...
       .
       .
       .
        {
          "id": 100,
          "name": "Stevie Morar",
          "avatar":  "https://s3.amazonaws.com/128.jpg",
          "phone": "(122) 628-3813 x91330",
          "email": "Antonina47@yahoo.com"
        }
     ],
   "feeds":
    {
       "state": "success",
       "pages": 1,
       "feeds": [
          {
             "id": 1,
             "fullname": "Adelle Jacobi",
             "avatar": "https://s3.amazonaws.com/uifaces/28.jpg",
             "handle": "Jayson.Raynor",
             "user_id": "6c8556ac-d616-4288-ad73-35bf9ade456b",
             "timePosted": "2020-09-08T09:51:03.854Z",
             "content": "Sit doloremque v",
             "likes": "@Conn",
             "comments": "@Leif"
           },
        ]
    }
}
Enter fullscreen mode Exit fullscreen mode
NB: The above is just a snippet of how your database.json file should be 
structured. When you are done, Please refer back to the Editing 
Package.json File image, check the next script 
added ? <b>spin</b>. This would be used to spin and properly configure the 
<b>database.json</b> file as a full API service. When you are done editing 
the package.json file, do well to run the below code, to spin up the 
server.
Enter fullscreen mode Exit fullscreen mode
// in your package.json file, in the script section
"spin" : "json-server ./db/db.js" // used to spin the server

// in your shell
 npm run spin

/* This will executes the script action we configured in the 
package.json file  and spin up the server proper.
*/
Enter fullscreen mode Exit fullscreen mode

Conclusion

Hey, congratulations Champ!!! We did it. Now, as the database server is up and running (I don't know who is pursing it though 馃ぃ馃ぃ). You can make API calls from your FrontEnd applications, with the endpoints we talked about, and you will get results. Also, other http methods are accepted, atleast, I have tried out POST.

NB: The script for generating the data creates an endpoint, this should 
only be used for generation. To use the API proper, spin the server, then 
another open shell, spin your own FrontEnd server, in my case (using quasar)
Enter fullscreen mode Exit fullscreen mode
 quasar dev // for quasar development mode

 npm run serve // for vue


Enter fullscreen mode Exit fullscreen mode

Thanks.

[deleted user] image

[Deleted User]

馃挅 馃挭 馃檯 馃毄
gikwegbu
George Ikwegbu Chinedu

Posted on August 24, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related