JAVASCRIPT
Transforming Request Payload Before API Submission
Learn to restructure and transform your local data objects into the specific format required by an API before sending the request payload using JavaScript's Fetch API.
async function createUser(localUserData) {
// Assume localUserData looks like this:
// { firstName: 'John', lastName: 'Doe', emailAddress: '[email protected]', passwordHash: 'hashedpassword' }
// API expects data in a different format:
// { user_name: 'John Doe', user_email: '[email protected]', auth_pass: 'hashedpassword' }
const apiPayload = {
user_name: `${localUserData.firstName} ${localUserData.lastName}`,
user_email: localUserData.emailAddress,
auth_pass: localUserData.passwordHash
};
try {
const response = await fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(apiPayload) // Send the transformed payload
});
if (!response.ok) {
const errorData = await response.json();
console.error('API Error:', errorData);
throw new Error(`HTTP error! Status: ${response.status}`);
}
const createdUser = await response.json();
console.log('User created successfully:', createdUser);
return createdUser;
} catch (error) {
console.error('Error creating user:', error);
throw error;
}
}
// Example usage:
// const userToCreate = {
// firstName: 'Jane',
// lastName: 'Smith',
// emailAddress: '[email protected]',
// passwordHash: 'anotherhashedpass'
// };
// createUser(userToCreate)
// .then(data => console.log('Successfully created:', data))
// .catch(err => console.error('Failed to create user:', err));
How it works: This snippet demonstrates how to transform a local data object into a format expected by a backend API before sending a request. It's common for frontend applications to use a different data structure than what the API expects for creating or updating resources. The code explicitly maps properties from the `localUserData` object to the `apiPayload` object, renaming keys, combining fields (like `firstName` and `lastName` into `user_name`), and ensuring the data conforms to the API's schema before it's sent via a POST request.