Json API


JSON-API is a specification for building REST APIs for CRUD (create, read, update, and delete) operations.Similar to GraphQL:

  • It allows the client to control what is returned in the response payload.
  • It provided an API extension (the patch extension that allowed multiple mutations to the graph to occur in a single request.
    Unlike GraphQL, the JSON-API specification spells out exactly how to perform common CRUD operations including complex graph mutations.JSON-API has no standardized schema introspection. However, Elide adds this capability to any service by exporting an Open API Initiative document (formerly known as Swagger).

The json-api specification is the best reference for understanding JSON-API. The following sections describe commonly used JSON-API features as well as Elide additions for filtering, pagination, sorting, and swagger.

Hierarchical URLs


Elide generally follows the JSON-API recommendations for URL design.

There are a few caveats given that Elide allows developers control over how entities are exposed:

  • Some entities may only be reached through a relationship to another entity. Not every entity is rootable.
  • The root path segment of URLs are by default the name of the class (lowercase). This can be overridden.
  • Elide allows relationships to be nested arbitrarily deep in URLs.
  • Elide currently requires all individual entities to be addressed by ID within a URL. For example, consider a model with an article and a singular author which has a singular address. While unambiguous, the following is not allowed: /articles/1/author/address.Instead, the author must be fully qualified by ID: /articles/1/author/34/address

    Model Identifiers


Elide supports three mechanisms by which a newly created entity is assigned an ID:

  • The ID is assigned by the client and saved in the data store.
  • The client doesn’t provide an ID and the data store generates one.
  • The client provides an ID which is replaced by one generated by the data store. When using the patch extension, the clientmust provide an ID to identify objects which are both created and added to collections in other objects. However, in some instancesthe server should have ultimate control over the ID that is assigned.
    Elide looks for the JPA GeneratedValue annotation to disambiguate whether or notthe data store generates an ID for a given data model. If the client also generated an ID during the object creation request, the data store ID overrides the client value.

Matching newly created objects to IDs

When using the patch extension, Elide returns object entity bodies (containing newly assigned IDs) in the order in which they were created. The client can use this order to map the object created to its server assigned ID.

Sparse Fields


JSON-API allows the client to limit the attributes and relationships that should be included in the response payloadfor any given entity. The fields query parameter specifies the type (data model) and list of fields that should be included.

For example, to fetch the book collection but only include the book titles:

  1. /book?fields[book]=title
  1. {
  2. "data": [
  3. {
  4. "attributes": {
  5. "title": "The Old Man and the Sea"
  6. },
  7. "id": "1",
  8. "type": "book"
  9. },
  10. {
  11. "attributes": {
  12. "title": "For Whom the Bell Tolls"
  13. },
  14. "id": "2",
  15. "type": "book"
  16. },
  17. {
  18. "attributes": {
  19. "title": "Enders Game"
  20. },
  21. "id": "3",
  22. "type": "book"
  23. }
  24. ]
  25. }

More information about sparse fields can be found here.

Compound Documents


JSON-API allows the client to fetch a primary collection of elements but also include their relationships or their relationship’s relationships (arbitrarily nested) through compound documents. The include query parameter specifieswhat relationships should be expanded in the document.

The following example fetches the book collection but also includes all of the book authors. Sparse fields are usedto limit the book and author fields in the response:

  1. /book?include=authors&fields[book]=title,authors&fields[author]=name
  1. {
  2. "data": [
  3. {
  4. "attributes": {
  5. "title": "The Old Man and the Sea"
  6. },
  7. "id": "1",
  8. "relationships": {
  9. "authors": {
  10. "data": [
  11. {
  12. "id": "1",
  13. "type": "author"
  14. }
  15. ]
  16. }
  17. },
  18. "type": "book"
  19. },
  20. {
  21. "attributes": {
  22. "title": "For Whom the Bell Tolls"
  23. },
  24. "id": "2",
  25. "relationships": {
  26. "authors": {
  27. "data": [
  28. {
  29. "id": "1",
  30. "type": "author"
  31. }
  32. ]
  33. }
  34. },
  35. "type": "book"
  36. },
  37. {
  38. "attributes": {
  39. "title": "Enders Game"
  40. },
  41. "id": "3",
  42. "relationships": {
  43. "authors": {
  44. "data": [
  45. {
  46. "id": "2",
  47. "type": "author"
  48. }
  49. ]
  50. }
  51. },
  52. "type": "book"
  53. }
  54. ],
  55. "included": [
  56. {
  57. "attributes": {
  58. "name": "Ernest Hemingway"
  59. },
  60. "id": "1",
  61. "type": "author"
  62. },
  63. {
  64. "attributes": {
  65. "name": "Orson Scott Card"
  66. },
  67. "id": "2",
  68. "type": "author"
  69. }
  70. ]
  71. }

More information about compound documents can be found here.

Filtering


JSON-API 1.0 is agnostic to filtering strategies. The only recommendation is that servers and clients _should_prefix filtering query parameters with the word ‘filter’.

Elide supports multiple filter dialects and the ability to add new ones to meet the needs of developers or to evolvethe platform should JSON-API standardize them. Elide’s primary dialect is RSQL

RSQL

RSQL is a query language that allows conjunction (and), disjunction (or), and parenthetic groupingof Boolean expressions. It is a superset of the FIQL language.

Because RSQL is a superset of FIQL, FIQL queries should be properly parsed.RSQL primarily adds more friendly lexer tokens to FIQL for conjunction and disjunction: ‘and’ instead of ‘;’ and ‘or’ instead of ‘,’.RSQL also adds a richer set of operators.

Filter Syntax

Filter query parameters look like filter[TYPE] where ‘TYPE’ is the name of the data model/entity.Any number of filter parameters can be specified provided the ‘TYPE’ is different for each parameter.

The value of any query parameter is a RSQL expression composed of predicates. Each predicate contains an attribute of the data model,an operator, and zero or more comparison values.

Filter Examples

Return all the books written by author ‘1’ with the genre exactly equal to ‘Science Fiction’:

/author/1/book?filter[book]=genre=='Science Fiction'

Return all the books written by author ‘1’ with the genre exactly equal to ‘Science Fiction’ and the title starts with ‘The’:

/author/1/book?filter[book]=genre=='Science Fiction';title==The*

Return all the books written by author ‘1’ with the publication date greater than a certain time or the genre not ‘Literary Fiction’or ‘Science Fiction’:

/author/1/book?filter[book]=publishDate>1454638927411,genre=out=('Literary Fiction','Science Fiction')

Return all the books whose title contains ‘Foo’. Include all the authors of those books whose name does not equal ‘Orson Scott Card’:

/book?include=authors&filter[book]=title==Foo&filter[author]=name!='Orson Scott Card'

Operators

The following RSQL operators are supported:

  • =in= : Evaluates to true if the attribute exactly matches any of the values in the list.
  • =out= : Evaluates to true if the attribute does not match any of the values in the list.
  • ==ABC* : Similar to SQL like 'ABC%.
  • ==*ABC : Similar to SQL like '%ABC.
  • ==ABC : Similar to SQL like '%ABC%.
  • =isnull=true : Evaluates to true if the attribute is null
  • =isnull=false : Evaluates to true if the attribute is not null
  • =lt= : Evaluates to true if the attribute is less than the value.
  • =gt= : Evaluates to true if the attribute is greater than the value.
  • =le= : Evaluates to true if the attribute is less than or equal to the value.
  • =ge= : Evaluates to true if the attribute is greater than or equal to the value.

    Values & Type Coercion

Values are specified as URL encoded strings. Elide will type coerce them into the appropriate primitive data type for the attribute filter.

Pagination


Elide supports:

  • Paginating a collection by row offset and limit.
  • Paginating a collection by page size and number of pages.
  • Returning the total size of a collection visible to the given user.
  • Returning a meta block in the JSON-API response body containing metadata about the collection.
  • A simple way to control:
    • the availability of metadata
    • the number of records that can be paginated

      Syntax

Elide allows pagination of the primary collection being returned in the response via the page query parameter.

The rough BNF syntax for the page query parameter is:

  1. <QUERY> ::=
  2. "page" "[" "size" "]" "=" <INTEGER>
  3. | "page" "[" "number" "]" "=" <INTEGER>
  4. | "page" "[" "limit" "]" "=" <INTEGER>
  5. | "page" "[" "offset" "]" "=" <INTEGER>
  6. | "page" "[" "totals" "]"

Legal combinations of the page query params include:

  • size
  • number
  • size & number
  • size & number & totals
  • offset
  • limit
  • offset & limit
  • offset & limit & totals

    Meta Block

Whenever a page query parameter is specified, Elide will return a meta block in theJSON-API response that contains:

  • The page number
  • The page size or limit
  • The total number of pages (totalPages) in the collection
  • The total number of records (totalRecords) in the collection.
    The values for totalPages and totalRecords are only returned if the page[totals] parameter was specified in the query.

Example

Paginate the book collection starting at the 4th record. Include no more than 2 books per page.Include the total size of the collection in the meta block:

  1. /book?page[offset]=3&page[limit]=2&page[totals]
  1. {
  2. "data": [
  3. {
  4. "attributes": {
  5. "chapterCount": 0,
  6. "editorName": null,
  7. "genre": "Science Fiction",
  8. "language": "English",
  9. "publishDate": 1464638927412,
  10. "title": "Enders Shadow"
  11. },
  12. "id": "4",
  13. "relationships": {
  14. "authors": {
  15. "data": [
  16. {
  17. "id": "2",
  18. "type": "author"
  19. }
  20. ]
  21. },
  22. "chapters": {
  23. "data": []
  24. },
  25. "publisher": {
  26. "data": null
  27. }
  28. },
  29. "type": "book"
  30. },
  31. {
  32. "attributes": {
  33. "chapterCount": 0,
  34. "editorName": null,
  35. "genre": "Science Fiction",
  36. "language": "English",
  37. "publishDate": 0,
  38. "title": "Foundation"
  39. },
  40. "id": "5",
  41. "relationships": {
  42. "authors": {
  43. "data": [
  44. {
  45. "id": "3",
  46. "type": "author"
  47. }
  48. ]
  49. },
  50. "chapters": {
  51. "data": []
  52. },
  53. "publisher": {
  54. "data": null
  55. }
  56. },
  57. "type": "book"
  58. }
  59. ],
  60. "meta": {
  61. "page": {
  62. "limit": 2,
  63. "number": 2,
  64. "totalPages": 4,
  65. "totalRecords": 8
  66. }
  67. }
  68. }

Sorting


Elide supports:

  • Sorting a collection by any attribute of the collection’s type.
  • Sorting a collection by multiple attributes at the same time in either ascending or descending order.
  • Sorting a collection by any attribute of a to-one relationship of the collection’s type. Multiple relationships can be traversed provided the path from the collection to the sorting attribute is entirely through to-one relationships.

    Syntax

Elide allows sorting of the primary collection being returned in the response via the sort query parameter.

The rough BNF syntax for the sort query parameter is:

  1. <QUERY> ::= "sort" "=" <LIST_OF_SORT_SPECS>
  2. <LIST_OF_SORT_SPECS> = <SORT_SPEC> | <SORT_SPEC> "," <LIST_OF_SORT_SPECS>
  3. <SORT_SPEC> ::= "+|-"? <PATH_TO_ATTRIBUTE>
  4. <PATH_TO_ATTRIBUTE> ::= <RELATIONSHIP> <PATH_TO_ATTRIBUTE> | <ATTRIBUTE>
  5. <RELATIONSHIP> ::= <TERM> "."
  6. <ATTRIBUTE> ::= <TERM>

Sort By ID

The keyword id can be used to sort by whatever field a given entity uses as its identifier.

Example

Sort the collection of author 1’s books in descending order by the book’s publisher’s name:

  1. /author/1/books?sort=-publisher.name
  1. {
  2. "data": [
  3. {
  4. "attributes": {
  5. "chapterCount": 0,
  6. "editorName": null,
  7. "genre": "Literary Fiction",
  8. "language": "English",
  9. "publishDate": 0,
  10. "title": "For Whom the Bell Tolls"
  11. },
  12. "id": "2",
  13. "relationships": {
  14. "authors": {
  15. "data": [
  16. {
  17. "id": "1",
  18. "type": "author"
  19. }
  20. ]
  21. },
  22. "chapters": {
  23. "data": []
  24. },
  25. "publisher": {
  26. "data": {
  27. "id": "2",
  28. "type": "publisher"
  29. }
  30. }
  31. },
  32. "type": "book"
  33. },
  34. {
  35. "attributes": {
  36. "chapterCount": 0,
  37. "editorName": null,
  38. "genre": "Literary Fiction",
  39. "language": "English",
  40. "publishDate": 0,
  41. "title": "The Old Man and the Sea"
  42. },
  43. "id": "1",
  44. "relationships": {
  45. "authors": {
  46. "data": [
  47. {
  48. "id": "1",
  49. "type": "author"
  50. }
  51. ]
  52. },
  53. "chapters": {
  54. "data": []
  55. },
  56. "publisher": {
  57. "data": {
  58. "id": "1",
  59. "type": "publisher"
  60. }
  61. }
  62. },
  63. "type": "book"
  64. }
  65. ]
  66. }

Bulk Writes And Complex Mutations


JSON-API supported a now-deprecated mechanism for extensions.The patch extension was a JSON-API extension that allowed muliple mutation operations (create, delete, update) to be bundled together in as single request.

Elide supports the JSON-API patch extension because it allows complex & bulk edits to the data model in the context of a single transaction.For example, the following request creates an author (earnest hemingway), multiple of his books, and his book publisher in a single request:

  1. [
  2. {
  3. "op": "add",
  4. "path": "/author",
  5. "value": {
  6. "id": "12345678-1234-1234-1234-1234567890ab",
  7. "type": "author",
  8. "attributes": {
  9. "name": "Ernest Hemingway"
  10. },
  11. "relationships": {
  12. "books": {
  13. "data": [
  14. {
  15. "type": "book",
  16. "id": "12345678-1234-1234-1234-1234567890ac"
  17. },
  18. {
  19. "type": "book",
  20. "id": "12345678-1234-1234-1234-1234567890ad"
  21. }
  22. ]
  23. }
  24. }
  25. }
  26. },
  27. {
  28. "op": "add",
  29. "path": "/book",
  30. "value": {
  31. "type": "book",
  32. "id": "12345678-1234-1234-1234-1234567890ac",
  33. "attributes": {
  34. "title": "The Old Man and the Sea",
  35. "genre": "Literary Fiction",
  36. "language": "English"
  37. },
  38. "relationships": {
  39. "publisher": {
  40. "data": {
  41. "type": "publisher",
  42. "id": "12345678-1234-1234-1234-1234567890ae"
  43. }
  44. }
  45. }
  46. }
  47. },
  48. {
  49. "op": "add",
  50. "path": "/book",
  51. "value": {
  52. "type": "book",
  53. "id": "12345678-1234-1234-1234-1234567890ad",
  54. "attributes": {
  55. "title": "For Whom the Bell Tolls",
  56. "genre": "Literary Fiction",
  57. "language": "English"
  58. }
  59. }
  60. },
  61. {
  62. "op": "add",
  63. "path": "/book/12345678-1234-1234-1234-1234567890ac/publisher",
  64. "value": {
  65. "type": "publisher",
  66. "id": "12345678-1234-1234-1234-1234567890ae",
  67. "attributes": {
  68. "name": "Default publisher"
  69. }
  70. }
  71. }
  72. ]
  1. [
  2. {
  3. "data": {
  4. "attributes": {
  5. "name": "Ernest Hemingway"
  6. },
  7. "id": "1",
  8. "relationships": {
  9. "books": {
  10. "data": [
  11. {
  12. "id": "1",
  13. "type": "book"
  14. },
  15. {
  16. "id": "2",
  17. "type": "book"
  18. }
  19. ]
  20. }
  21. },
  22. "type": "author"
  23. }
  24. },
  25. {
  26. "data": {
  27. "attributes": {
  28. "chapterCount": 0,
  29. "editorName": null,
  30. "genre": "Literary Fiction",
  31. "language": "English",
  32. "publishDate": 0,
  33. "title": "The Old Man and the Sea"
  34. },
  35. "id": "1",
  36. "relationships": {
  37. "authors": {
  38. "data": [
  39. {
  40. "id": "1",
  41. "type": "author"
  42. }
  43. ]
  44. },
  45. "chapters": {
  46. "data": []
  47. },
  48. "publisher": {
  49. "data": {
  50. "id": "1",
  51. "type": "publisher"
  52. }
  53. }
  54. },
  55. "type": "book"
  56. }
  57. },
  58. {
  59. "data": {
  60. "attributes": {
  61. "chapterCount": 0,
  62. "editorName": null,
  63. "genre": "Literary Fiction",
  64. "language": "English",
  65. "publishDate": 0,
  66. "title": "For Whom the Bell Tolls"
  67. },
  68. "id": "2",
  69. "relationships": {
  70. "authors": {
  71. "data": [
  72. {
  73. "id": "1",
  74. "type": "author"
  75. }
  76. ]
  77. },
  78. "chapters": {
  79. "data": []
  80. },
  81. "publisher": {
  82. "data": null
  83. }
  84. },
  85. "type": "book"
  86. }
  87. },
  88. {
  89. "data": {
  90. "attributes": {
  91. "name": "Default publisher"
  92. },
  93. "id": "1",
  94. "type": "publisher"
  95. }
  96. }
  97. ]

Swagger


Swagger documents can be highly customized. As a result, they are not enabled by default and instead must be initialized through code. The steps to do this are documented here.

原文: http://elide.io/pages/guide/10-jsonapi.html