Substitua todos os textos EM MAIÚSCULO pelos seus valores reais
YOUR_SHEET_ID
• YOUR_SHEET_NAME
• YOUR_KEY_NAME
(ex.: id, phone, cpf…)
1️⃣ Visão Geral
🚀 Web App Expõe sua planilha Google Sheets como endpoint HTTP (GET ou POST). ⚡ Cache em memória Índice em Map
para respostas em ms. 🔍 Busca por chave Consulta por YOUR_KEY_NAME
(ex.: id=123
) usando índice + fallback rápido. ♻️ Rebuild & Incremental Você controla quando reconstruir o índice (manual ou trigger de 1 min).
2️⃣ Script-base (anonimizado)
/**
* Web App – API de Planilha
* Troque TODOS os marcadores EM MAIÚSCULO pelos seus dados reais!
*/
/* ⚙️ CONFIGURAÇÃO */
const PLANILHA_ID = 'YOUR_SHEET_ID';
const SHEET_NAME = 'YOUR_SHEET_NAME';
/* 🗺️ Mapeie só as colunas que quer expor (A=1, B=2, …) */
const COL = {
key : 1, // YOUR_KEY_NAME (chave de busca)
field01 : 2,
field02 : 3,
field03 : 4
};
const NUM_COLS = Object.keys(COL).length;
const TTL_CACHE_MS = 15 * 60 * 1000; // 15 min
const CHUNK_ROWS = 8000; // leitura em blocos
/* 🛢️ Cache */
let cache = { map:new Map(), last:0, building:false };
/* 🌐 ENDPOINTS */
function doGet(e){ return handle(e); }
function doPost(e){
if (e.postData && e.postData.type === 'application/json')
Object.assign(e.parameter, JSON.parse(e.postData.contents||'{}'));
return handle(e);
}
/* 🧠 LÓGICA PRINCIPAL */
function handle(e){
const id = (e.parameter['YOUR_KEY_NAME'] || '').trim();
if (!id) return out({found:false,error:`Parâmetro 'YOUR_KEY_NAME' ausente`});
try{
if (Date.now() - cache.last > TTL_CACHE_MS) buildIndex();
const hit = cache.map.get(id);
if (hit) return out({found:true, ...hit});
const obj = searchSheet(id);
return out(obj ? {found:true, ...obj} : {found:false});
}catch(err){
return out({found:false,error:err.toString()});
}
}
/* 🔍 Busca direta (fallback) */
function searchSheet(id){
const sh = SpreadsheetApp.openById(PLANILHA_ID).getSheetByName(SHEET_NAME);
const rng = sh.getRange(1, COL.key, sh.getLastRow(), 1)
.createTextFinder(id).matchEntireCell(true).findNext();
if (!rng) return null;
const vals = sh.getRange(rng.getRow(), 1, 1, NUM_COLS).getValues()[0];
const obj = rowToObj(vals);
cache.map.set(id, obj); // salva no cache
return obj;
}
/* 🔄 Constrói OU renova o índice completo */
function buildIndex(){
if (cache.building) return;
cache.building = true;
try{
const sh = SpreadsheetApp.openById(PLANILHA_ID).getSheetByName(SHEET_NAME);
const rows = sh.getLastRow() - 1;
const map = new Map();
for (let i=2;i<=rows+1;i+=CHUNK_ROWS){
const end = Math.min(i+CHUNK_ROWS-1,rows+1);
sh.getRange(i,1,end-i+1,NUM_COLS).getValues().forEach(r=>{
const id = (r[COL.key-1]||'').toString().trim();
if (id) map.set(id, rowToObj(r));
});
}
cache = { map, last:Date.now(), building:false };
}finally{ cache.building=false; }
}
/* 🧩 Helpers */
function rowToObj(r){
const o={}; for (const k in COL) o[k]=r[COL[k]-1]; return o;
}
const out = o=>ContentService.createTextOutput(JSON.stringify(o))
.setMimeType(ContentService.MimeType.JSON);
/* ⏰ Trigger incremental (1 min) */
function criarTriggerIncremental(){
ScriptApp.newTrigger('buildIndex')
.timeBased().everyMinutes(1).create();
}
3️⃣ Passo a Passo Essencial
🔧 A. Configure & cole o script
-
Abra script.google.com → Novo projeto.
-
Cole o template acima.
-
Troque TODOS os marcadores
YOUR_…
.
⚡ B. Construa o primeiro índice manualmente
-
No editor ➜ Executar
buildIndex()
uma vez. -
Isso carrega todas as linhas em memória (mais rápido para a primeira requisição).
💡 Dica rápida
Se preferir, basta chamar a API com&rebuild=true
logo após o deploy – o efeito é o mesmo.
⏰ C. Crie o gatilho incremental
-
Una vez construído o índice inicial, selecione a função
criarTriggerIncremental
no menu suspenso de execução. -
Clique Run → autorizar.
-
Um trigger de 1 min manterá o cache sincronizado sem esforço.
🌐 D. Publique e gere a URL
-
Deploy ▸ New deployment ▸ Web app.
-
Execute as: Me • Who has access: Anyone (ou link).
-
Deploy ➔ Authorize ➔ Copy URL.
https://script.google.com/macros/s/SEU_DEPLOY_ID/exec
4️⃣ Testes Rápidos
5️⃣ Problemas Comuns & Soluções
🔒 Segurança Rápida
-
Web App roda com suas credenciais → clientes só veem JSON.
-
Para limitar, mude acesso para Only myself e exija token / API Key.
✨ Pronto!
-
👉 Construa o primeiro índice (
buildIndex
ourebuild=true
). -
👉 Crie o trigger incremental.
-
👉 Publique e use!
Qualquer dúvida, fale com a gente. 😉