JAVASCRIPT
Submitting JSON Data to an API using Fetch POST
Demonstrates how to send POST requests with JSON payloads to a REST API using the native Fetch API in JavaScript, ensuring proper headers and data serialization for effective communication.
async function postJsonData(url, data) {
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json' // Often good practice to include
},
body: JSON.stringify(data) // Convert JavaScript object to JSON string
});
if (!response.ok) {
const errorText = await response.text(); // Get raw error message
throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
}
const result = await response.json(); // Assuming the API responds with JSON
console.log('Success:', result);
return result;
} catch (error) {
console.error('Error submitting data:', error);
throw error; // Re-throw to allow caller to handle
}
}
// Example usage:
// const newData = { title: 'foo', body: 'bar', userId: 1 };
// postJsonData('https://jsonplaceholder.typicode.com/posts', newData)
// .then(response => console.log('API Response:', response))
// .catch(err => console.error('Submission failed:', err));
How it works: This snippet illustrates how to send data to an API using an HTTP POST request with a JSON payload. It uses the `fetch` API, setting the `method` to 'POST' and configuring the `headers` to specify `Content-Type: application/json`. The JavaScript object `data` is converted into a JSON string using `JSON.stringify()` before being sent in the `body` of the request. Robust error checking for non-OK responses is included, along with parsing the API's JSON response.