JAVASCRIPT

Idempotent API Requests with Idempotency-Key (Node.js)

Prevent duplicate operations in API integrations by sending unique 'Idempotency-Key' headers, crucial for reliable transaction processing in Node.js.

const axios = require('axios');
const { v4: uuidv4 } = require('uuid'); // For generating unique keys

// This function simulates making an idempotent request to an external API
async function makeIdempotentApiRequest(url, data, idempotencyKey = uuidv4()) {
    try {
        console.log(`Making idempotent request to ${url} with Idempotency-Key: ${idempotencyKey}`);
        const response = await axios.post(url, data, {
            headers: {
                'Content-Type': 'application/json',
                'Idempotency-Key': idempotencyKey
            }
        });
        console.log('API Response:', response.data);
        return response.data;
    } catch (error) {
        if (error.response) {
            console.error(`Error ${error.response.status}:`, error.response.data);
        } else if (error.request) {
            console.error('No response received:', error.request);
        } else {
            console.error('Request setup error:', error.message);
        }
        throw error;
    }
}

// Example Usage:
(async () => {
    const externalApiUrl = 'https://jsonplaceholder.typicode.com/posts'; // Using a public API for demonstration, though it won't process idempotency
    const payload = {
        title: 'Idempotent Test Post',
        body: 'This is a test post for idempotency demonstration.',
        userId: 1
    };

    // First request
    console.log('--- First Request ---');
    try {
        const key1 = uuidv4();
        await makeIdempotentApiRequest(externalApiUrl, payload, key1);
        console.log('First request successful.');
    } catch (e) {
        console.error('First request failed.');
    }

    // Sending the exact same request with the same idempotency key
    // A real idempotent API would process this only once, or return the original result.
    console.log('
--- Second Request with SAME Idempotency-Key ---');
    try {
        const key2 = 'a-fixed-unique-key-for-test'; // Use a fixed key to simulate re-sending
        await makeIdempotentApiRequest(externalApiUrl, payload, key2);
        console.log('Second request (same key) successful. A real API would handle this without side-effects.');
    } catch (e) {
        console.error('Second request (same key) failed.');
    }
})();
How it works: This Node.js snippet illustrates how to implement idempotent API requests using the 'Idempotency-Key' header. By including a unique, client-generated key with each request that modifies data (e.g., creating a resource, processing a payment), you ensure that even if the request is sent multiple times due to network issues or retries, the operation is only executed once on the server. The `uuid` library helps generate these unique keys for each distinct operation.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs