API Integration
2 weeks AdvancedFetching and displaying external data.
Overview
APIs let you request data from external services.
Essential for modern web apps.
- fetch
- JSON
- Error Handling
- Async Operations
Detailed Explanation
Async and setTimeout
JavaScript doesn't stop and wait during network requests; it moves on. To intentionally delay execution, use setTimeout.
- setTimeout(() => {\n console.log('After 3 sec');\n}, 3000);
- Trying to use data from an API before the request actually finishes
fetch and JSON
Use fetch(url) to make an HTTP request. Use await to pause until the response arrives, then extract JSON.
- const res = await fetch(url);
- const data = await res.json();
- await can only be used inside an async function
- Forgetting the parentheses: res.json instead of res.json()
Error Handling (try-catch & res.ok)
Assume networks will fail. Handle crashes (like no internet) with try-catch, and server errors (like 404 Not Found) by checking res.ok.
- try {\n const res = await fetch(url);\n if (!res.ok) throw new Error('Bad status');\n} catch (e) {\n console.log(e.message);\n}
- Always think about the 'unhappy path'
- Writing fetch calls without any error handling
Practical Steps
- 1 Fetch Mock Data 3 mins
Use JSONPlaceholder (a free fake API) to fetch some user data.
- Pass the URL to the fetch function
- Use await to wait for the response
- Use res.json() to convert it into a JS object
<script> const url = 'https://jsonplaceholder.typicode.com/users/1'; async function getData() { const res = await fetch(url); const data = await res.json(); console.log('Fetched Data:', data); } getData(); </script> - 2 Display Data in HTML 5 mins
Take that fetched data and actually put it on the screen.
- Create a <div> with an ID
- Set its textContent using the data we fetched
<div id="profile"> Loading... </div> <script> const url = 'https://jsonplaceholder.typicode.com/users/1'; async function renderData() { const res = await fetch(url); const data = await res.json(); const profileDiv = document.getElementById('profile'); profileDiv.textContent = `Name: ${data.name} (Email: ${data.email})`; } renderData(); </script> - 3 Handle Deliberate Errors 3 mins
Intentionlly break the URL to see how try-catch handles failures gracefully.
- Use a fake URL
- Wrap the code in try { ... } catch (e) { ... }
- Throw an error if !res.ok
<div id="profile">Loading...</div> <script> const url = 'https://jsonplaceholder.typicode.com/users/999999'; // Broken URL async function renderData() { const profileDiv = document.getElementById('profile'); try { const res = await fetch(url); if (!res.ok) { throw new Error(`HTTP Error: ${res.status}`); } const data = await res.json(); profileDiv.textContent = `Name: ${data.name}`; } catch (error) { profileDiv.textContent = 'Failed to load data.'; profileDiv.style.color = 'red'; console.error(error); } } renderData(); </script>
Career & real-world context
API work separates junior from mid-level frontend—gateway to React Query/Next data fetching.
Industry examples
- Weather APIs
- GitHub REST
- Headless CMS lists
Recommended study plan
fetch → JSON → errors → async/await → loading UI.
Prerequisites
API work separates junior from mid-level frontend—gateway to React Query/Next data fetching.…
Frequently Asked Questions
- What are some good free APIs to practice with?
- JSONPlaceholder (dummy data), GitHub API (fetching repos), PokéAPI (yes, a Pokémon encyclopedia), and OpenWeatherMap are the holy grail of beginner APIs. Building a Pokédex is a rite of passage.
- I tried to fetch an API and got a giant red 'CORS error'. Am I hacked?
- Welcome to the club! Browsers have a security policy that stops you from secretly downloading data from a different domain. If the API doesn't explicitly allow CORS, your browser bricks the request. You usually fix it by setting up your own backend proxy, which is a headache for another day.
- A senior dev told me to use 'Axios' instead of 'fetch'. Should I?
- Axios used to be mandatory because the old 'fetch' kinda sucked. It auto-converts JSON and handles timeouts better. But modern 'fetch' is quite good now, and many projects are moving back to native 'fetch' to avoid installing extra libraries. Learn fetch first.
- Is it safe to put API Secret Keys directly in my frontend JS code?
- ABSOLUTELY NOT. Never. Ever. Your frontend JavaScript is completely visible to anyone who hits F12. If you put an AWS or OpenAI key in there, bots will scrape it in 5 seconds and you'll wake up to a $50,000 bill. Always keep keys on a backend server.
- CORS errors?
- Browser security—often needs server Access-Control-Allow-Origin.
- axios vs fetch?
- Learn fetch first, then optional axios wrapper.
① Read the explanation. Next: ② Do exercises.
API integration complete.
Finally, let's tie it all together in a project.