All about Web Service, SOAP and RESTful Service

In the previous blog, we have seen "What is SOA (Service Oriented Architecture)?"
In this blog, we will see in details about Web Services, SOAP-based web service, and RESTful web service. You may also see one my blog WCF vs Web Services.

Let's start by exploring our first topic  - 

What is a Web Service?

Web service is a way to communicate between 2 machines via HTTP, those 2 machines can be on a different platform.

SOAP vs RESTful Service

Let's understand this in details.
As you know any communication consists of medium and response. Same in web service, the medium of communication could be LAN, the Internet using HTTP. On another side, a response is based on an input. In web service, all communication format is XML based which we call it SOAP (Simple Object Access Protocol) message.

So there will be two objects one will be a client which will raise request (also consume the service) and a server which will give the response (i.e. output) for the raised request.

Web service collects all the details in an XML file called WSDL(Web Services Description Language).
This WSDL file must be accessible to the client in order to access web service.

UDDI - UDDI stands for Universal Description Discovery and Integration. UDDI is a web directory for a service provider who wants to make their services available publicly.

Types of Web service

Web services are of 2 types. SOAP and REST.


What is SOAP?

SOAP - SOAP stands for Simple Object Access Protocol. SOAP web service is heavier than REST web service. SOAP is XML based web service. SOAP contains below elements.
  • An envelope which defines the XML document. 
  • Header - It contains header information.
  • Body - It contains the response information.
  • Fault - It contains fault and error information.
SOAP has its own security known as WS-Security.

Few important points about SOA, SOAP and REST:

SOA is a software architecture where 2 components/machines communicate with each other.
One is consumer other is a provider.

Web service is the implementation of SOA.

In web service, a service provider publishes its service description to a directory and consumer can query against this directory which tells what services available and how to communicate.

WSDL - Web Service Description Language

WSDL is an XML document that describes web service. So service provider will communicate service description using SOAP protocol. The consumer will query from service description using the same protocol.

Advantages of SOAP web service

  • Inbuilt WS-Security
  • Language and Platform independent

Disadvantages of SOAP web service

  • As we all know SOAP is an XML based protocol, data exchange between 2 system happens only in XML format. XML data require parsing to read, so it is slow and consumes more bandwidth.
  • Supports XML only as data exchange format

REST - Representational State Transfer

Now, we will try to make a point to understand What REST is?
Representation State Transfer - So, what does that mean? Simply, REST is just an architectural style to build and loosely couple 2 or more systems. In today's fast-growing and connected IT world REST API is playing a vital role in the web world.
REST says each resource should be accessed by URI.
In REST client sends a request and server responds to that request. This response is the representation of a resource which can be in HTML, XML, JSON, Plain Text format.

As we know REST is a style, so it can use any protocol like HTTP, SOAP.
REST is stateless, cacheable.

Characteristics of RESTful web service

  • Fixed URI or Uniform Interface - Client server communicates over a given URI. This is an identifier that we can use to access a resource. A resource could be anything like a record, a document, an image
  • Stateless - A fundamental principle of REST architecture is Stateless. The Server does not store any state or information about the client. It means every request is treated as unique and fresh.
  • Cacheable - Client can re-use response if it is cacheable. Several round trips can be saved by using the cache.

Advantages of RESTful web service

  • RESTful web service is faster than SOAP, RESTful web service consumes less bandwidth.
  • RESTful web service can also use SOAP because SOAP is a protocol and REST is an architectural style.
  • Supports XML, plain text, JSON as data exchange format.
You may read this - How to create WCF RESTful service?

The advantage of REST over SOAP is that in REST client have direct accesses to a resource in form of URI, wherein SOAP WSDL require to access service.

How to create a SOAP-based Web Service?

To create SOAP web service follow below steps:

Open Visual Studio, File->New Website
Once web site created in the visual studio, Right Click on Project in Solution Explorer and select add a new item. Select Web Service from given options, give a name MyWebWervice.asmx
Write below code in MyWebService.asmx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;

/// <summary>
/// Summary description for MyWebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.None)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
 //[System.Web.Script.Services.ScriptService]
