API Problem Details for HTTP APIs

9.0.2 · active · verified Sun Apr 19

api-problem is a JavaScript utility library designed to standardize error responses in HTTP APIs according to RFC 7807, "Problem Details for HTTP APIs." It provides a `Problem` class that allows developers to construct detailed, machine-readable error objects for various HTTP status codes. These objects include a status, human-readable title, a URI identifying the problem type (which defaults to MDN HTTP status pages since v9), and optional additional fields. The current stable version is 9.0.2. The library maintains an active release cadence, primarily focusing on security updates, dependency bumps, CI/CD improvements, and dropping support for older Node.js versions to align with modern JavaScript ecosystems. Its core differentiator is strict adherence to the RFC 7807 specification, ensuring consistent and interoperable error communication across different API clients and servers.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates the creation of various RFC 7807 problem detail objects with default HTTP meanings, custom titles, types, and additional application-specific details, including how to send a problem as an HTTP response.

import Problem from 'api-problem';
import http from 'http';

// Create a basic 404 Not Found problem
const notFoundProblem = new Problem(404);
console.log('Basic 404 Problem:', notFoundProblem.toObject());

// Create a 403 Forbidden problem with a custom title
const forbiddenProblem = new Problem(403, 'Access to resource denied');
console.log('Custom Title Problem:', forbiddenProblem.toObject());

// Create a custom problem type with additional details
const outOfCreditProblem = new Problem(
  403,
  'You do not have enough credit',
  'https://example.com/probs/out-of-credit',
  {
    detail: 'Your current balance is 30, but that costs 50 for this operation.',
    instance: '/account/12345/transactions/abc',
    balance: 30
  }
);
console.log('Custom Detailed Problem:', outOfCreditProblem.toObject());

// Example of sending a problem via an HTTP response (Node.js http module)
const server = http.createServer((req, res) => {
  if (req.url === '/error') {
    const problem = new Problem(400, 'Invalid parameters in request', 'https://example.com/probs/invalid-params', {
      errors: [
        { field: 'param1', message: 'Must be a number' },
        { field: 'param2', message: 'Cannot be empty' }
      ]
    });
    problem.send(res);
  } else {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello World');
  }
});

// server.listen(3000, () => console.log('Server running on http://localhost:3000'));
// To test: curl -i http://localhost:3000/error
// (Uncomment server.listen and run the file to test the .send() method)

view raw JSON →