From SOAP to REST to GraphQL: API Deep Dive

API Tutorial

When working with APIs, developers have several choices as far as protocols and specifications are concerned. You can use SOAP, REST, or GraphQL – three of the most popular approaches to build APIs and define the semantics and syntax of the messages that would be transferred over the wire.

Read: Productivity Tools for .NET Developers

SOAP is a long-established and well-known protocol that is popular primarily due to its simplicity and ease of use. REST is another approach for building lightweight, HTTP-based APIs that has gained popularity due to its flexibility. GraphQL is the newest of these three and promises to provide an even more flexible way of working with data.

In this API programming tutorial, we will take a deep dive into SOAP, REST, and GraphQL and how they compare against each other.

What is Simple Object Access Protocol (SOAP)?

Simple Object Access Protocol (SOAP) is a widely popular protocol that uses XML for data exchange. It is an XML-based protocol that was created in the late 1990s for exchanging data in a distributed and decentralized manner.

The primary distinction between SOAP and REST is that the former focuses on verbs while the latter focuses on resources. REST defines certain constraints and uses a consistent interface to work on them using the HTTP verbs. SOAP is easy to use and understand, which makes it a good choice for many developers.

Example of a SOAP Message

A SOAP message is encoded as an XML document and comprises the following elements:

  • SOAP messages include an envelope element that specifies the start and end of the message
  • An optional element that is used to define the header of the SOAP message
  • A mandatory body that represents the body of the SOAP message
  • An optional fault element that is used to represent any errors that might occur while processing the SOAP message

Here is an example of how a SOAP message format typically looks:

<SOAP: Envelope>
  <SOAP: Header>
  </SOAP: Header>
  <SOAP: Body>
  </SOAP: Body>
</SOAP: Envelope>

Read: Creating SOAP Web Services with JAX-WS

What are the Benefits of SOAP?

Distributed Applications are built to support heterogeneous platforms. They require a standard data exchange format for exchanging data between homogeneous and heterogeneous platforms. Remember, the technologies used for data exchange before the advent of SOAP were DCOM, RPC, IIOP, etc., which were constrained to a homogenous platform only. Here is where Simple Object-Oriented Protocol (SOAP) comes into play.

What is Representational State Transfer (REST)?

Representational State Transfer (REST) is an architectural paradigm for building high-performance, scalable services. In other words, it is an architectural style for designing web services. It is based on the idea of resource-oriented architecture, where resources are identified by their URI (Uniform Resource Identifier).

In other words, it is based on the idea of resources, which are identified by URLs. These resources can be manipulated using a set of well-defined operations that include GET, POST, PUT, and DELETE.

REST defines certain constraints to help build the design and architecture of modern-day web applications that run over Http. These constraints include the following:

  • Uniform interface
  • Cacheable
  • Stateless
  • Layered System
  • Client-Server Architecture

A RESTful Web Service adheres to the REST design constraints mentioned above. The following code snippet illustrates a typical RESTful service:

[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
    [HttpGet]
    public List Get()
    {
      //Write your code here to return all user records
    }
    [HttpGet("{id}", Name = "Get")]
    public string Get(int id)
    {
      //Write your code here to return an user record based on the id
    }
    [HttpPost]
    public void Post([FromBody] UserDTO user)
    {
      //Write your code here to insert an user record to the database
    }
    [HttpPut("{id}")]
    public void Put(int id, [FromBody] UserDTO user)
    {
        //Write your code here to update an user record
    }
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
       //Write your code here to delete an user record
    }
}

What are the Benefits of REST?

One of the main benefits of REST is that it enables developers to create web services that are scalable and easy to maintain. REST also allows for a greater degree of flexibility when it comes to how data is represented and accessed.

The REST architectural style has swiftly gained popularity across the globe for creating and architecting applications that use the HTTP protocol. Because of its simplicity, REST has achieved considerable popularity globally in place of SOAP and WSDL-based web services.

You can learn more about the REST in our tutorial: An Introduction to Representation State Transfer (REST).

What is GraphQL?

GraphQL is a modern query language developed by Facebook for working with APIs. It provides a more flexible way to query data than REST and SOAP, and it is slowly becoming the standard for API development. GrahQL addresses the over-fetching and under-fetching problems often encountered in RESTful applications.

GraphQL is a powerful query language that can be used to access data from any API. It is based on the concept of a graph, which is a collection of nodes (vertices) and edges (links). You can leverage GraphQL to query data from any data source, including databases, file systems, and even other APIs.

The following code snippet illustrates how you can use GraphQL in C#:

    public class UserDTO
    {
        [GraphQLType(typeof(NonNullType))]
        public int Id { get; set; }
        [GraphQLNonNullType]
        public string UserName { get; set; }
        [GraphQLNonNullType]
        public string Password { get; set; }
    }

Here’s the GraphQl query to retrieve all users:

query {
  allUsers{
    id
    firstName
    lastName
  }
}

When Should You Use SOAP, REST, or GraphQL?

There are a few key differences between SOAP, REST, and GraphQL that will help you decide which one to use for your project.

Protocol

Any transport protocol can be used to access a SOAP-based service, including TCP/IP, UDP, SMTP, and HTTP. Thus, SOAP-based services are not restricted to the HTTP protocol. REST is defined as an architectural style based on the concept of resources and uses HTTP for its communication protocol.

Message Format

SOAP is a protocol that uses XML for its message format. This makes it very verbose and can be difficult to parse. Hence, it also means that SOAP messages are self-describing, making them ideal for use in distributed environments.

REST (Representational State Transfer) is a more modern approach that uses JSON for its message format. REST messages are usually represented as JSON but they are not self-describing, making them less ideal for use in distributed environments.

Mobile Apps

Some of the benefits of SOAP include language and platform neutrality, and simplicity. However, SOAP is not well suited for mobile applications since SOAP messages are verbose and convoluted.

GraphQL is a newer technology that was developed by Facebook and uses JSON for its message format. GraphQL messages are self-describing, making them ideal for use in distributed environment. GraphQL can be used to retrieve data from multiple sources at once making it well suited for mobile applications that often need to load data from multiple API’s.

REST is light-weight since it uses JSON format for data exchange making it well suited for mobile applications.

Performance

In terms of performance, GraphQL is the clear winner amongst these three. It is able to fetch data much faster than both SOAP and REST. This is because it only fetches the data that is requested, rather than loading an entire dataset. In other words, it allows you to query exactly the data that you need – nothing more or less. This can be a huge benefit when working with large amounts of data, as it can help to reduce the amount of data that needs to be transferred.

Final Thoughts on SOAP, REST, and GraphQL

So, which of the three should you use for your web service? If you need maximum compatibility, then SOAP is the way to go. In general, you should use SOAP when you need a very robust and self-describing message format.

REST APIs are the most popular choice for public APIs, while SOAP and GraphQL are better suited for private or enterprise applications. If you want better performance and scalability, then REST or GraphQL would be a better choice.

Read: Best Practices to Design RESTful APIs

Joydip Kanjilal
Joydip Kanjilal
A Microsoft Most Valuable Professional in ASP.NET, Speaker, and Author of several books and articles. More than 25 years of experience in IT with more than 18 years in Microsoft .NET and its related technologies. He was selected as a Community Credit Winner at http://www.community-credit.com several times. He has authored 8 books and more than 500 articles in some of the most reputed sites worldwide including MSDN, Info World, CodeMag, Tech Beacon, Tech Target, Developer, CodeGuru, and more.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read