Thursday, August 28, 2014

Creating A Simple RESTful Web Service using Express Node.js - JSON Data for Different Platforms (Part - 1/2)

As Every Day Device Shrinks and the way how it is connected to the Server to pull data and Append data becomes complex.Here is the solution for that because usually Network related application are data driven applications,where data is the king and we could make up something as we need .JSON data - Javascript Object Notified which is considered to be Light weight data for data sharing between two platforms or systems.where XML is also used,but JSON is preferable for mobile applications to pull data easily via AJAX JQuery with cross origin request.API is common term where in web apps are data driven application,Data is used to build apps which paves a way to create Application Programs with those data.


Creating A Simple RESTful Web Service using Express Node.js - JSON Data for Different Platforms (Part - 1/2)
Creating A Simple RESTful Web Service using Express Node.js - JSON Data for Different Platforms (Part - 1/2)
Download :  Download Demo

The Main Aim of Creating such Rest API Web Service is to share the data between application where we could create apps that can reach a huge peoples!


There are lot of standards in REST API building to prevent attacks,scaling and illegal requests.To prevent that we could add APP ID and Secret token basically (BASIC).Oauth2 standards would have such process



  • The Specific Application is registered with APP id and Secret key and may be where the origin request is arises and handled.
  • Provide appId and Secret Key for Application.where the app developer just pass them via Header
  • [may be sometimes they have permissions if it is a Big Company like Facebook,Google,Twitter
  • And Action to be perform is passed via Body part with data to be processed.
  • Return Success/Error messages with Data to application in JSON/XML format
The above steps are basic simple but there are lot of methods to be followed for full Fledged API platform to run with performance.

Scope:

My Application will pull data from Server which is managed by Node.js as Backend Server Responding the Requests!

Warning:

  • This is just Basic Model Of pulling data from server to display at cross platform application.
  • I haven't enabled any HMAC Security and any other securing features to authenticate.
  • I am using Express Framework 4.x.x version since it is handy for me.
  • I am versioning the API via URL for my easiness.There are lot of controversies in this versioning API via URL/or body part!

Node.js Express Backend:


First of All let me Create a Simple routes that can respond with JSON format data and accepting inputs via body and headers.

package.json

{
"name":"SampleRestAPI",
"description":"Basic Web Service",
"version":"0.0.1",
"private":true,
"dependencies": {
              "express": "~4.x.x",
               "body-parser": "*",
              "mongoose": "~3.8.11"
  }
}

server.js:


Important part is to create routes for your application and which can determine to give away resource! Rest API is meant for that! Asking for resource via HTTP methods. :)
simple examples of creating routes for ur application:


app.get("/",function(req,res)
{
      //get movies list data
});
app.post("/year",function(req,res)
{
        //filter year wise result movie
});
app.post("/create",function(req,res)
{
      //create new movie in Database
});
app.put("/update",function(req,res)
{
     //update certain part of the object(movie)
}
app.delete("/delete",function(req,res)
{
     //delete object(movie)
}



So,from the above Routes created , you may get some idea to build yours,there are lot of techniques in routing in express,if you can manage it apply and make it,others simply you can use and further learn more about creating complex application routes[Express 3.x.x] version
And Finally respond your client with the JSON data appropriately using res.json method

Creating Database for Back End Data Handling With MODULUS.io:


Since we are going to handle a considerable amount of Data lets have simple schema holding recent film,2014 films and love.horror movies in single schema document with sub-document.


Create A account in modulus.io for free Mongoose Database hosting.It is actually free but we wont use it upto such extent! :)



  • Create An account with your email account
  • Create New -> Database service
  • Select preferred Hosting such as Amazon/Joyent
  • and give Database Name , here Database Username/Password is very important.
  • After creating they will provide a URL to connect to your database

mongodb://<username>:<password>@proximus.modulusmongo.net:27017/zzzzzzz


The Above GIven URL is for example ,you may get different Domain ,Port number and Database unique ID


database.js :



Sample DB from modulus.io
This is created for connecting your schema to Hosted DB and transferring of Data from application to Database and reverse to :)


 module.exports = {'url' : 'mongodb://<username>:<password>@proximus.modulusmongo.net:27017/zzzzzz};

server.js Additional to Routes :

Let me explain the logic of Database query here,Btw we connected to mongoose db with url connect() using the url.



  1. GET /  -  This route is used to request whole movie database with native function find() without passing any params and return type to client as JSON Format
  2. POST /create - this route is used to create new movie object and append to database and return user with unique id for the insert
  3. PUT /update - this route is used to update a movie by passing _id and necessary details to update.here findbyIdandupdate function is used to find id and update simultaneously.
  4. DELETE /delete - this route is used to delete a movie by passing a id and remove function is used to delete from our database
  5. POST /year - this route is used to search for particular year movie details using find() function and return as JSON[this can be done using GET method by passing params in url]



model.js:

var mongoose = require('mongoose');
var movie_api = mongoose.Schema({
    movie          : {
        name       : String,
        year         : String,
        director   : String,
        genre       : String,
        thumb      : String ,
        music       : String,
        rating       : Number ,
    }

});

//you can have methods here 
module.exports = mongoose.model('movie', movie_api);


Thus in Above model.js we have defined our database schema and how we are going to organize our data in mongoose database.



My Try over API from REST CLIENT :

Download the REST API Client from here. abd have a try.


  • Download the files and extract
  • execute npm install
  • run server.js file
  • try the API URL from client addons
  • report for errors/bugs [email protected] 

REST ADVANCED CLIENT CHROME ADDON - A try over my API


Note : I haven't validated any data from user and retrieve from DB.This is basic app for RESTful Webservice and not suitable for production mode.

Try the Demo files in your localhost/node.js hosting.if any error/suggestion/bug do comments below or mail me [email protected] or connect with me in FB/Twitter for help and other sorts.Share is care

1 comments:

shivasurya said...

Can you give me some helpful idea about Restapi with mysql as a back end front end IONIC and angular JS. Thanks in advance. :)

Post a Comment

feel free to post your comments! Don't Spam here!