Can Google Sheets API interact with the script editor programmatically?

I’m working on a project where I need to create a Google Sheet and add custom Apps Script code to it automatically. Right now I have to do this manually by opening the script editor and pasting in the code. Is there a way to do this programmatically using the Google Sheets API?

I’d like to:

  1. Generate a new Google Sheet
  2. Add custom .gs code to the sheet’s Apps Script
  3. Use the API to input data, including formulas that reference the custom script

Does anyone know if this is possible or if there’s a workaround? I’m using Python for my project if that matters. Thanks for any help!

I’ve actually dealt with this exact scenario in a recent project. While the Sheets API doesn’t directly support adding scripts, I found a workaround using a combination of the Drive API and Apps Script API. Here’s the gist:

  1. Use the Drive API to create the Google Sheet.
  2. Grab the file ID of the new sheet.
  3. Use the Apps Script API to create a new script project and link it to the sheet.
  4. Add your custom code to the script project via the Apps Script API.
  5. Finally, use the Sheets API to populate data and formulas.

It’s a bit convoluted, but it gets the job done. The trickiest part was figuring out the correct scopes and authentication flow. If you’re using Python, the google-auth and google-auth-oauthlib libraries were lifesavers for handling OAuth2.

Let me know if you want more specifics on implementation. It took some trial and error, but I eventually got a smooth automated process working.

I’ve experimented with this, and while it’s not straightforward, it is possible. The key is leveraging multiple APIs in tandem. You’ll need to use the Drive API to create the sheet, then the Apps Script API to attach and modify the script. Finally, you can use the Sheets API for data manipulation.

One caveat: this approach requires broader API access permissions, which might be a concern depending on your use case. Also, be prepared for some API quota limitations, especially if you’re doing this at scale.

In Python, the google-auth library is essential for handling authentication across these different APIs. You might also want to look into batching requests to optimize performance if you’re creating multiple sheets.

It’s a complex setup, but once you get it working, it’s quite powerful for automating sheet creation with custom scripts.

hey sophia, i’ve wrestled with similar stuff before. as far as i know, the sheets API can’t directly add scripts to a sheet. but you could try using the Apps Script API instead - it lets you create/update script projects programmatically. might be worth checking out for your use case. good luck with the project!