Skip to main content

API RFC 7807 Builder

v1.0.0

Problem Details JSON builder (legacy RFC 7807) — useful for older API contracts.

RFC 7807 Error Library
// RFC 7807 Problem Details helper

export interface ProblemDetail {
  type: string;
  title: string;
  status: number;
  detail?: string;
  instance?: string;
  [key: string]: unknown;
}

export enum ProblemType {
  VALIDATION_ERROR = "validation-error",
  NOT_FOUND = "not-found",
  UNAUTHORIZED = "unauthorized",
  FORBIDDEN = "forbidden",
  RATE_LIMITED = "rate-limited",
  INTERNAL_ERROR = "internal-error"
}

export class Problems {
  private readonly base: string;
  constructor(base = "https://api.example.com/problems") { this.base = base; }

  create(code: string, status: number, title: string, detail?: string, instance?: string): ProblemDetail {
    return { type: this.base + "/" + code, title, status, ...(detail ? { detail } : {}), ...(instance ? { instance } : {}) };
  }

  validationError(detail?: string, instance?: string): ProblemDetail {
    return this.create("validation-error", 422, "Validation Failed", detail, instance);
  }
  notFound(detail?: string, instance?: string): ProblemDetail {
    return this.create("not-found", 404, "Resource Not Found", detail, instance);
  }
  unauthorized(detail?: string, instance?: string): ProblemDetail {
    return this.create("unauthorized", 401, "Unauthorized", detail, instance);
  }
  forbidden(detail?: string, instance?: string): ProblemDetail {
    return this.create("forbidden", 403, "Forbidden", detail, instance);
  }
  rateLimited(detail?: string, instance?: string): ProblemDetail {
    return this.create("rate-limited", 429, "Too Many Requests", detail, instance);
  }
  internalError(detail?: string, instance?: string): ProblemDetail {
    return this.create("internal-error", 500, "Internal Server Error", detail, instance);
  }
}

export const problems = new Problems("https://api.example.com/problems");