How to Perform CRUD Operations on Google Sheets with Apps Script

by Fahim Mahmud Chisti

A CRUD API on Google Sheets lets another app create, read, update and delete rows over HTTP, with Google Apps Script as the backend and no server to run. By the end of this guide you will have one web app URL that handles all four operations, protected by an API key, plus test requests you can copy.

Quick answer: Put a header row in a sheet, paste a doGet/doPost script that sends ?action=create|read|update|delete to four helper functions, protect it with an API key stored in Script Properties, and deploy it as a web app. Every request then goes to the web app's /exec URL.

  1. Create a sheet with the headers ID, Name, Email and Phone in row 1.
  2. Open Extensions > Apps Script and paste the router and the four helper functions.
  3. Add a script property named API_KEY with a long random value.
  4. Deploy > New deployment > Web app, execute as Me, access Anyone.
  5. Call the /exec URL with action=read and your key to check it returns JSON.
In this guide
  1. Table of Contents
  2. Before You Start
  3. How the API Works
  4. Step 1: Set Up the Sheet
  5. Step 2: Create the Script and API Key
  6. Step 3: Add the Request Router
  7. Step 4: Add the CRUD Functions
  8. Step 5: Deploy the Web App
  9. Step 6: Test the Endpoints
  10. Calling the API from a Web Page
  11. Common Errors and Fixes
  12. Keep the API Safe and Fast
  13. Frequently Asked Questions
  14. Next Steps

Table of Contents

  1. Before You Start
  2. How the API Works
  3. Step 1: Set Up the Sheet
  4. Step 2: Create the Script and API Key
  5. Step 3: Add the Request Router
  6. Step 4: Add the CRUD Functions
  7. Step 5: Deploy the Web App
  8. Step 6: Test the Endpoints
  9. Calling the API from a Web Page
  10. Common Errors and Fixes
  11. Keep the API Safe and Fast
  12. Frequently Asked Questions

Before You Start

  • Access: a Google account that can create spreadsheets and Apps Script projects. Nothing to install; Postman or a terminal with curl is handy for testing.
  • Time: about 20–30 minutes.
  • Use a test spreadsheet first. The delete action removes rows for real. If something goes wrong on a live sheet, File > Version history lets you restore an earlier version.

How the API Works

Google Apps Script is Google's JavaScript platform for automating Sheets, Docs and other Workspace apps. When you deploy a script as a web app, Google gives it a public URL. A GET request to that URL runs your doGet(e) function and a POST request runs doPost(e); whatever the function returns becomes the HTTP response.

This guide uses one URL and an action parameter to pick the operation:

actionMethodWhat you sendWhat you get back
createPOSTJSON with name, email, phone{"status":"success","id":1}
readGEToptional id parameter{"status":"success","data":[…]}
updatePOSTJSON with id plus the fields to change{"status":"success","message":"Data updated"}
deletePOSTJSON with id{"status":"success","message":"Data deleted"}

Every request also carries key=YOUR_API_KEY in the URL. This setup is free and fine for small internal tools, forms and prototypes. It is not a replacement for a real database when you expect heavy traffic or many simultaneous writes.

Step 1: Set Up the Sheet

  1. Go to Google Sheets and create a new spreadsheet. Name the file something clear, such as API Data.
  2. In row 1 of the first tab, type these headers: A1 ID, B1 Name, C1 Email, D1 Phone.

Type the headers exactly as shown. The read function uses them as JSON keys, and the delete function looks for a column named exactly ID. Keep this tab first in the file: the code uses getActiveSheet(), and a web app has no open tab, so that call falls back to the first tab.

Step 2: Create the Script and API Key

  1. In the spreadsheet, click Extensions > Apps Script. The editor opens in a new tab with an empty Code.gs file.
  2. Click the project name (Untitled project) and rename it, for example Google Sheets CRUD API.
  3. Open Project Settings (the gear icon in the left sidebar), scroll to Script Properties and add a property named API_KEY. Use a long random value made of letters and digits, then save.

The key lives in Script Properties rather than in the code, so you can change it later without editing or redeploying the script.

Step 3: Add the Request Router

Delete the empty function in Code.gs and paste the following. It is the entry point for every request:

