समझिए
एक मिनट में API
API एक web address है जो लोगों के लिए web page की जगह programs के लिए data लौटाता है। ज़्यादातर APIs JSON लौटाते हैं:
{ "base": "USD", "rates": { "INR": 83.2, "EUR": 0.92 } }
JavaScript में JSON.parse(text) उस text को object में बदल देता है जिसे आप इस्तेमाल कर सकते हैं: data.rates.INR।
GET request
हम एक मुफ़्त test API लेंगे जिसमें key नहीं चाहिए:
function getTodo() {
const res = UrlFetchApp.fetch('https://jsonplaceholder.typicode.com/todos/1');
const data = JSON.parse(res.getContentText());
console.log(data.title, data.completed);
}
Errors को सही से संभालना
Default में fetch किसी भी 4xx/5xx response पर error फेंकता है। Status ख़ुद जाँचने के लिए muteHttpExceptions लगाएँ:
function safeGet(url) {
const res = UrlFetchApp.fetch(url, { muteHttpExceptions: true });
const code = res.getResponseCode();
if (code !== 200) {
console.error(`HTTP ${code}: ${res.getContentText().slice(0, 200)}`);
return null;
}
return JSON.parse(res.getContentText());
}
| Code | मतलब |
|---|---|
| 200 | OK |
| 400 | Bad request (आपका भेजा data ग़लत है) |
| 401 / 403 | अनुमति नहीं (key नहीं है या ग़लत है) |
| 404 | नहीं मिला (ग़लत URL) |
| 429 | बहुत ज़्यादा requests — धीरे चलें |
| 500+ | server की समस्या — बाद में फिर कोशिश करें |
Data भेजना: POST
function createPost() {
const payload = { title: 'New order', body: 'Ring x2', userId: 1 };
const res = UrlFetchApp.fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'post',
contentType: 'application/json',
payload: JSON.stringify(payload),
muteHttpExceptions: true
});
console.log(res.getResponseCode(), res.getContentText());
}
API keys और headers
ज़्यादातर असली APIs को key चाहिए, जो आमतौर पर header में भेजी जाती है:
const key = PropertiesService.getScriptProperties().getProperty('API_KEY');
const res = UrlFetchApp.fetch('https://api.example.com/v1/rates', {
headers: { Authorization: 'Bearer ' + key },
muteHttpExceptions: true
});
Keys को कभी ऐसे code में सीधे न डालें जो दूसरे देख सकें — उन्हें Script Properties में रखें (इस module का lesson 3)।
उदाहरण: list को शीट में लाना
function loadUsers() {
const users = safeGet('https://jsonplaceholder.typicode.com/users');
if (!users) return;
const out = [['ID', 'Name', 'Email', 'City']];
users.forEach(u => out.push([u.id, u.name, u.email, u.address.city]));
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Users');
sheet.clearContents();
sheet.getRange(1, 1, out.length, out[0].length).setValues(out);
sheet.getRange('F1').setValue('Updated: ' + new Date().toLocaleString('en-IN'));
}
हर घंटे वाला time-driven trigger जोड़िए और शीट अपने-आप refresh होती रहेगी।
एक साथ कई URLs
UrlFetchApp.fetchAll([...requests]) कई requests एक साथ भेजता है — एक-एक call वाले loop से बहुत तेज़।
const ids = [1, 2, 3];
const responses = UrlFetchApp.fetchAll(ids.map(id => ({
url: `https://jsonplaceholder.typicode.com/todos/${id}`,
muteHttpExceptions: true
})));
const titles = responses.map(r => JSON.parse(r.getContentText()).title);
मुख्य बातें
- GET/POST के लिए
UrlFetchApp.fetch(url, options); नतीजे कोJSON.parseकरें। - हमेशा
muteHttpExceptions: trueलगाएँ औरgetResponseCode()जाँचें। - API keys Script Properties में रखें; headers में भेजें।
- कई URLs के लिए
fetchAll; जो data कम बदलता है उसे cache करें।