Hello everyone, I am big fan of Node and have been using it from couple of months and it’s amazing. It is easy to get started and build application on Node. The most amazing thing about node is that it is all JavaScript. We all esp. web developers have worked with JavaScript at some or other point of time.
The awesomeness is you get the goodness of JavaScript, to build scalable system. Companies like UBER, NETFLIX, PAYPAL etc. have already adopted Node. So, if you don’t know about Node better get started with it as it can give you great career in future.
I would be giving some step by step tutorials on getting started with node. I have mostly used node for creating rest based web apis but you also serve web pages or files.
I will be using windows 7 as base machine for delivering these tutorial but the same tutorial could easily be replicated in other OS.
Creating Rest Based Web Apis using Node JS
- Framework- Express JS
- Database- mysql
- ORM – sequelize
Software needed-
- Node JS - Platform
- MySQL – your database provider
- Postman – used for creating http requests like GET, PUT, POST, DELETE
Install Node JS and MySQL from official website according to your platform(win/mac/linux).
We will be using postman as a client for sending http requests which is an extension for Chrome. You can also use SoapUI or apache-jmeter.
Before starting tutorial I would like you to create a user and a database in your MySql.
1. Initializing Node repo
Open command prompt (cmd.exe) or terminal or bash in your system. In window you can also open Node JS Command prompt. Go to directory where you want to create project( cd <path to directory>).
Type
(This command will initialize a node repository and will ask you certain parameter to fill in. You can leave parameter empty and can just press enter for skipping.)
This will create a file package.json which actually contains all packages for you given project.
2. Creating server file- Create server.js file in your current directory using file options.
3. Installing Dependencies-
In this we will install all applicable dependencies for our project. Here npm is node package manager which fetch packages via their online hub.
- npm install express
- npm install sequelize
4. Start coding
Paste the following code snippet in server.js
- var express = require('express');
- var app = express();
- var port = 3000;
- app.get('/', function(req, res){
- res.send('welcome to my api');
- });
- app.listen(port, function(){
- });
- console.log('my api is running on port:'+ port);
In above piece of code we have initialized express JS and created a simple address / for our api’s
5. Running API’s
Now it’s time to trigger our api so type following command
You will get a message “my api is running on port:3000” which means you are ready with your basic api.
6. Testing API
Open postman and write the url “localhost:3000/”
Yipee! You are done with your web api.