Web API With AJAX: Return Various Data Types From Web API Service

In this article we will see the real beauty of the Web API.

You are in the "Web API with AJAX" article series. In our previous articles we have understood various concepts and the practical implementation of AJAX requests to the Web API. We have learned the concept of various HTTP verbs and the consumption of a Web API service using those verbs using the ajax() jQuery function. You can go through all of them by navigating to the following links.

    In this article we will see the real beauty of the Web API, Ha..Ha.., Yes the Web API is quite beautiful without make-up (read configuration) than other services like WCF and a traditional WebService. That's nice, but the real power of the Web API is that it's content type negotiation. In other words, it can serve any type (Oh, not any type but in a different flavor) content to the client end depending on the demand of the client and that's the demand of various electronic gadgets. Now a days people are using various portable devices to browse web applications and their demanded content type is also different and the Web API is smart enough to fulfill their demands. How? Please continue your job (reading).

    Return JSON data from Web API

    In this example we will learn to return JSON data from the Web API. Nothing to learn here, by default the Web API returns JSON data if the client does not specify any demand type. Have a look a the Web API part, we will not configure anything (in another example also) and we will tune only the client part. Here is a sample example.

    Implementation of Web API

    This is the Web API implementation. From the Get() method we are returning a collection of person classes. Pretty simple to implement.

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Net;

    using System.Net.Http;

    using System.Web.Http;

    using TestWEB_API.Models;

     

    namespace TestWEB_API.Controllers

    {

        public class person

        {

            public string name { get; set; }

            public string surname { get; set; }

     

        }

        public class ValuesController : ApiController

        {

            // GET api/values

            public List<person> Get()

            {

                List<person> List = new List<person>();

                person p1 = new person();

                p1.name = "Sourav";

                p1.surname = "Kayal";

                List.Add(p1);

                person p2 = new person();

                p2.name = "Sourav";

                p2.surname = "Kayal";

                List.Add(p2);

     

                return List;

            }

        }

    }

    Implementation of client part

    In the jQuery ajax() function we are not providing any content type or data type. So by default it will return JSON data as expected.

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="TestWEB_API.WebForm1" %>

     

    <!DOCTYPE html>

     

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head runat="server">

        <script type="text/javascript" src="Scripts/jquery-1.7.1.min.js"></script>

        <script>

            $(document).ready(function () {

     

                $("#click").click(function () {

                    $.ajax({

                        url: 'http://localhost:11129/api/values',

                        type: 'GET',

                        success: function (data, textStatus, xhr) {

                            console.log(data);

                        },

                        error: function (xhr, textStatus, errorThrown) {

                            console.log(textStatus);

                        }

                    }).done(function () {

     

                    });

     

                });

            });

        </script>

           

     

    </head>

    <body>

        <form id="form1" runat="server">

        <input type="button" id="click" value="click me" />

        </form>

    </body>

    </html>


    Oh yes. It's returning JSON data from the Web API. The data is in the form of a JavaScript object.

    Implementation of client part

    Return XML data from Web API

    Now in this example we will demand a XML representation of the data to the Web API. And again, for that we will not perform any extra make up for the Web API. Here is the code implementation.

    The client part is here that will call the Web API. And we are seeing that we have specified the dataType is "xml" and the contentType is "application/rss+xml"; in other words it's demanding XML data to the service application.

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="TestWEB_API.WebForm1" %>

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head runat="server">

        <script type="text/javascript" src="Scripts/jquery-1.7.1.min.js"></script>

        <script>

            $(document).ready(function () {

     

                $("#click").click(function () {

                    $.ajax({

                        url: 'http://localhost:11129/api/values',

                        type: 'GET',

                        dataType: 'xml',

                        ContentType:"application/rss+xml",

                        success: function (data, textStatus, xhr) {

                            console.log(data);

                        },

                        error: function (xhr, textStatus, errorThrown) {

                            console.log('a' + textStatus);

                        }

                    }).done(function () {

     

                    });

     

                });

            });

        </script>

    </head>

    <body>

        <form id="form1" runat="server">

        <input type="button" id="click" value="click me" />

        </form>

    </body>

    </html>

    The Web API part is the same as the example above. We did not make any changes here.
     

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Net;

    using System.Net.Http;

    using System.Web.Http;

    using TestWEB_API.Models;

     

    namespace TestWEB_API.Controllers

    {

        public class person

        {

            public string name { get; set; }

            public string surname { get; set; }

     

        }

        public class ValuesController : ApiController

        {

            // GET api/values

            public List<person> Get()

            {

                List<person> List = new List<person>();

                person p1 = new person();

                p1.name = "Sourav";

                p1.surname = "Kayal";

                List.Add(p1);

                person p2 = new person();

                p2.name = "Sourav";

                p2.surname = "Kayal";

                List.Add(p2);

     

                return List;

            }

        }

    }

    Ok, in the output, we are getting data in the form of XML. Now it's the client application's duty to parse and process it.

    Return XML data from Web API

    Get data in plain text format

    There might be some client that likes neither JOSN nor XML, it's taste is different and it's like plain text data. The Web API is also capable of fulfilling their demand. Here is the sample example of that.

    The implementation of the client part is here, we are seeing that the dataType is "text", in other words the client application demands data in plain text format.

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="TestWEB_API.WebForm1" %>

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head runat="server">

        <script type="text/javascript" src="Scripts/jquery-1.7.1.min.js"></script>

        <script>

            $(document).ready(function () {

                $("#click").click(function () {

                    $.ajax({

                        url: 'http://localhost:11129/api/values',

                        type: 'GET',

                        dataType: 'text',

                        ContentType:"application/xml",

                        success: function (data, textStatus, xhr) {

                            console.log(data);

                        },

                        error: function (xhr, textStatus, errorThrown) {

                            console.log('a' + textStatus);

                        }

                    }).done(function () {

     

                    });

     

                });

            });

        </script>

    </head>

    <body>

        <form id="form1" runat="server">

        <input type="button" id="click" value="click me" />

        </form>

    </body>

    </html>


    Still we did not change our API implementation.

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Net;

    using System.Net.Http;

    using System.Web.Http;

    using TestWEB_API.Models;

     

    namespace TestWEB_API.Controllers

    {

        public class person

        {

            public string name { get; set; }

            public string surname { get; set; }

     

        }

        public class ValuesController : ApiController

        {

            // GET api/values

            public List<person> Get()

            {

                List<person> List = new List<person>();

                person p1 = new person();

                p1.name = "Sourav";

                p1.surname = "Kayal";

                List.Add(p1);

                person p2 = new person();

                p2.name = "Sourav";

                p2.surname = "Kayal";

                List.Add(p2);

     

                return List;

            }

        }

    }

    Ok, the data is coming in "text" format. Look, the style of the representation is the JSON format but it's type is plain text, not in the form of a JavaScript object.

    Get data in plain text format

    Conclusion

    The more you demand, the more you get. The expectation from people is coming to the IT farm, expectation from the IT farm is coming to developer and the expectation from developers is coming to Service-based applications. Ha..Ha.. Be happy, Keep Happy.