public class MyWebService : System.Web.Services.WebService {


    [WebMethod(MessageName="Get By Employee ID")]
    public string GetEmployee(int employeeId)
    {
        string empName = string.Empty;
        //write code and get employee name
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
        string query = "select employee_name,employee_department, employee_designation from employee where id = '" + employeeId + "'";
        SqlCommand cmd = new SqlCommand(query, con);
        con.Open();
        SqlDataReader dr = cmd.ExecuteReader();
       string empname = string.Empty;
        while (dr.Read())
        {
            empname = dr["employee_name"].ToString();
        }
        return empname ;
    }    
}



Now our SOAP web service is ready for consumption. To consume this service create a console application and name this project "SOAPClientDemo".

Right-click on the project and select "Add Service Reference", Enter web service URL in address bar and click on GO. Your web service should appear below.

Change namespace if wish to change, and click on OK.

Below is the code to consume web service.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SOAPClientDemo.ServiceClient;

namespace SOAPClientDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            MyWebServiceSoapClient objClient = new MyWebServiceSoapClient();
            string name = objClient.GetEmployee(1);
            Console.WriteLine(name);
        }
    }
}

Run this console application and it will display Employee Name for Employee ID which will be passed in GetEmployee method.

SOAP web service can be secured to avoid unauthorized access, this can be achieved by custom SOAP header.



REST - Representational State Transfer. REST access web service through URI. REST web service includes 4 main methods.

GET - To get or retrieve data.
POST - To create record
PUT - To update data
DELETE - To delete data

REST web service is less secure than SOAP web service as REST services are exposed over URI, but REST services are light weighted than SOAP web service.

Summary:  In SOAP request is sent to XML format, but REST uses HTTP request.
In SOAP XML request is processed but in REST parameters are processed.
SOAP returns XML response, REST returns JSON, Plain Text and XML format.
SOAP supports HTTP and SMTP as well.
SOAP uses HTTP Post, REST uses HTTP verbs (GET/PUT/POST/DELETE)
REST can be consumed by any client such as a browser by using AJAX and JavaScript.

Some more info about Web Service:

Using Session in Web service:
The class must inherit from System.web.Services.WebService

and an attribute should be like this:

[WebMethod(EnableSession=true)]
public void Do()
{
}



Web Method attribute properties:
Cache Duration - To cache the results of a web service method.
This is an integer value, which specifies the no. of seconds.

Method Overloading in Web Method


Method overloading can be done based on parameter type, no. of parameters.

[WebMethod(MessageName="Add 2 numbers")]
public int Add(int a, int b)
{
}

[WebMethod(MessageName="Add 3 numbers")]
public int Add(int a, int b, int c)
{
}


Calling ASP.Net Web Service from JavaScript using AJAX


Add below code:

<asp:scriptmanager id="SCriptManager1" runat="server">

<Services>

<asp:ServiceReference Path="~/MyWebService.asmx"/>

</Services>

</asp:scriptmanager>



<script>

function GetData()

{

var uid = document.getElementByID("txtUserID").value;

WebServiceNameSpace.WebUserServiceClass.WebMethod(id, OnSuccess, OnFail)

}



function OnSuccess(result)

{

document.getElementByID("txtValue").value = result["Value"];

}



function OnFail()

{

alert('There is an error');

}



</script>


Can SOAP be RESTful?

SOAP is a protocol so it can not use REST, whereas REST is a style and can use any protocol HTTP, SOAP etc.

SOAP can use HTTP, SMTP as transport protocols.

Differences between REST and SOAP | REST vs. SOAP

In below table, you may find the differences between REST and SOAP.

REST
SOAP
Representational State Transfer
Simple Object Access Protocol
REST is an architectural style
SOAP is an XML based protocol
REST is lightweight and faster than SOAP
SOAP is a traditional protocol but not faster than REST
REST is stateless
SOAP is stateful
REST do not have a concept called WSDL
SOAP uses WSDL to describe web services


Related Blogs -



Comments

Popular

What's new in C# 6.0 language - All new features of C# 6.0 for developers

SharePoint Interview Questions and Answers