JSON Server

Fetching and sending JSON data to servers

🌐 What is JSON Server Communication?

JSON Server communication involves sending and receiving JSON data between your web application and a server. This is the foundation of modern web APIs and AJAX requests.


// Fetching JSON from server
fetch('https://api.example.com/users')
    .then(response => response.json())
    .then(data => console.log(data));
                                    

HTTP Methods for JSON

📥

GET

Retrieve JSON data from server

fetch('/api/users')
📤

POST

Send new JSON data to server

fetch('/api/users', {
  method: 'POST',
  body: JSON.stringify(data)
})
✏️

PUT

Update existing JSON data

fetch('/api/users/1', {
  method: 'PUT',
  body: JSON.stringify(data)
})
🗑️

DELETE

Remove data from server

fetch('/api/users/1', {
  method: 'DELETE'
})

🔹 Fetching JSON Data (GET Request)

Retrieve JSON data from a server using the Fetch API:

// Basic GET request
async function getUsers() {
    try {
        const response = await fetch('https://jsonplaceholder.typicode.com/users');
        
        // Check if request was successful
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        // Parse JSON response
        const users = await response.json();
        console.log(users);
        
        // Display first user
        console.log(`First user: ${users[0].name}`);
        
    } catch (error) {
        console.error('Error fetching users:', error);
    }
}

// Call the function
getUsers();

Expected Response:

[{id: 1, name: "Leanne Graham", username: "Bret", email: "[email protected]", ...}, ...]

First user: Leanne Graham

🔹 Sending JSON Data (POST Request)

Send JSON data to a server to create new resources:

// Create new user
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);
    }
}

// Example usage
const newUserData = {
    name: "John Doe",
    username: "johndoe",
    email: "[email protected]",
    phone: "555-1234"
};

createUser(newUserData);

Expected Response:

User created: {id: 11, name: "John Doe", username: "johndoe", email: "[email protected]", phone: "555-1234"}

🔹 Updating JSON Data (PUT Request)

Update existing data on the server:

// Update existing user
async function updateUser(userId, userData) {
    try {
        const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(userData)
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const updatedUser = await response.json();
        console.log('User updated:', updatedUser);
        return updatedUser;
        
    } catch (error) {
        console.error('Error updating user:', error);
    }
}

// Example usage
const updatedData = {
    id: 1,
    name: "Jane Smith",
    username: "janesmith",
    email: "[email protected]"
};

updateUser(1, updatedData);

🔹 Error Handling

Always handle errors when working with server requests:

// Comprehensive error handling
async function fetchWithErrorHandling(url) {
    try {
        const response = await fetch(url);
        
        // Check for HTTP errors
        if (!response.ok) {
            switch (response.status) {
                case 404:
                    throw new Error('Resource not found');
                case 500:
                    throw new Error('Server error');
                case 401:
                    throw new Error('Unauthorized access');
                default:
                    throw new Error(`HTTP error! status: ${response.status}`);
            }
        }
        
        // Check if response is JSON
        const contentType = response.headers.get('content-type');
        if (!contentType || !contentType.includes('application/json')) {
            throw new Error('Response is not JSON');
        }
        
        const data = await response.json();
        return data;
        
    } catch (error) {
        if (error instanceof TypeError) {
            console.error('Network error:', error.message);
        } else {
            console.error('Request error:', error.message);
        }
        throw error; // Re-throw for caller to handle
    }
}

🔹 Working with Real APIs

Examples using popular free APIs:

🔸 Weather API Example

// Fetch weather data
async function getWeather(city) {
    const apiKey = 'your-api-key';
    const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;
    
    try {
        const response = await fetch(url);
        const weatherData = await response.json();
        
        console.log(`Weather in ${city}:`);
        console.log(`Temperature: ${weatherData.main.temp}°C`);
        console.log(`Description: ${weatherData.weather[0].description}`);
        
    } catch (error) {
        console.error('Weather fetch error:', error);
    }
}

getWeather('London');

🔸 Posts API Example

// Fetch blog posts
async function getBlogPosts() {
    try {
        const response = await fetch('https://jsonplaceholder.typicode.com/posts?_limit=5');
        const posts = await response.json();
        
        posts.forEach(post => {
            console.log(`Title: ${post.title}`);
            console.log(`Body: ${post.body.substring(0, 50)}...`);
            console.log('---');
        });
        
    } catch (error) {
        console.error('Posts fetch error:', error);
    }
}

getBlogPosts();

🧠 Test Your Knowledge

Which HTTP method is used to retrieve JSON data from a server?