function doGet(e) {
  var result;
  if (!isAuthorized(e)) {
    result = { status: 'failed', message: 'Unauthorized' };
  } else if (e.parameter.action === 'read') {
    result = readData(e);
  } else {
    result = { status: 'failed', message: 'Invalid action' };
  }
  return jsonOutput(result);
}
function doPost(e) {
  var result;
  if (!isAuthorized(e)) {
    result = { status: 'failed', message: 'Unauthorized' };
  } else {
    switch (e.parameter.action) {
      case 'create':
        result = createData(e);
        break;
      case 'update':
        result = updateData(e);
        break;
      case 'delete':
        result = deleteData(e);
        break;
      default:
        result = { status: 'failed', message: 'Invalid action' };
    }
  }
  return jsonOutput(result);
}
// Shared secret: add a script property named API_KEY
// under Project Settings > Script Properties.
function isAuthorized(e) {
  var key = PropertiesService.getScriptProperties().getProperty('API_KEY');
  return Boolean(key) && e.parameter.key === key;
}
function jsonOutput(result) {
  return ContentService.createTextOutput(JSON.stringify(result))
    .setMimeType(ContentService.MimeType.JSON);
}

An Apps Script project can have only one doGet and one doPost, so these two functions route every request to a helper based on the action URL parameter. Both reject any request that does not carry the secret key you saved in Script Properties.

Step 4: Add the CRUD Functions

Paste each of the four functions below the router in the same Code.gs file, then save with Ctrl + S (Cmd + S on a Mac).

Create (Insert Data)

createData() adds a row and gives it the next free ID:

function createData(e) {
  var lock = LockService.getScriptLock();
  try {
    // Serialize writes so two requests cannot get the same ID
    lock.waitLock(10000);
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
    var data = JSON.parse(e.postData.contents);
    // Next ID = highest existing ID + 1
    // (the row number is not a safe ID once rows are deleted)
    var id = 1;
    var lastRow = sheet.getLastRow();
    if (lastRow > 1) {
      var ids = sheet.getRange(2, 1, lastRow - 1, 1).getValues();
      for (var i = 0; i < ids.length; i++) {
        var n = Number(ids[i][0]);
        if (n >= id) {
          id = n + 1;
        }
      }
    }
    // Append the data
    sheet.appendRow([id, data.name, data.email, data.phone]);
    return { status: 'success', id: id };
  } catch (error) {
    return { status: 'failed', message: error.toString() };
  } finally {
    lock.releaseLock();
  }
}
  • Endpoint: /exec?action=create&key=YOUR_API_KEY, method POST.
  • Payload: JSON object with name, email and phone.
  • What it does: parses the JSON, takes a script lock, assigns the highest existing ID + 1, appends the row and returns the new ID. The lock stops two requests that arrive together from getting the same ID; how LockService prevents race conditions in Apps Script explains the pattern in detail.

Read (Retrieve Data)

readData() returns every row as an object keyed by the header names, or only the row whose ID matches:

function readData(e) {
  try {
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
    var id = e.parameter.id;
    var data = sheet.getDataRange().getValues();
    var headers = data[0];
    var result = [];
    for (var i = 1; i < data.length; i++) {
      var row = data[i];
      var rowData = {};
      for (var j = 0; j < headers.length; j++) {
        rowData[headers[j]] = row[j];
      }
      if (!id || rowData.ID == id) {
        result.push(rowData);
      }
    }
    return { status: 'success', data: result };
  } catch (error) {
    return { status: 'failed', message: error.toString() };
  }
}
  • Endpoint: /exec?action=read&key=YOUR_API_KEY, method GET. Add &id=2 to fetch one record.
  • What it does: reads the whole tab in one call, turns each row into an object such as {"ID": 1, "Name": "Alice Johnson", …}, filters by id if you passed one and returns the list as JSON.

Update (Modify Data)

updateData() changes only the fields you send:

function updateData(e) {
  try {
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
    var data = JSON.parse(e.postData.contents);
    var id = data.id;
    var values = sheet.getDataRange().getValues();
    // Match payload keys to headers without caring about case (name -> Name)
    var keys = values[0].map(function (header) {
      return String(header).toLowerCase();
    });
    var idColIndex = keys.indexOf('id');
    var rowToUpdate;
    for (var i = 1; i < values.length; i++) {
      if (values[i][idColIndex] == id) {
        rowToUpdate = i + 1;
        break;
      }
    }
    if (!rowToUpdate) {
      return { status: 'failed', message: 'ID not found' };
    }
    for (var key in data) {
      var colIndex = keys.indexOf(key.toLowerCase());
      if (colIndex > -1 && colIndex !== idColIndex) {
        sheet.getRange(rowToUpdate, colIndex + 1).setValue(data[key]);
      }
    }
    return { status: 'success', message: 'Data updated' };
  } catch (error) {
    return { status: 'failed', message: error.toString() };
  }
}
  • Endpoint: /exec?action=update&key=YOUR_API_KEY, method POST.
  • Payload: JSON with id and the fields to change, for example {"id": 2, "email": "new@example.com"}. Field names are matched to headers without caring about case, so email updates the Email column.
  • What it does: finds the row with that ID, writes each matching field and never overwrites the ID itself. An unknown ID returns ID not found.

