Development of API using Node and Express (Part 1)

Abdulfattah Hamzah Atanda
7 min readJun 9, 2020

--

Setting up projects especially when it’s a dynamic multi-platform application although not limited to this, will require that all platforms query the same resources (let’s say the same database). In order to simplify such requests this requires making calls to the same API’s (Application programming interface).

Basically, this has to do with the server side of the application where the client platforms make requests to.

This write up will focus on development of API to be exemplified with a project termed “Product App”. The project will aim at CRUD operation for a product. I will be using node, express and PostgreSQL database to demonstrate the API development.

Project Setup

To start, you need to have Node installed on your system and PostgreSQL database. Checkout their documentation on how to install and set them up.

  • Create a project folder named Products
  • Initialize the project using node with this command npm init
  • After initializing the project, you should find a package.json file created with some information being set during initialization of the node application
  • Install the following dependencies: express, body-parser, @babel/cli, @babel/core, @babel/node, @babel/preset-env, make-runnable, pg, dotenv. To install a dependency which will be required in production use npm install dependency_name, while for development dependency you add a flag -d or -dev i.e npm install -d dependency_name
  • MVC (Model, View, Controller) architecture will be used for this project. So, create the following folders inside the project root directory: model, controller, migrations, routes. Inside the project folder (.i.e the parent directory) there should be an index.js file created when initializing the node project. If not you can create it and that will be the entry file for the project.
  • Configure babel. Basically babel is used to compile JavaScript from Es6 to Es5. In this project, I will be using Es6. To do this, a .babelrc file should be created with the below configuration:
babel configuration

@babel/preset-env is basically the babel plugin that transforms the new JavaScript syntax (i.e Es6 (ECMAScript 2015) and beyond) into a backwards compatible version of JavaScript.

  • Setup postgres database. I will be naming my database products. Create a config.js file to configure the database to write and read from in the project. Here, we will be making use of the pg dependency earlier installed. The pg dependency is the nodejs module to interface with the postgres database. In this project, Pooling is being used because it gives room for multiple instances of client request to the db.
database configuration

In the above, Pool method was imported from pg in order to allow for multiple requests to the database. Also, dotenv is a node module that gives an interface to access environmental variables in a .env file in a node application. It’s always a good practice not to set some data which are not meant to be accessible to the public (such as secret keys, database information etc) inside your code. A better way to do that is to place them inside an env file. Below is how PostgreSQL database URL should be set in the .env file

dotenv.config() initializes the environment variable and makes it accessible. Thereafter, a new instance of Pool is configured with the options. Here, I am using the database URL which can be configured using the connectionString option. Note, if you are pushing your code to Version control systems such as github, bitbucket, do not push your .env file rather you could create a sample-env file with just the environment variables that’s needed to be set in the project.

  • Setup server. Go to index.js file which is the entry file. This is where the serve will be instantiated. To create the server, express.js will be used to create a server instance to run the application.
  • Import express module and initialize the server. Then, the express instance (i.e app) is set to listen for connection requests to the declared port number (defaulted to 8000) using the listen method made available via express. In the above code, lookup for an environment variable PORT which will be used and defaulted to 8000 should in case the port wasn’t set in the .env file.
  • To test your server if it’s properly set up, let’s run the application. However, the application can’t just start magically like that. We need to create a script command that will be used to start the application in the package.json file. Basically any kind of command you will always need to run, it’s always good you create it inside the script object within the package.json file. So by default, the start command is used to start a node application. However, you will have to declare the scripts that will be loaded by the start command.

In the project, the start command script is declared in the package.json as shown below

Here, babel-node is used to run the application. Babel-node is a CLI that works exactly the same as the node.js CLI, with the added benefit of compiling with babel presets and plugins before running the application. However, it’s not good to use babel-node in production because it’s heavy with high memory usage which can affect your application’s performance.

  • Now, start the application by running npm start in your terminal or command line interface. npm start is a short form of npm run start and this is so because the start and test commands are default npm commands. Any command which is not the default npm command needs to use npm run command_name. After starting the application you should see this
  • You will notice the port number the app will be listening to here is 7000 as against the default port 8000 set in the project. The 7000 is the port number that have been set in the environment variables file. Now, load http://localhost:7000 on your browser, you should see something like this
  • An error is displayed above, because we are trying to make a GET request to the root URL. However, what should happen when a request is made by a client to the root URL has not been defined. So let’s send a message to the browser when a request is made to the root URL. Go to index.js file to add the response to be sent by the server when a request is made to the root URL
  • What was done basically in the highlighted line of code is defining what should happen when a GET HTTP request is made to the root URL while the server is running. app is the server instance and get is one of the HTTP request methods. The first argument is the PATH on the server while the second argument is the callback function which is a handler function that is executed when a request is made to the path. The handler exposes the request and response object. In the above, I use the response object to send a response back to the client. Summarily route definition follows this format app.METHOD(PATH, HANDLER) where
  • app is an instance of express.
  • METHOD is an HTTP request method, in lowercase.
  • PATH is a path on the server.
  • HANDLER is the function executed when the route is matched.

After defining the root route, you have to restart your server so that the new changes can reflect.In the part 2 of this tutorial, I will introduce what can be used to run the application during development such that it watches for any new changes and restarts your application automatically. Now, load this URL ( http://localhost:7000) again in the browser you should see “Hello World” being displayed in your browser.

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

--

--

Abdulfattah Hamzah Atanda

Fullstack Software Engineer skilled in NodeJs, React and React Native with interest in building robust mobile and web applications