API Pattern: Self-documenting REST Responses

Here is an example of a self-documenting REST response. Ideally every API call should let the developer append a param like help=true to get details such as calling context, documentation links, examples, and related/further calls that might be made. Of course, those additional URLs also include the help=true to ensure hypertext-powered API browser surfing is possible (Further calls might also be part of the response in some cases, following the HATEOAS model.)

javascript

  1. {
  2.   type: 'post',
  3.   id: 123,
  4.   title: 'How to make pancakes',
  5.   ...
  6.   # other normal response stuff
  7.   ...
  8.   # some calling context help
  9.   caller: {
  10.     type: 'user',
  11.     id: 789,
  12.     name: 'happyjoy',
  13.     role: 'member'
  14.   },
  15.   # general docs link
  16.   docs: 'https://example.com/docs/posts#get',
  17.   # usage examples for this particular resource
  18.   examples: [
  19.     {
  20.        url: 'https://example.com/posts/123?help=true',
  21.        explanation: 'get post 123'
  22.     }
  23.     {
  24.        url: 'https://example.com/posts/123?metadata=true?help=true',
  25.        explanation: 'get only metadata for post 123 (omits the description)'
  26.     }<br />
  27.   ],
  28.   # calls related to this particular resource
  29.   related: [
  30.     {
  31.       comments: [
  32.         {
  33.           url: 'https://example.com/posts/123/comments?help=true',
  34.           explanation: 'get comments for this post'
  35.         }
  36.       ],
  37.       owner: [
  38.         {
  39.           url: 'https://example.com/users/5555?help=true',
  40.           explanation: 'get author details'
  41.         }
  42.       ]
  43.       editor: [
  44.         {
  45.           url: 'https://example.com/users/8888?help=true',
  46.           explanation: 'get editor details'
  47.         }
  48.       ]
  49.     }
  50.   ]
  51. }

One thought on “API Pattern: Self-documenting REST Responses

  1. Pingback: Dew Drop – April 26, 2015 (#2002) | Morning Dew

Leave a Reply