All Articles

Sending XML SOAP Requests With Axios


Problem

Summary

  • You’re faced with the challenge of make a SOAP request for the first time.
  • The recommended NPM packages to make the SOAP request don’t work.

Solution

Depending on the SOAP API you’re addressing, it could be as simple as this:

const res = await axios.post(soapURL, xml, {
  headers: {
    'Accept-Encoding': 'gzip,deflate',
    'Content-Type': 'text/xml;charset=UTF-8',
    'SOAPAction': 'provider_soap_request_type', // this may be required or not, depending on the wsdl setup
  },
});

In this example:

  • The soapURL is provided by the endpoint provider
  • xml is the string form of the xml required for the request

We can handle XMLs easily in Javascript using two separate npm packages, one to generate XML and one to parse XML.

  • xmlbuilder for creating
  • xml2js for parsing

Here’s how you create the xml:

const xml = xmlbuilder
  .begin()
  .ele({
    'soapenv:Envelope': {
      '@xmlns:soapenv': 'http://schemas.xmlsoap.org/soap/envelope/',
      '@xmlns:api': 'your_provider_soap_api',
      'soapenv:Header': {},
      'soapenv:Body': {
        'api:your_soap_api_endpoint': {
          sessionId: '1234-XYY',
          userId: 123,
          ...,
        },
      },
    },
  })
  .end();

The exact keys required depends on the xml nodes you need for your request, but it should look fairly similar to the above.

You can pass the xml created by xmlBuilder as the xml argument in the axios code above.

When you get the response…

const parsedResponseToJS = await xml2js
  .parseStringPromise(res.data, { explicitArray: false, ignoreAttrs: true });

parsedResponseToJS will be a JS object representation of the XML, ready for you to validate and user in your code.

Problem Solved?

If you have any questions you’d like to ask me about this post, feel free to reach me on Twitter or Github.

If you found this post useful and would like to show you’re appreciation, join the Brave movement and send me a tip :)