JAVASCRIPT

Submitting JSON Data to a REST API (POST/PUT)

Master sending JSON payloads to API endpoints for creating or updating resources, demonstrating common practices with HTTP POST or PUT requests in JavaScript.

async function submitJsonData(url, method, data) {
  try {
    const response = await fetch(url, {
      method: method, // 'POST' for creation, 'PUT' for update
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    });

    if (!response.ok) {
      // Attempt to read error message from response body
      const errorBody = await response.json().catch(() => ({ message: `HTTP error! Status: ${response.status}` }));
      throw new Error(errorBody.message || `HTTP error! Status: ${response.status}`);
    }

    // If the API returns content for POST/PUT (e.g., created resource),
    // you might want to parse it. Otherwise, check response.status.
    const responseData = await response.json().catch(() => ({})); // Handle empty response body
    console.log('API Response:', responseData);
    return responseData;
  } catch (error) {
    console.error(`Error submitting data with ${method}:`, error);
    throw error;
  }
}

// Example usage for POST:
// const postUrl = 'https://api.example.com/items';
// const newItem = { name: 'New Item', value: 123 };
// submitJsonData(postUrl, 'POST', newItem);

// Example usage for PUT:
// const putUrl = 'https://api.example.com/items/123';
// const updatedItem = { name: 'Updated Item', value: 456 };
// submitJsonData(putUrl, 'PUT', updatedItem);
How it works: This snippet illustrates how to send JSON data to an API using `POST` (for creating new resources) or `PUT` (for updating existing ones). It correctly sets the `Content-Type` header to `application/json` and stringifies the JavaScript object into a JSON string for the request body. Robust error handling is included, attempting to extract error messages from the API's response body.

Need help integrating this into your project?

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

Hire DigitalCodeLabs