Readme

Wrapper around Google Sheets API v4. You will need:

  • a Google Cloud service account
  • the Google Sheets API v4 enabled in your Google Cloud project
  • the spreadsheet ID (provide it in the sheetId parameter)
  1. Share the spreadsheet with the service account
  2. Make a JSON key for the service account, minify it and set it as a secret.
  • Use the secret for the serviceAccount parameter.
  1. Figure out the action you want to perform.
  • You will need to provide everything that comes after {spreadsheetId}/ as the action parameter. For example: values/A1:C1:append?valueInputOption=RAW
  1. Figure out the request body. For example: {values: [["foo", "bar", "baz"]]}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { fetchJSON } from "https://esm.town/v/stevekrouse/fetchJSON?v=41";
type Args = {
serviceAccount: string;
sheetId: string;
action: string;
data: object;
};
export async function callGoogleSheetsAPI(
{ serviceAccount, sheetId, action, data }: Args,
) {
const { getToken } = await import(
"https://deno.land/x/google_jwt_sa@v0.2.3/mod.ts"
);
const googleAuthOptions = {
scope: ["https://www.googleapis.com/auth/spreadsheets"],
};
const { access_token } = await getToken(serviceAccount, googleAuthOptions);
const result = fetchJSON(
`https://sheets.googleapis.com/v4/spreadsheets/${sheetId}/${action}`,
{
method: "POST",
bearer: access_token,
body: JSON.stringify(data),
},
);
return result;
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
October 23, 2023