What HTTP Content-Type header should be used when sending and receiving JSON? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

What HTTP Content-Type header should be used when sending and receiving JSON?

message-square
0

When sending and receiving JSON over HTTP, use Content-Type: application/json (or application/json; charset=utf-8 when explicitly specifying UTF-8 encoding), and pair it with Accept: application/json on requests to signal that your client expects a JSON response. By RFC 8259, JSON text exchanged over open protocols is UTF-8 by default, so application/json is the standard media type for REST APIs, webhooks, and JSON payloads.


1. Standard Request and Response Headers for JSON

Set Content-Type: application/json whenever the HTTP request or response body contains JSON, and use Accept: application/json on outgoing requests to declare your preferred response format:

# Sending JSON in an HTTP request
POST /api/items HTTP/1.1
Host: api.example.com
Content-Type: application/json
Accept: application/json

{"name":"Notebook","quantity":2}

# Receiving JSON in an HTTP response
HTTP/1.1 201 Created
Content-Type: application/json
Cache-Control: no-store

{"id":104,"name":"Notebook","quantity":2}
  • Use Content-Type for the body you send: Tells the server or client how to parse the current payload.
  • Use Accept for the body you want back: Tells the server you prefer JSON if multiple representations exist.

2. Sending and Receiving JSON in JavaScript with fetch()

In browser or Node.js fetch() calls, serialize request bodies with JSON.stringify(), set "Content-Type": "application/json", check response.ok, and parse responses with await response.json():

// Send a JSON payload and parse a JSON response safely with fetch()
async function postJson(url, payload) {
  if (typeof url !== "string" || url.length === 0) {
    throw new TypeError("Expected url to be a non-empty string.");
  }

  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Accept": "application/json"
    },
    body: JSON.stringify(payload)
  });

  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`HTTP ${response.status}: ${errorText}`);
  }

  return response.json();
}

// Example usage:
// const created = await postJson("https://api.example.com/items", { title: "Task" });
  • Always pair JSON.stringify() with application/json: Passing a raw object to body or omitting Content-Type can cause servers to reject or misread the request body.
  • Check response.ok before .json(): Error responses (4xx/5xx) sometimes return plain text or HTML rather than valid JSON.

3. Media Type Variants and Common Pitfalls

While application/json is the primary standard header, certain APIs use specialized JSON media types or run into common header mismatches:

// Inspecting and validating JSON Content-Type headers in server/client code
function isJsonContentType(contentTypeHeader) {
  if (typeof contentTypeHeader !== "string") return false;
  const mediaType = contentTypeHeader.split(";")[0].trim().toLowerCase();
  return mediaType === "application/json" || mediaType.endsWith("+json");
}

// Example usage:
console.log(isJsonContentType("application/json; charset=utf-8")); // true
console.log(isJsonContentType("application/problem+json"));         // true
console.log(isJsonContentType("text/plain"));                       // false
  • Structured +json types: Formats such as application/problem+json or application/vnd.api+json extend JSON with domain conventions while still being JSON payloads.
  • Avoid text/json or text/plain for JSON APIs: Non-standard or plain-text types can break strict body parsers, CORS preflight rules, or content-negotiation checks.