Thursday 5 June 2014

Calling a MVC Web Api from Advance Rest Client Chrome

In this article we are going to see how to call a MVC web api from the Rest client, For do this first we have to create a MVC Web API with following HTTP methods GET, POST, PUT, DELETE

In the Following code we are taking a 4 GET methods
1 with returning a Complex object ,
1 which takes id as input and return the corresponding Student. along with url because id is mention in route config.
1 which takes name as input, values are submitted in query string.
1 which takes name , id as input, so one value is mapped in url, another one in Query string.

     // GET api/Student
        public IEnumerable<Student> Get()
        {
            AddData();
            return _students;
        }

        //GET api/student?name=rajesh
        public Student Get(string name)
        {
            AddData();
            return _students.Where(x => x.Name == name).FirstOrDefault();
        }

        // GET api/Student/1
        public Student Get(int id)
        {
            AddData();
            return _students.Where(x => x.Id == id).FirstOrDefault();
        }

        // GET api/student/1?name=rajesh
        public Student Get(int id,string name)
        {
            AddData();
            return _students.Where(x => x.Id == id && x.Name==name).FirstOrDefault();
        }

        private void AddData()
        {
            Department dep = new Department() { Id = 1, Name = "computer" };
            List<Marks> marks = new List<Marks>() { new Marks() { Mark = 85, 
           SubectName = "Computer" }, new Marks() { Mark = 78, SubectName = "Electronic" } };
            _students.Add(new Student() { Age = 12, Id = 1, Depart = dep, Name = "rajesh",              Rank = 1, Subjects = new string[] { "Computer", "Electronic" }, 
           SubMarks = marks });

        }




1 POST method which intakes the Complex object

        // POST api/Student
        public void Post([FromBody]List<Student> students)
        {
            _students.AddRange(students);           
        }


1 DELETE method

        // PUT api/Student/1
        public void Put(int id, [FromBody]Student value)
        {
            AddData();
            Student stud = _students.Where(x => x.Id == id).FirstOrDefault();
            stud = value;
        }

1 PUT Method with Authorization passing in header

        // DELETE api/Student/1
        public void Delete(int id)
        {
            string auth = Request.Headers.Authorization.Scheme;
            AddData();
            Student std = _students.Where(x => x.Id == id).FirstOrDefault();
            if(std!=null)
            _students.Remove(std);

        }


Full code :


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace mvcSAMPLE.Controllers
{
    public class Department
    {
        public string Name {set;get;}

        public int Id {set;get;}

    }

    public class Marks
    {
        public string SubectName {set;get;}

        public int Mark {set;get;}

    }

    public class Student
    {
        public int Id { set; get; }

        public string Name { set; get; }

        public int Age { set; get; }

        public string[] Subjects { set; get; }

        public Department Depart { set; get; }

        public List<Marks> SubMarks { set; get; }

        public int Rank { set; get; }

    }

    public class StudentController : ApiController
    {
        List<Student> _students = new List<Student>();

        // GET api/Student
        public IEnumerable<Student> Get()
        {
            AddData();
            return _students;
        }

        //GET api/student?name=rajesh
        public Student Get(string name)
        {
            AddData();
            return _students.Where(x => x.Name == name).FirstOrDefault();
        }

        // GET api/Student/1
        public Student Get(int id)
        {
            AddData();
            return _students.Where(x => x.Id == id).FirstOrDefault();
        }

        // GET api/student/1?name=rajesh
        public Student Get(int id,string name)
        {
            AddData();
            return _students.Where(x => x.Id == id && x.Name==name).FirstOrDefault();
        }

        private void AddData()
        {
            Department dep = new Department() { Id = 1, Name = "computer" };
            List<Marks> marks = new List<Marks>() { new Marks() { Mark = 85, SubectName = "Computer" }, new Marks() { Mark = 78, SubectName = "Electronic" } };
            _students.Add(new Student() { Age = 12, Id = 1, Depart = dep, Name = "rajesh", Rank = 1, Subjects = new string[] { "Computer", "Electronic" }, SubMarks = marks });

        }

        // POST api/Student
        public void Post([FromBody]List<Student> students)
        {
            _students.AddRange(students);           
        }

        // PUT api/Student/1
        public void Put(int id, [FromBody]Student value)
        {
            AddData();
            Student stud = _students.Where(x => x.Id == id).FirstOrDefault();
            stud = value;
        }

        // DELETE api/Student/1
        public void Delete(int id)
        {
            string auth = Request.Headers.Authorization.Scheme;
            AddData();
            Student std = _students.Where(x => x.Id == id).FirstOrDefault();
            if(std!=null)
            _students.Remove(std);
        }
    }

}


