You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
JSONAPI::Serializers is a simple library for serializing Ruby objects and their relationships into the [JSON:API format](http://jsonapi.org/format/).
4
4
5
-
Note: as of writing, the JSON:API spec has not reached v1 and is still undergoing changes. This library supports RC3+ and aims to keep up with the continuing development changes.
5
+
As of writing, the JSON:API spec is approaching v1 and still undergoing changes. This library supports RC3+ and aims to keep up with the continuing development changes.
6
+
7
+
*[Features](#features)
8
+
*[Installation](#installation)
9
+
*[Usage](#usage)
10
+
*[Define a serializer](#define-a-serializer)
11
+
*[Serialize an object](#serialize-an-object)
12
+
*[Serialize a collection](#serialize-a-collection)
13
+
*[Null handling](#null-handling)
14
+
*[Custom attributes](#custom-attributes)
15
+
*[More customizations](#more-customizations)
16
+
*[Relationships](#relationships)
17
+
*[Compound documents and includes](#compound-documents-and-includes)
* Works with **any Ruby web framework**, including Rails, Sinatra, etc. This is a pure Ruby library.
10
26
* Supports the readonly features of the JSON:API spec.
11
-
***Full support for compound documents** ("side-loaded" objects) and the `include` parameter.
27
+
***Full support for compound documents** ("side-loading") and the `include` parameter.
12
28
* Similar interface to ActiveModel::Serializers, should provide an easy migration path.
13
-
* Intentionally unopinionated, allows you to structure your app however you would like and then serialize the objects at the end.
14
-
15
-
JSONAPI::Serializers was built as an intentionally simple serialization interface. It makes no assumptions about your database structure or routes and it does not provide controllers or any create/update interface to your objects. It is a library, not a framework. You will probably still need to do work to make your API fully compliant with the nuances of the [JSON:API spec](http://jsonapi.org/format/), for things like supporting `/links` routes and of course for implementing any mutation action like PATCH or creating objects. If you are looking for a more complete and opiniated framework, see the [jsonapi-resources](https://github.com/cerebris/jsonapi-resources) project.
29
+
* Intentionally unopinionated and simple, allows you to structure your app however you would like and then serialize the objects at the end.
16
30
17
-
Note: still under development, doesn't currently support certain readonly things like `fields`, but I'd like to.
31
+
JSONAPI::Serializers was built as an intentionally simple serialization interface. It makes no assumptions about your database structure or routes and it does not provide controllers or any create/update interface to the objects. It is a library, not a framework. You will probably still need to do work to make your API fully compliant with the nuances of the [JSON:API spec](http://jsonapi.org/format/), for things like supporting `/links` routes and for supporting write actions like creating or updating objects. If you are looking for a more complete and opinionated framework, see the [jsonapi-resources](https://github.com/cerebris/jsonapi-resources) project.
> Note: the JSON:API spec makes a specific distinction in how null `linkage` information is presented for single objects vs. collections, so you must always provide `is_collection: true` when serializing multiple objects. If you attempt to serialize multiple objects without this flag (or a single object with it) a `JSONAPI::Serializer::AmbiguousCollectionError` will be raised.
118
+
You must always pass `is_collection: true` when serializing a collection, see [Null handling](#null-handling).
Note that the JSON:API spec distinguishes in how null/empty is handled for single objects vs. collections, so you must always provide `is_collection: true` when serializing multiple objects. If you attempt to serialize multiple objects without this flag (or a single object with it on) a `JSONAPI::Serializer::AmbiguousCollectionError` will be raised.
146
+
147
+
### Custom attributes
148
+
149
+
By default the serializer looks for the same name of the attribute on the object it is given. You can customize this behavior by providing a block to the attribute:
150
+
151
+
```ruby
152
+
attribute :contentdo
153
+
object.body
154
+
end
155
+
```
156
+
157
+
The block is evaluated within the serializer instance, so it has access to the `object` and `context` instance variables.
158
+
159
+
### More customizations
160
+
161
+
Many other formatting and customizations are possible by overriding any of the following instance methods on your serializers.
162
+
163
+
```ruby
164
+
# Override this to customize the JSON:API "id" for this object.
165
+
# Always return a string from this method to conform with the JSON:API spec.
166
+
defid
167
+
object.id.to_s
168
+
end
169
+
```
170
+
```ruby
171
+
# Override this to customize the JSON:API "type" for this object.
172
+
# By default, the type is the object's class name lowercased, pluralized, and dasherized,
173
+
# per the spec naming recommendations: http://jsonapi.org/recommendations/#naming
174
+
# For example, 'MyApp::LongCommment' will become the 'long-comments' type.
175
+
deftype
176
+
object.class.name.demodulize.tableize.dasherize
177
+
end
178
+
```
179
+
```ruby
180
+
# Override this to customize how attribute names are formatted.
181
+
# By default, attribute names are dasherized per the spec naming recommendations:
182
+
# http://jsonapi.org/recommendations/#naming
183
+
defformat_name(attribute_name)
184
+
attribute_name.to_s.dasherize
185
+
end
186
+
```
187
+
```ruby
188
+
# The opposite of format_name. Override this if you override format_name.
189
+
defunformat_name(attribute_name)
190
+
attribute_name.to_s.underscore
191
+
end
192
+
```
193
+
```ruby
194
+
# Override this to provide resource-object metadata.
You can easily specify relationships with the `has_one` and `has_many` directives.
218
+
219
+
```ruby
220
+
classBaseSerializer
221
+
includeJSONAPI::Serializer
222
+
end
223
+
224
+
classPostSerializer < BaseSerializer
225
+
attribute :title
226
+
attribute :content
227
+
228
+
has_one :author
229
+
has_many :comments
230
+
end
231
+
232
+
classUserSerializer < BaseSerializer
233
+
attribute :name
234
+
end
235
+
236
+
classCommentSerializer < BaseSerializer
237
+
attribute :content
238
+
239
+
has_one :user
240
+
end
241
+
```
242
+
243
+
Note that when serializing a post, the `author` association will come from the `author` attribute on the `Post` instance, no matter what type it is (in this case it is a `User`). This will work just fine, because JSONAPI::Serializers automatically finds serializer classes by appending `Serializer` to the object's class name. This behavior can be customized.
244
+
245
+
Because the full class name is used when discovering serializers, JSONAPI::Serializers works with any custom namespaces you might have, like a Rails Engine or standard Ruby module namespace.
246
+
247
+
### Compound documents and includes
105
248
106
-
### Serialize compound documents
249
+
> To reduce the number of HTTP requests, servers MAY allow responses that include related resources along with the requested primary resources. Such responses are called "compound documents".
"content": "Have no fear, sers, your king is safe."
309
+
},
310
+
"links": {
311
+
"self": "/comments/1",
312
+
"user": {
313
+
"self": "/comments/1/links/user",
314
+
"related": "/comments/1/user",
315
+
"linkage": {
316
+
"type": "users",
317
+
"id": "2"
318
+
}
319
+
}
320
+
}
321
+
},
322
+
{
323
+
"id": "2",
324
+
"type": "users",
325
+
"attributes": {
326
+
"name": "Barristan Selmy"
327
+
},
328
+
"links": {
329
+
"self": "/users/2"
330
+
}
331
+
}
332
+
]
333
+
}
334
+
```
335
+
336
+
Notice a few things:
337
+
* The [primary data](http://jsonapi.org/format/#document-structure-top-level) now includes "linkage" information for each relationship that was included.
338
+
* The related objects themselves are loaded in the top-level `included` member.
339
+
* The related objects _also_ include "linkage" information when a deeper relationship is also present in the compound document. This is a very powerful feature of the JSON:API spec, and allows you to deeply link complicated relationships all in the same document and in a single HTTP response. JSONAPI::Serializers automatically includes the correct linkage information for whatever `include` paths you specify. This conforms to this part of the spec:
340
+
341
+
> Note: Resource linkage in a compound document allows a client to link together all of the included resource objects without having to GET any relationship URLs.
The `include` param also accepts a string of [relationship paths](http://jsonapi.org/format/#fetching-includes), ie. `include: 'author,comments,comments.user'` so you can pass an `?include` query param directly through to the serialize method. Be aware that letting users pass arbitrary relationship paths might introduce security issues depending on your authorization setup, where a user could `include` a relationship they might not be authorized to see directly. Be aware of what you allow API users to include.
> To reduce the number of HTTP requests, servers MAY allow responses that include related resources along with the requested primary resources. Such responses are called "compound documents". [JSON:API Compound Documents](http://jsonapi.org/format/#document-structure-compound-documents)
404
+
## Unfinished business
109
405
110
-
...
406
+
* Support for passing `context` through to serializers is partially complete, but needs more work.
407
+
* Support for a `serializer_class` attribute on objects that overrides serializer discovery, would love a PR contribution for this.
408
+
* Support for the `fields` spec is planned, would love a PR contribution for this.
409
+
* Support for pagination/sorting is unlikely to be supported because it would likely involve coupling to ActiveRecord, but please open an issue if you have ideas of how to support this generically.
0 commit comments