Basic REST API GET Call Using JSON


This is a basic REST API call that parses out JSON data and returns it back to you. To do a POST request using JSON data, check out the Basic REST API POST Request Using JSON 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. For a GET request, you'll want to pass in method: 'get' as an option.

UrlFetchApp.fetch(url, {method: 'get'})

Parsing the Response Data

Once you've recieved the response, you won't be able to read the data just yet. The raw response contains a bunch of methods within it, but the one that carries the data you seek will be .getContentText(). This method will give you back the raw JSON data from the API response. To read it, you'll need to run it through JSON.parse()

const response = UrlFetchApp.fetch(url, {method: 'get'}) const responseData = response.getContentText() const parsedData = JSON.parse(responseData)

From there, you can do whatever you need with the parsed data - such as referencing the objects within it.

Making it Easy to Use

Here's a pre-written function that helps you make a GET request to an API where the only thing you need to do is pass through the URL of the API Endpoint.

function basicJsonApiGetRequest(url) { const result = JSON.parse(UrlFetchApp.fetch(url, {method: 'get'}).getContentText()) return result } // To run it, just call the function and pass in the API Endpoint basicJsonApiGetRequest('https://rickandmortyapi.com/api')

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 requesting data from 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