Route config:

       config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );



Chrome:
Now install the advance rest client in chrome.

In the Rest client three things are important
1. Url passing for request along with methods selected.
2. Passing the header information and Body information
3. Content Type selection

In our sample Content-Type is application/json , we will use the Body section on the POST method.

For the various Get Methods:

Default Get Method
url : http://localhost:53986/api/Student

Get with parameter 
paramter id:
url : http://localhost:53986/api/Student/1


parameter name:
url : http://localhost:53986/api/Student?name=rajesh






paramter id, name:
url : http://localhost:53986/api/Student/1?name=rajesh







For all the three queries we have the same output

Output:





POST Method 
url : http://localhost:53986/api/Student


FromBody we can only able to pass one parameter







In this post content we have to pass a complex object which is a list,now we are going to see how to pass a complex object for rest client.

For object we have to use {}
For array or List we have to use []
then next thing we have to place the property name as key in the left side with in double quotes and value in the right side of colon , string are mention in double quotes values , integer are as it is.


For example :
*************
Array or list of string to pass as a input to API then. ["Rajesh","suresh"]. 

If an object is need to be pass then  { "Name":"Rajesh","Age":10}

if an property is an array of another object then
"submarks" : [ {"Mark":80,"subject":"Computer"},{"Mark":97,"subject":"Electronic"} ]



POST content :

[
 {
   "Id"            :   1,
   "Name"      :   "Rajesh",
   "Age"         :   12,
   "Subjects"   :   ["Computer","Electronics"],
  "Depart"      :   {
"Name":"Computer Science",
"Id"  :1
                       },
  "SubMarks"  :   [
{ "SubectName":"Computer", "Mark":95 },
                          { "SubectName":"Electronics","Mark":84}
                       ],
  "Rank"          :  13
 },
{
   "Id"              :   2,
   "Name"        :   "Suresh",
   "Age"           :   8,
   "Subjects"    :   ["Computer","Electronics"],
   "Depart"       :  {
                              "Name":"Computer Science",
"Id":1
                       },
   "SubMarks"  :  [
{"SubectName":"Computer","Mark":100},
{"SubectName":"Electronics","Mark":100}
                       ],
   "Rank"  :  1
  }

]



Output:



















DELETE method
url : http://localhost:53986/api/Student/1








PUT Method 

url : http://localhost:53986/api/Student/1


From this article you can learn how to call the MVC web api from the rest client.


8 comments:

  1. I think you have a long story to share and i am glad after long time finally you cam and shared your experience.
    python training in pune | python training institute in chennai | python training in Bangalore

    ReplyDelete
  2. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.

    rpa training in velachery| rpa training in tambaram |rpa training in sholinganallur | rpa training in annanagar| rpa training in kalyannagar

    ReplyDelete
  3. Thank you for taking the time and sharing this information with us. It was indeed very helpful and insightful while being straight forward and to the point.

    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training

    ReplyDelete
  4. Attend The Python training in bangalore From ExcelR. Practical Python training in bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python training in bangalore.
    python training in bangalore

    ReplyDelete
  5. I feel there is a need to look for more and more aspects of SQL and other reasons to provide and look for more solutions like these.

    SQL Server Load Soap API

    ReplyDelete