Developing REST APIs with ExpressWebJs v2(A Nodejs Framework) part 1.
Tags: microservices, node, javascript
Published: 2021-02-17 22:21:34

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5c38htgku4uomtbjzrtv.png)

ExpressWebJs is a Node FrameWork with expressive and organised syntax that runs on all major operating systems. It provides the starting point for creating your node project, allowing you to focus more on developing your amazing solution.

ExpressWebJs focuses on providing developer experience and powerful features such as dependency injection,database abstraction layer for both SQL and NOSQL, robust routing, code structure, application configuration, testing and more.

# There are some built in features of ExpressWebJs
   . Robust routing
   . Focus on high performance
   . Super-high test coverage
   . HTTP helpers (redirection, caching, etc)
   . Support for both SQL and NOSQL database
   . Well organised and structured.
   . Supports Use Of Dependency Injection
   . Supports websocket
   . Highly scalable
   . Events and Listeners
   . Queues
   . Task Scheduling

# Building an employee record API with ExpressWebJs
At company X, we have many employees. We are asked to build an app to manage our employee record. The front end app will be built with Vuejs or ReactJs. However, it needs to pull data from a source and also push to it. We need an API which we are going to develop with ExpressWebJs.

This is what we need our API to do:
   . Get all employees 
   . Get an employee 
   . Add new employee
   . Edit employee record
   . Delete an employee

For the endpoints, we will be looking at:
   . GET /api/employees
   . GET /api/employees/6
   . POST /api/employees
   . PATCH  /api/employees/6
   . DELETE /api/employees/6

Next we will look at employees attribute:
   . name
   . email
   . phone
   . location
   . country
   . state

# Install ExpressWebJs
Run the following command in your terminal to create a new project with ExpressWebJs:

```cli
  npx expresswebcli new employeesApp
```
cd into your newly created project.
```cli
  cd employeesApp
```

Now run <code>npm install </code> to install all dependencies.

Copy example.env into .env file with the following command
```cli
 cp example.env .env
```

Once that is done, you can now configure your database in the .env file. 
### Remember: ExpressWebJs supports Both SQL and NOSQL Database.

For this tutorial, we will be working with mysql db (sql database).

Now, run <code> npm run dev </code> to serve the project. Head over to your browser.

# Migration:
ExpressWebJs comes with Maker command, which is the command line interface. Maker exists at the root of your application as the maker script and provides a number of helpful commands that can assist you while you build your application. To view a list of all available Maker commands, you may use the help command:

```cli
  node maker -h
```

So for us to create our employees migration and model, we can do that like so:

```cli
  node maker make-sql-model employees -m
```

<code> -m </code> tells <code>Maker </code> to also generate out migration while creating our model.

The new migration will be placed in <code> Database/Migrations </code> .
 Each migration file name contains a timestamp, which allows ExpressWebJs to determine the order of the migrations. Next, we'll modify the recently created migration to include the attributes we need for the employees table.

Open up the migration file and modify it like so:

```js
  /**
   * Migration layout file.
   * Assign your table name to the tableName variable.
   * Remember, it's always in plural
  */
  let tableName = "employees";
  exports.up = function (knex) {
  return knex.schema.createTable(tableName, (table) => {
    table.increments("id");
    table.string("name").notNullable();
    table.string("email").unique().notNullable();
    table.string("phone").notNullable();
    table.string("location").notNullable();
    table.string("country").notNullable();
    table.string("state").notNullable();
    table.timestamps(true, true);
  });
};

exports.down = function (knex) {
  return knex.schema.dropTable(tableName);
};
```

Now, go ahead and run the migration like so:

```js
   node maker run-sql-migration
```

Check your database. You should now have the <code>employees</code> and <code> migrations </code> tables present.

# model
when we ran the <code> node maker make-sql-model employees 
 -m </code> ExpressWebjs generated our model in the <code> App/Model </code> directory.

App/Model/Employees_model.js

```js
   "use strict";
   const Model = require("@elucidate/Model");
   class Employees extends Model {
      static get tableName() {
         return "employees";
      }
   }

   module.exports = Employees;
```

# Set up Employees Controller
To create a new controller called EmployeesController, use the maker command for controller:

```js
  node maker make-controller EmployeesController -r
```
where <code> -r </code> will tell Maker to generate our controller with resource methods.

Our Controller will be generated in <code> App/Http/Controller </code> directory

App/Http/Controller/EmployeesController:

```js
  "use strict";

        class EmployeesController{
          /**
           * Display a listing of the resource.
           */
          index = async (req, res, next) =>{
            try{
              //
            }catch (error) {
              return next(error);
            }
          }

          /**
           * Show the form for creating a new resource.
           *
           * @return Response
           */
          create = async (req, res, next) => {
            try{
              //
            }catch (error) {
              return next(error);
            }
          }

          /**
           * Store a newly created resource in storage.
           * @param  Request 
           * @return Response
           */
          store = async (req, res, next) => {
            try{
              //
            }catch (error) {
              return next(error);
            }
          }

          /**
           * Display the specified resource.
           * @param  Request
           * @return Response
           */
          show = async (req, res, next) => {
            try{
              //
            }catch (error) {
              return next(error);
            }
          }

          /**
           * Show the form for editing the specified resource.
           * @param  Request
           * @return Response
           */
          edit = async (req, res, next) => {
            try{
              //
            }catch (error) {
              return next(error);
            }
          }

          /**
           * Update the specified resource in storage.
           * @param  Request
           * @return Response
           */
          update = async (req, res, next) => {
            try{
              //
            }catch (error) {
              return next(error);
            }
          }

          /**
           * Remove the specified resource from storage.
           *
           * @param Request
           * @return Response
           */
          destroy = async (req, res, next) => {
            try{
              //
            }catch (error) {
              return next(error);
            }
          }
        }

        module.exports = EmployeesController;
        
```
We will fill up our EmployeesController in a bit.

# Set up Routes
Routing is fairly straight-forward. Open up Routes/api.js and modify it like so:

```js
   "use strict";
   const Route = require("@routerManager");
   /*
    |---------------------------------------------------------
    | Api route   
    |---------------------------------------------------------
    |
    | Here is where you can register your application routes. 
    | These
    | routes are loaded by the RouteProvider. Now create 
    | something great!
    |
  */

Route.get("/", (req, res) => {
  res.json({ Message: "Welcome To ExpressWebjs" });
});

Route.group("/employees", () => {
  Route.get("/","EmployeesController@index");

  Route.get("/:id", "EmployeesController@show");

  Route.post("/", "EmployeesController@store");

  Route.patch("/", "EmployeesController@update");

  Route.delete("/:id", "EmployeesController@destroy");
});

module.exports = Route.exec;
```

### We will start developing the business logic in [part 2](https://dev.to/alexigbokwe/developing-rest-apis-with-expresswebjs-v2-a-nodejs-framework-part-2-8dk).
To read more about ExpressWebJs, visit the Documentation site at [ExpressWebJs](https://expresswebjs.com)

You can follow me on twitter [@EmekaIgbokwe](https://twitter.com/EmekaIgbokwe)
You can follow ExpressWebJs on twitter [@expresswebjs](https://twitter.com/expresswebjs)
and don't forget to star on github [ExpressWebJs](https://github.com/Alexigbokwe/ExpressWebJs)

Please, let me know if you have any questions in the comment section. 😊