RFC 7807 Problem Details for HTTP APIs

RFC 7807 introduced an excellent, standardized means to report problems that occurred as a result of invoking a REST API to the client. We added the Caridea\Http\ProblemDetails class to output RFC 7807 compliant JSON.

The RFC defines several pieces of information common to all Problem Details Objects.

  • type – A URI reference that identifies the problem type
  • title – A short, human-readable summary of the problem type
  • status – The HTTP status code generated by the origin server for this occurrence of the problem
  • detail – A human-readable explanation specific to this occurrence of the problem
  • instance – A URI reference that identifies the specific occurrence of the problem

Any additional members on the object can be specified via an associative array passed as the $extensions parameter.

Quick Example

Take for example the following:

use Caridea\Http\ProblemDetails;
use Zend\Diactoros\Uri;

$problem = new ProblemDetails(
    new Uri('http://example.com/problem/oops'),  // type
    'A weird thing happened',                    // title
    500,                                         // status
    'It looks like the server has goofed again', // detail
    new Uri('http://example.com/problems/1f9a'), // instance
    [                                            // extensions
        'server' => 'workerbee01.example.com',
        'auth' => 'foobar'
    ]
);
echo json_encode($problem);

Since ProblemDetails implements JsonSerializable, this example would output:

{"type":"http:\/\/example.com\/problem\/oops","title":"A weird thing happened","status":500,"detail":"It looks like the server has goofed again","instance":"http:\/\/example.com\/problems\/1f9a","server":"workerbee01.example.com","auth":"foobar"}

Methods

The class is immutable, therefore has no setter methods. All necessary data is passed in to the constructor. However, there are several other methods of note in this class:

Getter Methods

  • getType – Returns a Psr\Http\Message\UriInterface if specified, or null
  • getTitle – Returns a string if specified, or null
  • getStatus – Returns an int, or 0 if not specified
  • getDetail – Returns a string if specified, or null
  • getInstance – Returns a Psr\Http\Message\UriInterface if specified, or null
  • getExtensions – Returns an associative array of extension members, which may be empty
  • __toString – The magic stringify method, which simply returns the JSON representation
  • toJson – Returns the string JSON representation
  • toArray – Returns as associative array representation that can be converted to JSON

Utility Methods

  • send – Given a Psr\Http\Message\ResponseInterface, this method will return a response that includes the Problem Details as JSON, and will also set the correct Content-Type header of application/problem+json