Back to Tutorials
API Integration with JSON Tutorial
Lesson 1 of 2: Fetch API Basics
Progress50%
Fetch API Basics
The Fetch API provides a modern way to make HTTP requests in JavaScript. It returns promises and works well with async/await syntax. Key concepts: • Promise-based API • Request and Response objects • HTTP methods (GET, POST, PUT, DELETE) • Headers and request configuration • JSON parsing with .json() method Fetch syntax: fetch(url, options) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)) Common patterns: • GET requests for fetching data • POST requests for creating data • Error handling with try/catch • Loading states during requests
Example
// Basic GET request
async function fetchUsers() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const users = await response.json();
console.log(users);
return users;
} catch (error) {
console.error('Error fetching users:', error);
throw error;
}
}
// POST request with JSON data
async function createUser(userData) {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(userData)
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const newUser = await response.json();
console.log('User created:', newUser);
return newUser;
} catch (error) {
console.error('Error creating user:', error);
throw error;
}
}
// Usage
fetchUsers();
createUser({ name: 'John Doe', email: 'john@example.com' });Exercise
Create a function that: 1. Fetches posts from 'https://jsonplaceholder.typicode.com/posts' 2. Handles loading state 3. Handles errors properly 4. Returns the data or null on error 5. Logs appropriate messages
Lesson 1 of 2