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 typetitle– A short, human-readable summary of the problem typestatus– The HTTP status code generated by the origin server for this occurrence of the problemdetail– A human-readable explanation specific to this occurrence of the probleminstance– 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 aPsr\Http\Message\UriInterfaceif specified, ornullgetTitle– Returns astringif specified, ornullgetStatus– Returns anint, or0if not specifiedgetDetail– Returns astringif specified, ornullgetInstance– Returns aPsr\Http\Message\UriInterfaceif specified, ornullgetExtensions– Returns an associativearrayof extension members, which may be empty__toString– The magic stringify method, which simply returns the JSON representationtoJson– Returns thestringJSON representationtoArray– Returns as associative array representation that can be converted to JSON
Utility Methods
send– Given aPsr\Http\Message\ResponseInterface, this method will return a response that includes the Problem Details as JSON, and will also set the correctContent-Typeheader ofapplication/problem+json