brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Return API errors as application/problem+json

Json
~/tips/tip-rest-problem-details-application-problem-json

Content-Type: application/problem+json

RFC 9457 defines a standard JSON shape for HTTP API errors, so clients don't parse a new format per API.

Every API seems to invent its own error JSON. One uses message, one uses error, one nests it two levels deep. RFC 9457 has a standard shape for this, and it is smaller than you’d expect.

HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json

{
  "type": "https://example.net/validation-error",
  "title": "Your request is not valid.",
  "status": 422,
  "detail": "age must be a positive integer"
}

The media type is application/problem+json. The RFC defines five members:

  • type: a URI that identifies the problem type. If it is missing, it counts as about:blank. Absolute URIs are recommended.
  • status: the HTTP status code. It is advisory, and the real response must use the same code.
  • title: a short summary of the problem type. It should not change between occurrences, except for localisation.
  • detail: an explanation specific to this occurrence.
  • instance: a URI that identifies this particular occurrence.

You can add your own members. The RFC’s validation example adds an errors array with a detail and a pointer per field.

A small Python test server returning the body above made curl 8.5.0 show the application/problem+json content type on a 422 response.

One caveat: consumers should not parse detail for information, since it is for humans. Put anything a client needs to act on in its own extension member.

Further reading: RFC 9457: Problem Details for HTTP APIs

More Json tips curl -s -X PATCH -H 'Content-Type: application/merge-patch+json' \ echo '{"id":1,"payload":"{\"user\":\"ann\",\"tags\":[\"x\",\"y\"]}"}' | jq -c '.payload | fromjson | .tags' jq empty config.json Paths() tells you where in a big JSON document a value lives jq -c --slurpfile u users.json ' All Json tips (11) All topics

Link