Delete (Remove Data)

deleteData() removes the row with the given ID:

function deleteData(e) {
  try {
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
    var data = JSON.parse(e.postData.contents);
    var id = data.id;
    var values = sheet.getDataRange().getValues();
    var idColIndex = values[0].indexOf('ID');
    var rowToDelete;
    for (var i = 1; i < values.length; i++) {
      if (values[i][idColIndex] == id) {
        rowToDelete = i + 1;
        break;
      }
    }
    if (rowToDelete) {
      sheet.deleteRow(rowToDelete);
      return { status: 'success', message: 'Data deleted' };
    }
    return { status: 'failed', message: 'ID not found' };
  } catch (error) {
    return { status: 'failed', message: error.toString() };
  }
}
  • Endpoint: /exec?action=delete&key=YOUR_API_KEY, method POST.
  • Payload: JSON with id, for example {"id": 2}.
  • What it does: finds the matching row and deletes the whole sheet row, so the rows below move up. IDs of other records do not change.

Step 5: Deploy the Web App

  1. Save the script, then click Deploy > New deployment at the top right of the editor.
  2. Next to Select type, click the gear icon and choose Web app.
  3. Add a Description if you like (for example "v1").
  4. Under Execute as, choose Me. The script then reads and writes the sheet with your permissions.
  5. Under Who has access, select Anyone, so apps can call it without a Google sign-in.
  6. Click Deploy, then Authorize access, and follow the prompts to allow the script to use your spreadsheet.
  7. Copy the Web app URL. It ends in /exec; this is the URL you call in every request below.

Note: Choosing Anyone makes the URL callable by anyone who has it, so do not remove the isAuthorized() check: without it, anyone could create, change or delete rows. The /exec URL keeps serving the version you deployed, so after you edit the code go to Deploy > Manage deployments, edit the deployment and choose New version.

Step 6: Test the Endpoints

Test from outside the editor. Clicking Run on doGet or doPost in the editor fails, because there is no request object (see Common Errors). Any of these works:

  • curl in a terminal. Always add -L: Apps Script answers through a redirect, and without it you only see a "Moved Temporarily" page.
  • Postman or a similar HTTP client.
  • A web browser, for the read (GET) requests.

Test with curl

Run these in a terminal on your computer, one at a time. Replace YOUR_DEPLOYMENT_ID and YOUR_API_KEY with your own values:

# Create a row. -d makes curl send a POST; do not add -X POST (see Common Errors)
curl -L -H "Content-Type: application/json" \
  -d '{"name":"Alice Johnson","email":"alice@example.com","phone":"555-1234"}' \
  "https://script.google.com/macros/s/YOUR_DEPLOYMENT_ID/exec?action=create&key=YOUR_API_KEY"

# Read every row
curl -L "https://script.google.com/macros/s/YOUR_DEPLOYMENT_ID/exec?action=read&key=YOUR_API_KEY"

# Change the email of the row with ID 1
curl -L -H "Content-Type: application/json" \
  -d '{"id":1,"email":"alice@newmail.example"}' \
  "https://script.google.com/macros/s/YOUR_DEPLOYMENT_ID/exec?action=update&key=YOUR_API_KEY"

# Delete the row with ID 1
curl -L -H "Content-Type: application/json" \
  -d '{"id":1}' \
  "https://script.google.com/macros/s/YOUR_DEPLOYMENT_ID/exec?action=delete&key=YOUR_API_KEY"

On an empty sheet the create call should print {"status":"success","id":1} and row 2 should appear in the sheet. The read call prints {"status":"success","data":[…]} with one object per row. Update and delete print Data updated and Data deleted messages.

Test the Create Operation with Postman

  1. Method: POST
  2. URL: Your_Web_App_URL?action=create&key=YOUR_API_KEY
  3. Headers: Content-Type: application/json
  4. Body (raw JSON):
{
    "name": "Alice Johnson",
    "email": "alice@example.com",
    "phone": "555-1234"
}
  1. Send Request: Click Send.
  2. Response: You should get a JSON object with "status": "success" and the assigned id.

If you create two contacts, Alice Johnson and then Ada (the web page example below), before deleting anything, the sheet looks like this:

ABCD
1IDNameEmailPhone
21Alice Johnsonalice@example.com555-1234
32Adaada@example.com555-0100

Test the Read Operation in a Browser

  • All rows: open Your_Web_App_URL?action=read&key=YOUR_API_KEY. The page shows every row as JSON.
  • One row: open Your_Web_App_URL?action=read&key=YOUR_API_KEY&id=2. The data array now holds only the record with ID 2.

Calling the API from a Web Page

