Learn APIs in JavaScript in Hindi – Easy Guide for Beginners
JavaScript में APIs और Async JavaScript आपको बाहरी डेटा से जोड़ते हैं और गैर-समकालिक ऑपरेशन्स को आसान बनाते हैं।
यह HindiStudyHub ब्लॉग आपको API, fetch, promises, async/await जैसे टेक्निकल कॉन्सेप्ट्स को सरल हिंदी में सिखाता है। इसमें Exercise (रैंडम कोट फेच करना), Quiz (5 MCQs), और Mini Project (वेदर ऐप) शामिल हैं।
endpoint, CORS, microtask queue जैसे टर्म्स English में हैं, कोड भी पूरी तरह English में है। आइए, डायनामिक वेब ऐप्स बनाना शुरू करें!
What is an APIs in JavaScript in Hindi? (JavaScript में APIs क्या है?)
API (Application Programming Interface) दो सॉफ्टवेयर सिस्टम्स को डेटा और सर्विसेज़ शेयर करने देता है। यह एक डिजिटल ब्रिज है जो endpoint के ज़रिए बाहरी सर्वर से डेटा लाता है। गलत endpoint या authentication से CORS errors या rate limits हो सकते हैं।
- बेस्ट प्रैक्टिस: API documentation पढ़ें और सही headers यूज़ करें।
- उपयोग: डायनामिक डेटा (जैसे वेदर, कोट्स) लाना, थर्ड-पार्टी इंटीग्रेशन।
- समस्याएँ: network latency, security issues, invalid endpoints।
Example:
fetch("https://api.example.com/data", { headers: { "Authorization": "Bearer token" } })
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("API Error:", error));
Fetching Data with fetch:
fetch API बाहरी सर्वर से डेटा लाने का मॉडर्न तरीका है, जो एक promise लौटाता है। यह HTTP रिक्वेस्ट्स (GET, POST) को सपोर्ट करता है और JSON डेटा को आसानी से हैंडल करता है। गलत URL, CORS पॉलिसी, या नेटवर्क इश्यू से rejections हो सकते हैं।
- बेस्ट प्रैक्टिस: response.ok चेक करें और error handling लागू करें।
- उपयोग: API डेटा फेचिंग, डायनामिक UI अपडेट्स।
- समस्याएँ: timeout issues, invalid JSON, CORS restrictions।
Example:
fetch("https://api.quotable.io/random")
.then(response => {
if (!response.ok) throw new Error("Network response failed");
return response.json();
})
.then(data => console.log(`Quote: ${data.content}`))
.catch(error => console.error("Fetch Error:", error));
Promises Basics:
Promise एक ऑब्जेक्ट है जो गैर-समकालिक ऑपरेशन्स (जैसे API कॉल्स) का रिजल्ट रिप्रजेंट करता है। यह तीन स्टेट्स में होता है: pending, fulfilled, या rejected। microtask queue में promises को प्रायोरिटी मिलती है, जो callbacks से तेज़ है। गलत हैंडलिंग से unhandled rejections हो सकते हैं।
- बेस्ट प्रैक्टिस: हमेशा .then और .catch यूज़ करें, और promise chaining समझें।
- उपयोग: API रिक्वेस्ट्स, फाइल लोडिंग, टाइमर।
- समस्याएँ: जटिल promise chains, race conditions।
Example:
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Data loaded!"), 1000);
// setTimeout(() => reject("Failed!"), 1000); // For testing reject
});
myPromise
.then(result => console.log(result))
.catch(error => console.error("Promise Error:", error));
Types of Promises in APIs in Hindi
.then:
Promise .then promise के सक्सेसफुल resolution को हैंडल करता है। यह promise chaining की अनुमति देता है, जिससे डेटा स्टेप-बाय-स्टेप प्रोसेस होता है। गलत डेटा फॉर्मेट या चेनिंग से undefined या errors हो सकते हैं।
- बेस्ट प्रैक्टिस: डेटा स्ट्रक्चर जाँचें और return स्टेटमेंट्स यूज़ करें।
- उपयोग: API डेटा प्रोसेसिंग, UI अपडेट्स।
- समस्याएँ: unhandled promises, async race conditions।
Example:
fetch("https://api.quotable.io/random")
.then(response => response.json())
.then(data => console.log(`Author: ${data.author}, Quote: ${data.content}`))
.catch(error => console.error("Then Error:", error));
.catch:
Promise .catch promise के rejection या त्रुटियों (जैसे नेटवर्क फेलियर) को पकड़ता है। यह यूज़र को त्रुटि मैसेज दिखाने में मदद करता है। बिना .catch के unhandled rejections क्रैश का कारण बन सकते हैं।
- बेस्ट प्रैक्टिस: हर promise chain में
.catchशामिल करें और त्रुटि टाइप्स जाँचें। - उपयोग: error handling, यूज़र फीडबैक, लॉगिंग।
- समस्याएँ: silent failures, generic error messages।
Example:
fetch("https://api.quotable.io/invalid")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Catch Error:", error.message));
Async/Await Intro:
Async/await promises को सरल और callback-जैसे कोड की तरह पठनीय बनाता है। async फंक्शन हमेशा promise लौटाता है, और await promise resolution का इंतज़ार करता है।
बिना try/catch के त्रुटियाँ अनहैंडल्ड रहती हैं, जिससे microtask queue में बग्स हो सकते हैं। बेस्ट प्रैक्टिस: try/catch यूज़ करें और await केवल async फंक्शन्स में यूज़ करें।
- उपयोग: API कॉल्स, डेटा प्रोसेसिंग, सिक्वेंशियल ऑपरेशन्स।
- समस्याएँ: async misuse, performance bottlenecks।
Example:
async function getQuote() {
try {
const response = await fetch("https://api.quotable.io/random");
if (!response.ok) throw new Error("Failed to fetch quote");
const data = await response.json();
console.log(`Quote: ${data.content}, Author: ${data.author}`);
} catch (error) {
console.error("Async Error:", error.message);
}
}
getQuote();
Exercise: Fetch and display a random quote
Task: fetch और async/await का उपयोग करके Quotable API से रैंडम कोट फेच करें और DOM में डिस्प्ले करें। यह प्रैक्टिस बिगिनर्स को API integration और error handling सिखाती है। गलत endpoint या नेटवर्क इश्यू से rejections हो सकते हैं।
- बेस्ट प्रैक्टिस: response.ok चेक करें, try/catch यूज़ करें, और यूज़र को त्रुटि मैसेज दिखाएँ।
- उपयोग: डायनामिक UI, API टेस्टिंग।
- समस्याएँ: CORS issues, rate limits, DOM errors।
Code:
async function displayQuote() {
const quoteElement = document.getElementById("quote");
try {
const response = await fetch("https://api.quotable.io/random");
if (!response.ok) throw new Error("Failed to fetch quote");
const data = await response.json();
quoteElement.textContent = `${data.content} - ${data.author}`;
} catch (error) {
quoteElement.textContent = `Error: ${error.message}`;
}
}
document.getElementById("fetchBtn").addEventListener("click", displayQuote);
Quiz: Promises and Fetch
यह क्विज़ APIs, fetch, और promises के कॉन्सेप्ट्स को टेस्ट करता है। सवाल microtask queue, promise resolution, और error handling पर फोकस करते हैं। सही जवाब चुनें और HindiStudyHub पर प्रैक्टिस करें!
-
What is an API?
-
A) Interface for sharing data/services
-
B) Programming language
-
C) Error
-
D) Database
Answer: A) Interface for sharing data/services
-
-
What does fetch return?
-
A) Promise
-
B) String
-
C) Error
-
D) Array
Answer: A) Returns a promise
-
-
What is the purpose of .catch in a promise?
-
A) Handles errors
-
B) Processes data
-
C) Error
-
D) Defines variables
Answer: A) Handles errors
-
-
What does await do in an async function?
-
A) Waits for promise resolution
-
B) Defines a loop
-
C) Error
-
D) null
Answer: A) Waits for promise resolution
-
-
What happens if fetch fails due to network issues?
-
A) Rejects the promise
-
B) Returns null
-
C) Error
-
D) undefined
Answer: A) Rejects the promise
-
Mini Project:
Task: OpenWeatherMap API से fetch और async/await यूज़ करके वेदर डेटा लाएँ और DOM में डिस्प्ले करें। यह प्रोजेक्ट API integration, error handling, और डायनामिक UI को सिखाता है।
यूज़र सिटी इनपुट देगा, और ऐप तापमान, मौसम का विवरण दिखाएगा। गलत API की, इनवैलिड सिटी, या CORS से errors हो सकते हैं।
Code:
async function getWeather() {
const city = document.getElementById("cityInput").value.trim();
const weatherElement = document.getElementById("weather");
const apiKey = "YOUR_API_KEY"; // Replace with OpenWeatherMap API key
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;
try {
if (!city) throw new Error("Please enter a city");
const response = await fetch(url);
if (!response.ok) throw new Error("City not found or invalid API key");
const data = await response.json();
weatherElement.textContent = `${data.name}: ${data.main.temp}°C, ${data.weather[0].description}`;
} catch (error) {
weatherElement.textContent = `Error: ${error.message}`;
}
}
document.getElementById("weatherBtn").addEventListener("click", getWeather);
Conclusion
APIs और Async JavaScript वेब डेवलपमेंट को शक्तिशाली बनाते हैं। fetch, promises, और async/await के साथ आप डायनामिक, रियल-टाइम ऐप्स बना सकते हैं। microtask queue और error handling समझना कोड को रिलायबल बनाता है। HindiStudyHub पर प्रैक्टिस करें, अपने प्रोजेक्ट्स बनाएँ, और अगले मॉड्यूल में Modules सीखें।
Also Read: