GraphQL with BizTalk

Tanguy Schoubert
Published by Tanguy
Category : BizTalk
02/07/2019

To communicate with APIs, the message format generally used by Microsoft BizTalk Server is XML or Json. There are indeed some native pipeline components which allows us, while both sending and receiving, to convert from XML to Json and from Json to XML as well: the Json encoder & decoder.

However, the GraphQL query language is more and more used by APIs. The goal of this article is therefore to show a way to communicate from BizTalk to an API in GraphQL.

 

Generate GraphQL format

The first step is to generate the Json equivalent of the GraphQL request we want to send. To achieve that, I use Insomnia. Here is an example of a GraphQL request. Its goal is to get an ID from an order reference:

 

{  order(ref: "XXX") {    fulfilments {      edges {        node {          id        }      }    }  }}

 

To switch the format from GraphQL to Json in Insomnia:

 

 

The equivalent message generated is the following:

 

{"query":"{  order(ref: \"XXX\") {    fulfilments {      edges {        node {          id        }      }    }  }}"}

 

Create XSD schema in BizTalk

We have now to create this message in BizTalk. To do that, several options:

  • Define a xsd that matches the message structure, create the message with a map then use the pipeline component Json encoder
  • Use a helper to directly create the message from the orchestration

 

To decide here, we have to consider which flexibility we want. With the helper, the structure of the request – and particularly the name of the fields – is entirely customizable. Note that we can do that with a full xsl map as well.

In this example we use a helper. Taking in account escape characters, here is the content of the message construct shape with the order reference as a predefined variable:

 

msgIdRequest = new System.Xml.XmlDocument();
Helper.LoadXLANGMsgFromString("{\"query\":\"{  order(ref: " + OrderReference + ") {    fulfilments {      edges {        node {          id        }      }    }  }}\"}", msgIdRequest);

 

And in the helper:

 

public static void LoadXLANGMsgFromString(string source, XLANGMessage dest) {
   var bytes = Encoding.UTF8.GetBytes(source);
   using (MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length, false, true)) {
      dest[0].LoadFrom(ms);            
   }
}

 

Here the role of the helper is only to generate a XLANG message from a string. But it could be used to contain a more complex logic for the request creation, based on parameters passed from the orchestration for instance.

 

Setting the BizTalk Server pipeline

In regards to the bindings, we set a send pipeline PassThruTransmit. In reception, a pipeline containing a Json decoder and a XML Disassembler will allow us to parse the response message (a xsd must first be defined) and finally to get the ID that we want using a xpath request for example.