fetch xml from api in typescript

To fetch XML from an API in TypeScript, we can use the fetch method provided by the window object. We can then use the response.text() method to read the response as a string, and then use a third-party XML parsing library to convert the string into an XML object.

Here's an example code snippet:

index.ts
// Make a GET request to the API endpoint
fetch('https://api.example.com/data.xml')
  .then(response => response.text())
  .then(xmlString => {
    // Use a third-party XML parser to convert the string into an XML object
    const parser = new DOMParser();
    const xmlDoc = parser.parseFromString(xmlString, 'text/xml');

    // Now, you can use the xmlDoc object to access the XML data
    const nodes = xmlDoc.getElementsByTagName('node');
    console.log(nodes.length);
  })
  .catch(error => console.error(error));
521 chars
14 lines

In the example above, we first make a GET request to the API endpoint using the fetch method. We then use the text() method to read the response body as a string.

Once we have the response body as a string, we use the DOMParser object to parse it into an XML object. We can then use this XML object to access the data in the response.

Note that the fetch method returns a Promise, so we can use then() and catch() to handle success and error cases respectively.

gistlibby LogSnag