Recipe 4.3

Sending a POST Request With the Fetch API

This example sends a POST request to an endpoint that will echo back the body and headers that were sent to it.

Fill out the user form and click “Create User”.

Demo

Create User

Response


Code

JavaScript
/**
 * Creates a new user by sending a POST request to /api/users.
 * @param firstName The user's first name
 * @param lastName The user's last name
 * @param department The user's department
 * @returns a Promise that resolves to the API response body
 */
function createUser(firstName, lastName, department) {
  return fetch('/api/users', {
    method: 'POST',
    body: JSON.stringify({ firstName, lastName, department }),
    headers: {
      'Content-Type': 'application/json'
    }
  })
    .then(response => response.json())
    .catch(error => console.error('Error:', error.message));
}

const form = document.querySelector('#user-form');
form.addEventListener('submit', event => {
  event.preventDefault();

  const { firstName, lastName, department } = form.elements;
  console.log(department.value);

  createUser(firstName.value, lastName.value, department.value)
    .then(data => {
      const result = document.querySelector('#response');
      result.querySelector('pre').textContent = JSON.stringify(data, null, 2);
      result.classList.remove('d-none');
    });
});
HTML
<h3>Create User</h3>
<form id="user-form">
  <div class="mb-3">
    <label for="firstName" class="form-label">First name</label>
    <input type="text" class="form-control" id="firstName" name="firstName" required>
  </div>
  <div class="mb-3">
    <label for="lastName" class="form-label">Last name</label>
    <input type="text" class="form-control" id="lastName" name="lastName" required>
  </div>
  <div class="mb-3">
    <label for="department" class="form-label">Department</label>
    <select class="form-select" id="department" name="department">
      <option>Sales</option>
      <option>Marketing</option>
      <option>Human Resources</option>
      <option>Finance</option>
      <option>Engineering</option>
    </select>
  </div>
  <button class="btn btn-primary">Create User</button>
</form>

<div id="response" class="mt-3 d-none">
  <h4>Response</h4>
  <pre class="bg-success-subtle p-2"></pre>
</div>
Web API Cookbook
Joe Attardi