Any page that can run fetch() can use the API. Two details matter. A browser sends a CORS preflight request for a JSON POST, and Apps Script web apps do not answer preflight requests, so send the body as text/plain; the script still parses it with JSON.parse. And a key placed in front-end code is visible to every visitor, so only do this on an internal page, or call the API from your own server instead.

Put this in the page's JavaScript file (or a script tag) and replace the URL and key:

const API_URL = 'https://script.google.com/macros/s/YOUR_DEPLOYMENT_ID/exec';
const API_KEY = 'YOUR_API_KEY'; // visible to anyone who can open this page
// Read every row
async function listContacts() {
  const res = await fetch(`${API_URL}?action=read&key=${encodeURIComponent(API_KEY)}`);
  const json = await res.json();
  if (json.status !== 'success') {
    throw new Error(json.message);
  }
  return json.data;
}
// Create a row: text/plain avoids the CORS preflight
async function addContact(contact) {
  const res = await fetch(`${API_URL}?action=create&key=${encodeURIComponent(API_KEY)}`, {
    method: 'POST',
    headers: { 'Content-Type': 'text/plain;charset=utf-8' },
    body: JSON.stringify(contact),
  });
  return res.json();
}
addContact({ name: 'Ada', email: 'ada@example.com', phone: '555-0100' }).then(console.log);

Open the browser's developer console: the addContact call should log {status: "success", id: …} and a new row should appear in the sheet.

Common Errors and Fixes

  • {"status":"failed","message":"Unauthorized"}: the key in the URL does not match the API_KEY script property, or the property was never saved. Keys are case-sensitive; re-copy the value from Project Settings.
  • You get an HTML page instead of JSON: in curl, add -L. A Google sign-in page means Who has access is not set to Anyone, or you are calling the /dev test URL instead of the /exec URL.
  • A POST works in Postman but fails in curl: remove -X POST. With -X POST, curl repeats the POST on the redirect target instead of switching to GET, and Google returns an error page.
  • Your code changes have no effect: the /exec URL still serves the old version. Use Deploy > Manage deployments, edit the deployment and pick New version.
  • TypeError: Cannot read properties of undefined (reading 'parameter'): you clicked Run on doGet or doPost in the editor. There is no request in that case; test through the web app URL instead.

Keep the API Safe and Fast

  • Keep the key secret and change it when needed. Editing the API_KEY script property takes effect on the next request; no redeploy is needed.
  • Validate input. Check that name and email exist and look sensible before writing, so bad requests cannot fill the sheet with blank rows.
  • Do not leak details in errors. The helpers return error.toString(), which is handy while testing. Replace it with a generic message once the API is in use.
  • Read and write in batches. One getValues() or setValues() call is much faster than many single-cell calls. For frequent reads, cache the result with CacheService for a short time.
  • Lock every write if many clients write at once. Only createData() takes a lock. Wrap update and delete the same way if two callers may edit the same rows.
  • Watch the quotas. Apps Script has daily limits and a maximum run time per call; see Google's Apps Script quotas page. Use console.log() while developing and check the Executions page for failures.

Frequently Asked Questions

Is it safe to deploy the web app with access set to "Anyone"?

Only with the API key check in place. "Anyone" means anyone who has the URL can send requests, so isAuthorized() is what stops strangers from changing rows. Use a long random key, keep it out of public pages and do not store sensitive personal data in a sheet exposed this way.

Can I send the API key in an HTTP header?

No. Apps Script web apps cannot read HTTP request headers, so a key sent in a header never reaches your code. Pass it as a URL parameter, as isAuthorized() expects, or inside the JSON body. If the key must stay hidden from users, call the API from your own server rather than from a browser.

How many rows can a Google Sheets API handle?

It works best for small datasets. A spreadsheet can hold up to 10 million cells, but readData() loads the whole tab on every request, so responses slow down long before that limit. Writes are also slower than a database and simultaneous writes queue behind the lock. For heavy traffic, move to a real database.

Can I use this API for commercial applications?

Yes, as long as you stay within Google Apps Script quotas and limits. Daily quotas depend on your account type, and each request runs as a separate execution. For high-demand applications, consider a dedicated backend and keep Sheets as a reporting copy.

How do I update multiple rows at once?

Change updateData() to accept an array of objects, apply all changes to the array returned by getValues(), then write it back with a single setValues() call. One batch write is much faster than calling setValue() for each cell.

Next Steps

Deploy the script, run the four curl tests and check the sheet after each one. Then decide how data should flow out of the sheet: to push rows to another service as they change, see how to send webhooks from Google Sheets with Apps Script. For triggers, custom menus and scheduled jobs, continue with the Google Apps Script automation guide.

all_in_one_marketing_tool