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.
- Create a sheet with the headers ID, Name, Email and Phone in row 1.
- Open Extensions > Apps Script and paste the router and the four helper functions.
- Add a script property named API_KEY with a long random value.
- Deploy > New deployment > Web app, execute as Me, access Anyone.
- Call the /exec URL with action=read and your key to check it returns JSON.
In this guide
- Table of Contents
- Before You Start
- How the API Works
- Step 1: Set Up the Sheet
- Step 2: Create the Script and API Key
- Step 3: Add the Request Router
- Step 4: Add the CRUD Functions
- Step 5: Deploy the Web App
- Step 6: Test the Endpoints
- Calling the API from a Web Page
- Common Errors and Fixes
- Keep the API Safe and Fast
- Frequently Asked Questions
- Next Steps
Table of Contents
- Before You Start
- How the API Works
- Step 1: Set Up the Sheet
- Step 2: Create the Script and API Key
- Step 3: Add the Request Router
- Step 4: Add the CRUD Functions
- Step 5: Deploy the Web App
- Step 6: Test the Endpoints
- Calling the API from a Web Page
- Common Errors and Fixes
- Keep the API Safe and Fast
- 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
curlis 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:
| action | Method | What you send | What you get back |
|---|---|---|---|
create | POST | JSON with name, email, phone | {"status":"success","id":1} |
read | GET | optional id parameter | {"status":"success","data":[…]} |
update | POST | JSON with id plus the fields to change | {"status":"success","message":"Data updated"} |
delete | POST | JSON 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
- Go to Google Sheets and create a new spreadsheet. Name the file something clear, such as API Data.
- In row 1 of the first tab, type these headers: A1
ID, B1Name, C1Email, D1Phone.
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
- In the spreadsheet, click Extensions > Apps Script. The editor opens in a new tab with an empty
Code.gsfile. - Click the project name (Untitled project) and rename it, for example Google Sheets CRUD API.
- 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,emailandphone. - 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=2to 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 byidif 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
idand the fields to change, for example{"id": 2, "email": "new@example.com"}. Field names are matched to headers without caring about case, soemailupdates theEmailcolumn. - 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
- Save the script, then click Deploy > New deployment at the top right of the editor.
- Next to Select type, click the gear icon and choose Web app.
- Add a Description if you like (for example "v1").
- Under Execute as, choose Me. The script then reads and writes the sheet with your permissions.
- Under Who has access, select Anyone, so apps can call it without a Google sign-in.
- Click Deploy, then Authorize access, and follow the prompts to allow the script to use your spreadsheet.
- 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
- Method: POST
- URL:
Your_Web_App_URL?action=create&key=YOUR_API_KEY - Headers:
Content-Type:application/json - Body (raw JSON):
{
"name": "Alice Johnson",
"email": "alice@example.com",
"phone": "555-1234"
}- Send Request: Click Send.
- Response: You should get a JSON object with
"status": "success"and the assignedid.
If you create two contacts, Alice Johnson and then Ada (the web page example below), before deleting anything, the sheet looks like this:
| A | B | C | D | |
|---|---|---|---|---|
| 1 | ID | Name | Phone | |
| 2 | 1 | Alice Johnson | alice@example.com | 555-1234 |
| 3 | 2 | Ada | ada@example.com | 555-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. Thedataarray now holds only the record withID2.
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"}: thekeyin the URL does not match theAPI_KEYscript 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/devtest URL instead of the/execURL. - 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
/execURL 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 ondoGetordoPostin 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_KEYscript property takes effect on the next request; no redeploy is needed. - Validate input. Check that
nameandemailexist 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()orsetValues()call is much faster than many single-cell calls. For frequent reads, cache the result withCacheServicefor 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.

