fx API और वेब ऐप्स
ENहिन्दी

UrlFetchApp से बाहरी API कॉल करें

⏱ 20 मिनट

आप क्या सीखेंगे

  • API क्या है और JSON कैसा दिखता है
  • UrlFetchApp से GET और POST requests
  • errors और status codes संभालना
  • API data को schedule पर शीट में लिखना

समझिए

एक मिनट में 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 करें।

अभ्यास

अभ्यासअभ्यास 1

कोई मुफ़्त public API चुनिए (जैसे currency या weather API जो free key देती हो)। Key को Script Properties में रखिए और एक function लिखिए जो हर run पर Rates tab में timestamp के साथ आज की value की एक row जोड़े।

प्रश्नोत्तरी

muteHttpExceptions: true क्या करता है? a) logs छिपाता है b) 4xx/5xx पर error फेंकने की जगह response लौटाता है c) requests तेज़ करता है
4xx/5xx पर error फेंकने की जगह response लौटाता है
429 response का मतलब… a) ग़लत URL b) ग़लत key c) बहुत ज़्यादा requests
बहुत ज़्यादा requests
UrlFetchApp से बाहरी API कॉल करें · हिंदी | ExcelWalaa