Fetch API

Fetch API Headers, Status Codes, and Responses

Work with request headers, response headers, HTTP status codes, and content types using Fetch.

Fetch API Headers, Status Codes, and Responses

HTTP status codes and headers tell the client how a request was handled. A reliable Fetch integration checks both the status and the response format.

Set request headers

const response = await fetch('/api/items.php', {
  headers: { 'Accept': 'application/json' }
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const contentType = response.headers.get('content-type') || '';
if (!contentType.includes('application/json')) {
  throw new Error('Expected a JSON response');
}
const data = await response.json();

Common status codes

  • 200 OK: request completed successfully.
  • 201 Created: a resource was created.
  • 400 Bad Request: request data is invalid.
  • 401 Unauthorized: authentication is required or invalid.
  • 403 Forbidden: the user is not allowed to perform the action.
  • 404 Not Found: the resource does not exist.
  • 422 Unprocessable Content: validation failed.
  • 500 Internal Server Error: an unexpected server failure occurred.

Design useful endpoints

Keep response formats consistent, include field-level validation errors where appropriate, and avoid exposing internal exception messages. Remember that Fetch does not automatically convert non-2xx responses into rejected promises.

Share this page Help other developers discover this resource.