Created
March 27, 2022 07:13
-
-
Save arisetyo/bf11949af17f6fc803b55059b5a3579c to your computer and use it in GitHub Desktop.
Accessing Google Sheet using NodeJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Example of a simple data request to a Google Sheet spreadsheet. | |
* Requirements: | |
* 1. Make sure the spreadsheet is public | |
* 2. Get an API key from Google Developer Console | |
*/ | |
const axios = require('axios'); | |
const apiKey = "YOUR_GOOGLE_DEVELOPER_API_KEY"; | |
/** | |
* example file: | |
* https://docs.google.com/spreadsheets/d/<GOOGLE_SHEET_ID>/edit#gid=0 | |
*/ | |
const sheetId = "GOOGLE_SHEET_ID"; | |
const sheetName = "Sheet1"; // <= this is a Google Sheet's default sheet name. You can rename it accordingly. | |
const range = "A2:C11"; // <= select the cells that contain tabular data or data you want to retrieve | |
const endpoint = "https://sheets.googleapis.com/v4/spreadsheets"; // <= Google Sheet API endpoint | |
/** | |
* An example method of getting data | |
* and then write it on console. | |
* You can modify it to your need. | |
*/ | |
const getData = async () => { | |
let result = null; | |
const api_endpoint = `${endpoint}/${sheetId}/values/${sheetName}!${range}?key=${apiKey}`; | |
await axios.get(api_endpoint) | |
.then(response => { | |
if (response.status === 200) result = response.data; | |
}) | |
.catch(thrown => { | |
console.log("failed to get data from Google Sheet, thrown:", thrown) | |
}); | |
// write the result to console | |
console.log(result); | |
} | |
getData(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment