Basic REST API Request Call Using XML


This is a basic REST API call that parses out XML data and returns it back to you. To do a POST request using XML data, check out the Basic REST API POST Request Using XML how-to guide.

The Basics

With Google Apps Scripts, you can use a built-in library called UrlFetchApp which contains a method called .fetch(). This .fetch() method accepts two parameters - the first is the URL you want to make the API request against and the second is an object for your "options" which could include the headers options and any other options you need. In this case, you'll want to make sure that the content-type is set to "application/xml" and that the method is set to "get".

UrlFetchApp.fetch(url, {headers: {"Content-Type": "application/xml"}, method: 'get'})

Parsing the Response Data

Once you've recieved the response, you won't be able to read the data just yet. You'll need to parse the data using XmlService.parse() before you can do anything with it.

const response = UrlFetchApp.fetch(url, {headers: {"Content-Type": "application/xml"}, method: 'get'}) const responseData = XmlService.parse(response)

After using XmlService.parse() you'll be able to use additional commands like .getRootElement() and .getChldren() to parse through your XML data's elements. Here's a good way to see what you're working with:

console.log(result.getRootElement().getChildren().map(element => element.getText()))

Making it Easy to Use

This is a pre-written function that helps you make a GET request to an API that returns XML structured data where the only thing you need to do is pass through the URL of the API Endpoint.

function basicXmlApiGetRequest(url) { const result = XmlService.parse(UrlFetchApp.fetch(url, {headers: {"Content-Type": "application/xml"}, method: 'get'})) console.log(result.getRootElement().getChildren().map(element => element.getText())) return result } // // To run it, just call the function and pass in the API Endpoint along with your payload basicXmlApiGetRequest('https://mocktarget.apigee.net/xml')

Being able to make an API request in Google Apps Script is a powerful tool to have in your arsenal. This basic get request will cover the majority of API requests you need to make to get data that you can use in Google Sheets, Docs, or Slides.

Keep in mind that you may need to include an API Key in your url params or an 'Authorization' variable to your headers if the API you're connecting to requires authentication. Some APIs require OAuth2.0 authentication, which is something we cover in our video guide for accessing the Google Search Console API.

thumbnail

NitroGAS Chrome Extension

Want to reference this code snippet right from your Google Apps Script Project? Check out our NitroGAS Chrome Extension. This tool will help you build your scripts faster than you could imagine. The tool itself and access to the code snippets are 100% FREE - Happy Coding!

Get the Extension