Development of API using Node and Express (Part 2)
By: Abdulfattah Hamzah Atanda
Tags: Postgresql, Api Development, Node Js Tutorial, Expressjs, Beginners Guide

Part One of this write up can be found in Development of API using Node and Express (Part 1)

Create Product Endpoint

A. Create Migration Method

To start with, I will create a products.js file in the migrations folder created in the root folder. Here, I will define my SQL script that will create the products table in my database. Below is the migration code

The Pool instance configured during database setup in the config.js file was imported. Thereafter, registered an event listener to listen to the pool connect event which logs “connected to database” when the application is successfully connected to the database.

Then, a function createProductTable was defined, which will be called to run the PostgreSQL query to create a products table. For more info on PostgreSQL usage check their documentation. Inside the function, SQL query was defined to run and then use the pool query method to run the SQL query. Only four columns (id, name, description, created_at) is to be created in the products table. After which, the function is being exported to be accessible from outside this file. The make-runnable module was required here to make this file function available to be called directly from the command line.

Now let’s define the script that will be called to create a products table in the package.json file script object as shown below

Babel-node is used to run the function defined to create table in the database. Confirm if your database is already created. Find out how to list your PostgreSQL database and tables in the command line.

Now run npm run createProductTable to create your table in your database. You should get something like this, as shown below

Now checking your database to confirm if it was actually created. You should see this

B. Setup Request Body Parser

The incoming request body needs to be parsed to ensure only allowed content types coming from the client passes through for processing. Hence, body-parser which is a module that helps achieve that was used. This parser middleware will be set in the index.js file after the express server had been instantiated. Below is the declaration as shown below

root index.js file

The body parser module was imported and the two content types (json and url encoded) are to be allowed by the application for processing. So, the json and urlencoded parser will parse all incoming requests to the server.

C. Create Product Model

Let’s create the model that will interface the database to create a product. Create a products.js file inside the model folder in the root folder. Below is the model method to create a Product

migration products.js

The pool instance configured was exported which gives the client access to connect to the database. A createProduct method was defined with the query to insert a product entity inside the products table. In the SQL query defined, only name, description and created_at value that’s required to be passed to this model. Note, the values argument of the model defined must be an array which must contain the name, description and created_at values arranged in that order as defined in the SQL query else data will be inserted in the wrong column. The rows array of objects was destructured from the data returned from the new entity created in the products table which is then returned.

D. Create Controller Method

Next is the controller method which is the intermediary between the client and model. Create a products.js file inside the controller folder with the code shown below

controller products.js

Firstly, the createProduct model method was imported. Then a controller method for product creation named addProduct was defined. It has two arguments which are the request and response object which are exposed by express. The request object embodies any data that is coming from the client that made the request. The two data required from the client request body are the product’s name and description which is being destructured out of the request body object. The created_at time stamp was defined and assigned current time value. The request body values are then passed to the model which inserts them into a row in the products table. Thereafter, the product row object returned is then sent back to the client as json.

E. Declare Route

Now define the route needed to make a request to create a product. So basically api routes are always of this format root_url/api/version/resource (e.g http://example.com/api/v1/users); Note that it’s always good your api’s are versioned. In your routes folder, create index.js file in it and create v1 folder with index.js and products.js file inside it as well. You should have something like this

Below code should be in the routes index.js file

routes index.js

An express router object instance was created and any request to api/v1 will be routed to the version1 route. Express router is capable of performing middleware and routing functions. Below is the version1 router definition in the v1 index.js file.

v1 index.js

An express router object was instantiated. Any request to api/v1/products will be routed to productRouter defined in the v1 products.js file. Below is the productRouter definition

v1 products.js

Above, express router was instantiated and router defines the type of HTTP request method that will be routed to the controller method addProduct passed as the router.post argument. Only post requests to /api/v1/products will call the addProduct controller method. Invariably, any other request method (such as get, patch etc) to /api/v1/products will not be recognized by the server.

Let’s complete our route definition by passing our router to the express server instance use method as argument. This is done inside the entry index.js file in the root folder as shown below

root index.js

Note that the router was passed to the server instance after the body parser middleware which needs to parse all incoming requests before it continues with processing the request.

F. Testing with Postman

Let’s test our newly created api endpoint which is root_url/api/v1/products which only allows post requests. To test api endpoints, you can download and use postman. Start your application using npm start then test the endpoint just created using the below guide

Step 1: Put the endpoint URL inside the URL text input and select the request method as shown below in postman

Step 2: set the content-type as application/json in the Headers content section

Step 3: pass in the request body object of the data to be sent to the server. In the post endpoint, we only need to pass the product name and description into the request body

Step 4: Click the send and you will get a json response object in the response section as shown below

From the response returned it can be seen that the endpoint is working and successfully returned the data of the created product.

Finally, a double check can be done by checking the products table to be sure the product was actually created as shown below

Example Project GitHub Repository: https://github.com/fantastic-genius/products

Part three of this write up can be found in Development of API using Node and Express (Part 3)