Asynchronous Programming
Lesson Progress0%
Fetch API
Topic Overview
Take your time to understand each concept. Practice with the examples below!
The Fetch API lets you talk to servers and APIs from your JavaScript code. It's like making a phone call to get or send information!
Basic fetch syntax:
fetch(url) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));
With async/await (cleaner!):
async function getData() { const response = await fetch(url); const data = await response.json(); return data;}
GET Request (getting data):
async function getUsers() { try { const response = await fetch('https://api.example.com/users'); if (!response.ok) { throw new Error('Network response was not ok'); } const users = await response.json(); return users; } catch (error) { console.error('Fetch error:', error); }}
POST Request (sending data):
async function createUser(userData) { const response = await fetch('https://api.example.com/users', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(userData) }); return response.json();}
Common options:
- •method:'GET', 'POST', 'PUT', 'DELETE'
- •headers:Additional info about the request
- •body:Data to send (for POST/PUT)
Response methods:
- •response.json() - Parse as JSON
- •response.text() - Get as plain text
- •response.blob() - Get binary data
Ready to practice? Try the exercise below to reinforce your learning!
Try it yourself
Create a function that fetches data from a public API (we'll simulate it).
Loading...