Lesson 5.2: APIs & Fetch – Getting Data from External Sources
APIs (Application Programming Interfaces) allow web applications to fetch data from servers and display it dynamically. The fetch() method in JavaScript is commonly used to retrieve data asynchronously.
1. What is an API?
-
API is a bridge between applications to communicate and exchange data.
-
Example: Weather API, Movie Database API, or any REST API.
-
Data is usually in JSON format.
2. Using fetch()
-
The
fetch()function sends a request to a server and returns a promise.
3. Async/Await with Fetch
-
Clean syntax for handling promises.
4. Practical Example: Fetching Users
Output Example:
5. Best Practices
-
Always handle errors using
.catch()ortry…catch. -
Use
async/awaitfor readable and maintainable code. -
Parse JSON with
response.json(). -
Avoid blocking the UI; fetch data asynchronously.
✅ Summary:
-
APIs allow dynamic data retrieval from servers.
-
fetch()method is promise-based and works asynchronously. -
Async/await makes code cleaner and easier to read.
-
Essential for real-world web applications like dashboards, social apps, and e-commerce sites.
