fetch — getting data from an API
1 min read
Getting data from the internet
Almost every real app shows data from a server — weather, prices, posts. The tool to ask a server for data is fetch. The server's address is called an API.
async function getQuote() {
let response = await fetch("https://api.example.com/quote");
let data = await response.json();
console.log(data);
}
getQuote();
Two steps, every time:
await fetch(url)→ ask the server, wait for its reply.await response.json()→ turn the reply into usable JavaScript (an object or array).
What comes back?
APIs almost always reply in JSON — a text format that looks just like JavaScript objects and arrays:
{ "author": "Gandhi", "text": "Be the change" }
response.json() converts that text into a real object you can use: data.author, data.text.
Always handle failure
Networks fail. Wrap it in try/catch:
async function getQuote() {
try {
let res = await fetch("https://api.example.com/quote");
let data = await res.json();
console.log(data.text);
} catch (e) {
console.log("Could not load quote");
}
}
fetch = ask an API for data.
await response.json()= unwrap it. Wrap it in try/catch so a failed network never crashes your app.