Building Restful Web Apis With Node - JS, Express, Mongodb and Typescript Documentation
Building Restful Web Apis With Node - JS, Express, Mongodb and Typescript Documentation
Dale Nguyen
1 Introductions 3
1.1 Who is this book for? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 How to read this book? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2 Setting Up Project 5
2.1 Before we get started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2 MongoDB preparation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.3 Step 1: Initiate a Node project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.4 Step 2: Install all the dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.5 Step 3: Configure the TypeScript configuration file (tsconfig.json) . . . . . . . . . . . . . . . . . . . 7
2.6 Step 4: edit the running scripts in package.json . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.7 Step 5: getting started with the base configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
i
ii
Building RESTful Web APIs with Node.js, Express, MongoDB and TypeScript Documentation,
Release 1.0.1
Contents: 1
Building RESTful Web APIs with Node.js, Express, MongoDB and TypeScript Documentation,
Release 1.0.1
2 Contents:
CHAPTER 1
Introductions
This book is about how to create a Web APIs from NodeJS, MongoDB, Express and TypeScript. There are lots of
things that need to improve in this book. If you find one, please leave a comment. I’m appreciated that ;)
If you are interested in building Web APIs by taking advancage of the benefits of Node.js, Express, MongoDB and
TypeScript, this book is perfect for you. This book assumes that you already have some knowlege of JavaScript and
NoSQL Database.
The chapters in this book are meant to be read in order. You can skip some parts of some chapters, if you have existing
knowlege.
3
Building RESTful Web APIs with Node.js, Express, MongoDB and TypeScript Documentation,
Release 1.0.1
4 Chapter 1. Introductions
CHAPTER 2
Setting Up Project
Make sure that you have NodeJS installed on your machine. After that, you have to install TypeScript and TypeScript
Node.
In order to test HTTP request, we can use Postman to send sample requests.
You should install MongoDB on your local machine, or use other services such as mLab or Compose
If you installed MongoDB locally, you should install either Robo Mongo or Mongo Compass for GUI interface.
Before we dive into the coding part, you can checkout my github repository if you want to read the configuration in
advance. Otherwise, you just need to follow the steps in order to get your project run.
Create a project folder and initiate the npm project. Remember to answer all the question, and you can edit it any time
after that
mkdir node-apis-project
cd node-apis-project
npm init
5
Building RESTful Web APIs with Node.js, Express, MongoDB and TypeScript Documentation,
Release 1.0.1
The idea is to put all the TypeScript files in the lib folder for development purpose, then for the production, we will
save all the Javascript files in the dist folder. And of course, we will take advantage of the ES2015 in the project.
{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"pretty": true,
"sourceMap": true,
"target": "es6",
"outDir": "./dist",
"baseUrl": "./lib"
},
"include": [
"lib/**/*.ts"
],
"exclude": [
"node_modules"
]
}
So whenever we run the tsc command, all the ts files in the lib folder will be compiled to js files in the dist folder
tsc
{
"scripts": {
"build": "tsc",
"dev": "ts-node ./lib/server.ts",
"start": "nodemon ./dist/server.js",
"prod": "npm run build && npm run start"
}
}
For production
You will need sooner or later the package body-parse for parsing incoming request data.
// lib/app.ts
class App {
constructor() {
this.app = express();
this.config();
}
// lib/server.ts
app.listen(PORT, () => {
console.log('Express server listening on port ' + PORT);
})
From now, although you can not send a HTTP request yet, you still can test the project by running npm run dev.
Remember in part 1 of this project. We save everything in lib folder. So I will create routes folder with a file named
crmRoutes.ts that will save all the routes for this project.
// /lib/routes/crmRoutes.ts
// /lib/app.ts
class App {
9
Building RESTful Web APIs with Node.js, Express, MongoDB and TypeScript Documentation,
Release 1.0.1
constructor() {
this.app = express();
this.config();
this.routePrv.routes(this.app);
}
Now, you can send GET request to your application (http://localhost:3000) directly or by using Postman .
I assume that you have a basic understanding of HTTP request (GET, POST, PUT and DELETE). If you don’t, it is
very simple:
• GET: for retrieving data
• POST: for creating new data
• PUT: for updating data
• DELETE: for deleting data
Now we will build the routing for building a contact CRM that saves, retrieves, updates and deletes contact info.
// /lib/routes/crmRoutes.ts
app.route('/')
.get((req: Request, res: Response) => {
res.status(200).send({
message: 'GET request successfulll!!!!'
})
})
// Contact
app.route('/contact')
// GET endpoint
.get((req: Request, res: Response) => {
// Get all contacts
res.status(200).send({
message: 'GET request successfulll!!!!'
})
})
(continues on next page)
// Contact detail
app.route('/contact/:contactId')
// get specific contact
.get((req: Request, res: Response) => {
// Get a single contact detail
res.status(200).send({
message: 'GET request successfulll!!!!'
})
})
.put((req: Request, res: Response) => {
// Update a contact
res.status(200).send({
message: 'PUT request successfulll!!!!'
})
})
.delete((req: Request, res: Response) => {
// Delete a contact
res.status(200).send({
message: 'DELETE request successfulll!!!!'
})
})
}
}
In this chapter, we will show you how to use Controller and Model for creating, saving, editing and deleting data.
Remember to read the previous parts before you move forward.
All the model files will be saved in /lib/models folder. We will define the structure of the Contact by using Schema
from Mongoose .
// /lib/models/crmModel.ts
13
Building RESTful Web APIs with Node.js, Express, MongoDB and TypeScript Documentation,
Release 1.0.1
This model will be used inside the controller where we will create the data.
Remember in previous chapter, We created CRUD place holder for communicating with the server. Now we will apply
the real logic to the route and controller.
// /lib/controllers/crmController.ts
// /lib/routes/crmRoutes.ts
// /lib/controllers/crmController.ts
Remember that, without {new: true}, the updated document will not be returned.
// /lib/controllers/crmController.ts
if(err){
res.send(err);
(continues on next page)
In the routes,
// /lib/routes/crmRoutes.ts
// /lib/controllers/crmController.ts
In the routes,
// /lib/routes/crmRoutes.ts
Important: Remember that you don’t have to call app.route(‘/contact/:contactId’) every single time for GET, PUT
or DELETE a single contact. You can combine them.
// /lib/routes/crmRoutes.ts
app.route('/contact/:contactId')
// edit specific contact
.get(this.contactController.getContactWithID)
.put(this.contactController.updateContact)
.delete(this.contactController.deleteContact)
From now, your model and controller are ready. We will hook to the MongoDB and test the Web APIs.
In this chapter, we will connect the RESTful API application to local MongoDB, but you can connect to any other
database services. Please read Setting Up Project to install the MongoDB to your machine.
All that you need to do is to import mongoose package, and declare URL for your MongoDB in the app.ts file. After
that you will connect your app with your database through mongoose.
// lib/app.ts
class App {
...
public mongoUrl: string = 'mongodb://localhost/CRMdb';
constructor() {
...
this.mongoSetup();
}
17
Building RESTful Web APIs with Node.js, Express, MongoDB and TypeScript Documentation,
Release 1.0.1
You can test your first route (GET /) through web browser (http://127.0.0.1:3000)
I will send a POST request to http://127.0.0.1:3000/contact with the information of a contact in the body.
Remember to set the content-type in Headers
Content-Type: application/x-www-form-urlencoded
After sending, the server return the status 200 with contact information in the database.
To get all contacts, we just need to send a GET request to http://127.0.0.1:3000/contact. You will get an Array of all
the contacts in the databse. Now there is only one contact that I just created.
If we want to get a single contact by Id, we will send a GET request to http://127.0.0.1:3000/contact/:contactId. It will
return an Object of your contact. Remember that the ID that we passed to the URL is the _id of the contact.
In case we want to update an existing contact, we will send a PUT request to the http://127.0.0.1:3000/contact/:
contactId together with the detail. For example, I will update the phone number of the contact with _id:
5b03015e3c4b1a1164212ff4
After this, now we have a fully working RESTful Web APIs application with TypeScript and Nodejs.
In this chapter, I will show you various methods to secure your RESTful Web APIs. You should use at least one or
combine those methods for a more secure API application.
And if you want to use services like mLab , compose . . . , they have already implemented a secured system on their
end. All that you need to do is to follow their instructions to hook the database to your app.
6.1 Method 1: The first and foremost is that you should always use
HTTPS over HTTP
For local testing, I will use OpenSSL on Windows to generate the key and certificate for HTTPS configuration. The
process is similar on Mac or Linux.
After installing OpenSSL, I will open OpenSSL and start generating key and cert files.
OpenSSL> req -newkey rsa:2048 -nodes -keyout keytemp.pem -x509 -days 365 -out cert.pem
OpenSSL> rsa -in keytemp.pem -out key.pem
After that, we will move key.pem and cert.pem files to our project. They will be in the config folder.
Then we will edit the server.ts file to enable https.
// server.ts
23
Building RESTful Web APIs with Node.js, Express, MongoDB and TypeScript Documentation,
Release 1.0.1
ts-node .\lib\server.ts
From now on, our application will always run over HTTPS.
This method uses a unique key to pass in the URL, so you can access the database. You can use crypto to create a key
from your command line.
node -e "console.log(require('crypto').randomBytes(20).toString('hex'))"
Now, we will use middleware to check for the key before responding to a request. For example, if you want to get all
contacts, you need to pass a key.
// GET request
https://127.0.0.1:3000?key=78942ef2c1c98bf10fca09c808d718fa3734703e
Important: Remember that, in production, you should pass the key in the environment, not directly like in the
Fig. 2: You will get no response and an error if trying to access over HTTP
example.
// lib/routes/crmRouters.ts
It’s sad that by default, there is no security for MongoDB like at all. If you want to check your current configuration.
Go to your mongo installation directory and type mongo.
As you can see, there is no Access control for the database and anyone can do anything with the database. So we will
enable authentication feature for MongoDB.
First, we need to create an account in order to authenticate with Mongodb.
After that, we will stop and restart MongoDB with authentication. Remember to check your dbpath.
Now, if we login to the mongo shell, there is no warning about access control.
Or you can connect to the mongo shell with username and password you just created.
Now, if we try to access the database even with the key, we are not able to.
That’s why we need to edit the mongodb URL in order for the app to work. Again, you should put the mongodb URI
to the environment.
// lib/app.ts
class App {
...
public mongoUrl: string = 'mongodb://dalenguyen:123123@localhost:27017/CRMdb';
Then you restart RESTful API, everything will starts working fine again, but now you have a more secure and control
API application. There are more security methods that we can implement to improve our application. I will try to
update all of them in other posts.
After this, now we have a fully secure and working RESTful Web APIs application with TypeScript and Nodejs. If
you want to check all the code, please visit my github repository for the full code.
• genindex
• modindex
• search
29