Web API: All about

NodeJS

Installation

Usage

[js]
/* users.json
{
“user1” : {
“name” : “mahesh”,
“password” : “password1”,
“profession” : “teacher”,
“id”: 1
},
“user2” : {
“name” : “suresh”,
“password” : “password2”,
“profession” : “librarian”,
“id”: 2
},
“user3” : {
“name” : “ramesh”,
“password” : “password3”,
“profession” : “clerk”,
“id”: 3
}
}
*/
var express = require(‘express’);
var app = express();
var fs = require(“fs”);

app.get(‘/listUsers’, function (req, res) {
fs.readFile( __dirname + “/” + “users.json”, ‘utf8’, function (err, data) {
console.log( data );
res.end( data );
});
})

var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log(“Example app listening at http://%s:%s”, host, port)
})
[/js]

Javascript

How to call Restful API in JavaScript

[js]
var xmlhttp = new XMLHttpRequest();
var url = “http://domain.com/api/getEmployees&department=”;
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {

// Convert json to JS object
var myObj = JSON.parse(this.responseText);
}
};
xmlhttp.open(“GET”, url, true);
xmlhttp.send();
[/js]

ASP.NET MVC

Database connection

  • Define DB connection info in web.config
    [js]



    [/js]
  • Create DB connection class
    [js]
    private static DataTable ReturnTable(String strCmdText, SqlParameter[] sqlParams)
    {
    DataTable dt = null;
    try
    {
    using (SqlConnection conn = OpenConnection())
    {
    using (SqlDataAdapter sda = MakeDataAdapter(conn, strCmdText, sqlParams, true))
    {
    dt = new DataTable();
    sda.Fill(dt);
    }
    conn.Close();
    }
    }
    catch (Exception ex)
    {
    }

    return dt;
    }

    private static SqlConnection OpenConnection(String ConnectionString)
    {
    SqlConnection conn = new SqlConnection(ConnectionString);
    try { conn.Open(); }
    catch (Exception ex)
    {
    }
    return conn;
    }

    private static SqlConnection OpenConnection()
    {
    return OpenConnection(ConfigurationManager.AppSettings[“SqlDbConnectionString”]);
    }

    private static SqlDataAdapter MakeDataAdapter(SqlConnection sqlConn, String strCommandText, SqlParameter[] sqlParams, Boolean StoredProc)
    {
    if (sqlConn == null) return null;
    SqlDataAdapter sDa = null;
    try
    {
    sDa = new SqlDataAdapter(strCommandText, sqlConn);
    //sDa.SelectCommand.CommandTimeout = CommandTimeout();
    sDa.SelectCommand.CommandType = (StoredProc) ? CommandType.StoredProcedure : CommandType.Text;
    if (sqlParams != null)
    sDa.SelectCommand.Parameters.AddRange(sqlParams);
    }
    catch (Exception ex)
    {
    if (sDa != null) { sDa.SelectCommand.Cancel(); sDa.Dispose(); sDa = null; }
    }
    return sDa;
    }
    [/js]

  • Usage – Example of calling a stored procedure
    [js]
    SqlParameter[] prm = new SqlParameter[2];
    prm[0] = new SqlParameter(“@param1”, SqlDbType.BigInt);
    prm[0].Value = value1;
    prm[1] = new SqlParameter(“@param2”, SqlDbType.VarChar);
    prm[1].Value = value2;
    DataTable dt = ReturnTable(“stored_proc_name”, prm);
    [/js]

Create an API

  • Create Model: Data to be called by APIs are defined in Model
    [js]
    namespace AppName.Models
    {
    public class Employer
    {
    public string name
    {
    get;
    set;
    }

    public string adrress
    {
    get;
    set;
    }
    }

    public class Employee
    {
    public string name
    {
    get;
    set;
    }

    public IList data
    {
    get;
    set;
    }

    public class Info
    {
    public string age
    {
    get;
    set;
    }

    public string department
    {
    get;
    set;
    }
    }
    }
    }
    [/js]

  • Create API controller: Request coming from client hits the controller first. Then the controller decides which model to use to serve the incoming request.
    In order to make things simple, we can load the model with data inside this controller instead of loading it from database.
    [js]
    namespace AppName.Controllers
    {
    public class APIExampleController : ApiController
    {
    [HttpGet]
    [Route(“api/APIExample/GetEmployee”)]
    public IList GetEmployee()
    {
    // Access stored proc
    SqlParameter[] prm = new SqlParameter[0];
    DataTable dt = ReturnTable(“return_employee”, prm);

    // Parse to json
    IList arrEmployee = new List();
    if (dt != null)
    {
    Employee item = new Employee();
    item.name = “AAAA”;
    IList subObject = new List();
    for (int i = 0; i < dt.Rows.Count; i++) { Employee.Info subitem = new Employee.Info(); subitem.age= dt.Rows[i]["age"].ToString(); subObject.Add(subitem); } item.data = subObject; arrEmployee.Add(item); } return arrEmployee; } } } [/js]

Be the first to comment

Leave a Reply

Your email address will not be published.


*