JavaScript · Intermediate level

Intermediate level · Module 3: Fetch, APIs and JSON in the Browser · Lesson 2 of 3

Sending Data and Working with Headers

Send JSON to an API with POST, set headers and handle validation errors returned by the server.

In this lesson you will

  • Send JSON with POST and the right headers
  • Handle 400-level responses that describe validation errors

Key concepts

method and bodyContent-Type headerJSON.stringify for bodiesvalidation error responses

The lesson

To send data, pass options to fetch: method: "POST", headers: { "Content-Type": "application/json" } and body: JSON.stringify(data). The server uses the Content-Type header to know how to read the body.

Servers reply with 201 Created for new resources, 400 Bad Request or 422 Unprocessable Entity for invalid data, often with a JSON body explaining what is wrong. Show those messages next to the relevant form fields.

Never put secrets such as API keys in browser JavaScript: anyone can read them in DevTools. Requests that need secrets must go through a server you control.

Step by step

  1. Send a POST request with a JSON body to a practice API.
  2. Check for 201 and display the created item.
  3. Send invalid data and display the server's error messages.
  4. Find the request and its headers in the Network tab.

Practice activity

Connect a registration form to a practice API so that valid submissions are saved and server-side errors appear next to the fields.

Expected result: Valid registrations are confirmed; invalid ones show the server's messages beside the right fields.

Check your understanding

  1. Which header tells the server the body is JSON?

    Show answer

    Content-Type: application/json.

  2. Why must API secrets not be in browser code?

    Show answer

    Anyone can read browser code and network requests.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.