In the previous blog, we have seen “What is SOA (Service Oriented Architecture)?“
In this blog, we will see in detail about Web Services, SOAP-based web services, and RESTful web services. You may also see one of my blogs WCF vs Web Services.
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 detail.
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 the other hand, a response is based on an input. In web service, all communication format is XML based which we call SOAP (Simple Object Access Protocol) message.
So there will be two objects one will be a client which will raise a 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 to access the 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. This web service is heavier than the REST web service. SOAP is an XML-based web service. SOAP contains the 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 security known as WS-Security.
A few important points about SOA, SOAP and REST:
SOA is a software architecture where 2 components/machines communicate with each other.
One is a consumer and the 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 consumers can query against this directory which tells what services are available and how to communicate.
WSDL – Web Service Description Language
WSDL is an XML document that describes web services. So the service provider will communicate with the service description using SOAP protocol. The consumer will query from the 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 systems happens only in XML format. XML data requires parsing to read, so it is slow and consumes more bandwidth.
- Supports XML only as the 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, it sends a request and the server responds to that request. This response is the representation of a resource which can be in HTML, XML, JSON, or Plain Text format.
As we know REST is a style, that can use any protocol like HTTP, or SOAP.
REST is stateless and cacheable.
Characteristics of RESTful Web Service
- Fixed URI or Uniform Interface – The 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 – The client can re-use the 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, and JSON as data exchange formats.
You may read this – How to create WCF RESTful service?
The advantage of REST over SOAP is that in REST clients have direct access to a resource in the form of URI, whereas SOAP WSDL require to access service.
How to create a SOAP-based Web Service?
To create SOAP web service follow the below steps:
Open Visual Studio, File->New Website
Once the website is created in the visual studio, Right-click on Project in Solution Explorer and select Add a new item. Select Web Service from the given options, give a name MyWebWervice.asmx
Write the 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 the address bar and click on GO. Your web service should appear below.
Change the namespace if wish to change, and click on OK.
Below is the code to consume the 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 a custom SOAP header.
CRUD operation in REST Services
REST – It stands for Representational State Transfer and access web service through URI. REST web service includes 4 main methods.
GET – To get or retrieve data.
POST – To create a 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 more lightweight than SOAP web service.
Summary: In SOAP requests data are sent in XML format, but REST uses an HTTP request.
In SOAP XML requests are processed but in REST parameters are processed.
SOAP returns XML response, and REST returns JSON, Plain Text and XML format.
It 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, and number 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, and SMTP as transport protocols.
Differences between REST and SOAP | REST vs. SOAP
In the 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 does not have a concept called WSDL | SOAP uses WSDL to describe web services |
What are the similarities between SOAP and REST?
To build an application, we need different programming languages, frameworks, architectures, and platforms. Sharing data between different technologies is not an easy task because they have different data formats. Both SOAP and REST emerged in an attempt to solve this problem.
Here are a few similarities between SOAP and REST:
- SOAP and REST both use HTTP protocol to exchange data
- They both describe protocols and standards on how applications process the data and respond to data requests from other applications
Conclusion
In this article, we learnt about Web services and its type which are REST and SOAP. SOAP is a protocol and REST is an architectural style. Currently, SOAP is less preferable to REST. SOAP uses XML data formats while REST uses HTML, XML and JSON as data formats.