Building a rest API using Typescript, Express and with Dependency Injection pattern.

Kishore Srinivas
6 min readJun 7, 2022

--

Road trip on building the rest api starter template that can help you to kick start your Web API development.

Overview

In this article, we will be building a REST API with Node JS , Typescript and API will be built with OOP(Object Oriented Programming) and Functional Programing. Going further, We will going to make use of commonly used Dependency Injection pattern which will allow us to create scalable, loosely coupled API’s.

You might be thinking there are many starter patterns already available. Why do we need to look into this. All the patterns/design out there are great. But when I was going through, Implementing the API by consuming OOP in functional programing will make our API bit scalable and allow us to writing quality code.

So welcome to the learning road map and let’s get started.

What you will need

To begin, first you have initialize your project with:
— Install NodeJS and NPM from https://nodejs.org/en/download/.
— A code editor of your choice. I am using VS Code.
— To test the API, I’ll be using Postman. You can use any other tools of your choice.

Getting started :

We will first create a new directory and name it has node-restbolierplate. Open the newly created folder with VS code or any of your favorite editor.

$ mkdir node-restboilerplate
$ cd node-restboilerplate

Navigate into the newly created directory and Open the terminal form your editor and run the below command.

npm init

You will be asked with series of question about the project. You can accept all the defaults until you get to the entry point or else you can update your input about your project.

Your npm init output will looks something like this.

Once you reach to the endpoint press “Enter”. A new file called package.json will be created at the root level of your project directory. This file will holds the information about your project’s dependency.

Now we will going to install typescript globally by running the below command. Adding the –g flag to install the packages globally ensures that Typescript is available to any Node.js project.

npm i -g typescript

Let’s Create tsconfig.json file at the root level of our directory. This file specifies the root files and the compiler options required to compile the project. Open the terminal and run :

tsc --init

This will create a tsconfig file in the root of our project directory. Add the below configuration inside the tsconfig file.

{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"pretty": true,
"sourceMap": true,
"outDir": "dist",
"importHelpers": true,
"strict": true,
"noImplicitAny": false,
"strictNullChecks": false,
"noImplicitThis": false,
"alwaysStrict": true,
"noUnusedLocals": true,
"noUnusedParameters": false,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"moduleResolution": "node",
"baseUrl": ".",
"allowSyntheticDefaultImports": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"resolveJsonModule": true,
"paths": {}
}
}

Let’s create a folder named dist at the root of the project. When we run the application, compiler will put the transpiled Javascript files in the dist folder.

Now, we are going to install all the dependencies which we will going to use while building the REST API.

npm i express axios ts-node routing-controllers reflect-metadata module-alias body-parser class-transformer class-validator typedi tslib --savenpm i typescript @types/node --save-dev

Your package.json now looks something like this.

package.json

Let’s Start…

Once all the dependencies are been installed. Create a folder api at the root of the project and inside the api folder create a file app.ts .

Add the following code into the app.ts file.

Note: Currently I have created a logger class to handle the logs. In the above file I have imported it. That’s why we are able to see the log message in terminal. You can replace the Logger with console.log to see the output in the terminal.

Create a folder app at the root level of project and inside that folder create config.ts file. Here we will define all the project related configurations things.

Add the following code into the config.ts file.

From here onwards, we will be adding more new things into our project. Whenever we make changes we need to restart the server, that will be tedious activity.

So we will going to use a library called nodemon, which reduces a lot of development time by automatically restarting our application whenever any file related to our project is altered and saved.

Run the below command to install it.

$ npm i nodemon --save-dev

Once it’s been installed, we will make some changes in the package.json file.

Add the below line of code inside the script section.

“scripts”: {
"dev": "tsc & nodemon api/app.ts"
},

Save the package.json file and run the below command.

$ npm run dev

You should be able to see the below output in your terminal.

Nodemon Server Started

Now try to make some changes in the app.js file, the nodemon will automatically restart the server for us.

The controller

Now we need the entry point for our HTTP to perform some of the API actions. Under the api folder, create sub folder called userProfile and inside that create controller, model, service folders.

So let’s see what we have here :

  • @JsonController : This will indicate that our data returned by our controller actions always be transformed to JSON.
  • @Service : It’s an decorator, used to create instances for unknown classes.
  • @Get : Indicate the Http method that is linked to our method.

The model

We will create the request and response object of our REST API.

The Services

Here we will perform our Data fetching activity. If we are fetching the data from Database or from external API’s. All those activity should take place here. Currently I’ll be using external API’s to fetch the data.

Lets Test!

It’s time to hit our endpoint in the postman. Make sure the serve is up. Let’s ping our endpoints.

http://localhost:8500/v1/api/userInfo/getUserInfo
http://localhost:8500/v1/api/userInfo/getUserInfoById?id=15

Boom !! It works. If you hit the request in postman and check the terminal. You will be able to see the logged response.

Server log

The Folder Structure :

Application Structure

Above one is the boilerplate folder structure.

Here I have used class for generating logs. It’s just for example. We have package called Winston , we can use that also. If you have any better idea, you can implement that approach as well.

When the application keeps growing, we can create individual folder for the different use cases. Here I have created only one folder. If we need to perform (DTO or massage the request or response), we can create class folder on top of controller folder and there we can achieve what ever the way we want.

All the logic should be handled in controller files. DB calls or API invocation should happen in service files. All the endpoint should be configured in config.ts files. Here for learning purpose, I have kept in service file.

Conclusion:

Through out this tutorial, you have engaged in building RESTful API. As I mentioned in the top, it’s an starter template to create the skeleton structure for our application. For more information on creation of the class based approach you can refer routing-controller.

Let me know if you have anything to discuss with me in the comments section. I’ll be happy to hear !!!

Source code

Please find the github repository link.

Thanks for reading !! Feel free to leave any comment.

--

--