Skip to content

Commit 05c403b

Browse files
committed
Merge branch 'master' of github.com:fotinakis/jsonapi-serializers
2 parents eeb1795 + 97fbb56 commit 05c403b

File tree

1 file changed

+314
-15
lines changed

1 file changed

+314
-15
lines changed

README.md

Lines changed: 314 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,33 @@
22

33
JSONAPI::Serializers is a simple library for serializing Ruby objects and their relationships into the [JSON:API format](http://jsonapi.org/format/).
44

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)
18+
* [Relationship path handling](#relationship-path-handling)
19+
* [Rails example](#rails-example)
20+
* [Unfinished business](#unfinished-business)
21+
* [Contributing](#contributing)
622

723
## Features
824

925
* Works with **any Ruby web framework**, including Rails, Sinatra, etc. This is a pure Ruby library.
1026
* 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.
1228
* 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.
1630

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.
1832

1933
## Installation
2034

@@ -37,7 +51,7 @@ class PostSerializer
3751
include JSONAPI::Serializer
3852

3953
attribute :title
40-
attribute :body
54+
attribute :content
4155
end
4256
```
4357

@@ -55,7 +69,7 @@ Returns a hash:
5569
"type": "posts",
5670
"attributes": {
5771
"title": "Hello World",
58-
"body": "Your first post"
72+
"content": "Your first post"
5973
},
6074
"links": {
6175
"self": "/posts/1"
@@ -64,7 +78,7 @@ Returns a hash:
6478
}
6579
```
6680

67-
### Serialize multiple objects
81+
### Serialize a collection
6882

6983
```ruby
7084
JSONAPI::Serializer.serialize(posts, is_collection: true)
@@ -80,7 +94,7 @@ Returns:
8094
"type": "posts",
8195
"attributes": {
8296
"title": "Hello World",
83-
"body": "Your first post"
97+
"content": "Your first post"
8498
},
8599
"links": {
86100
"self": "/posts/1"
@@ -91,7 +105,7 @@ Returns:
91105
"type": "posts",
92106
"attributes": {
93107
"title": "Hello World again",
94-
"body": "Your second post"
108+
"content": "Your second post"
95109
},
96110
"links": {
97111
"self": "/posts/2"
@@ -101,13 +115,298 @@ Returns:
101115
}
102116
```
103117

104-
> 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).
119+
120+
### Null handling
121+
122+
```ruby
123+
JSONAPI::Serializer.serialize(nil)
124+
```
125+
126+
Returns:
127+
```json
128+
{
129+
"data": null
130+
}
131+
```
132+
133+
And serializing an empty collection:
134+
```ruby
135+
JSONAPI::Serializer.serialize([], is_collection: true)
136+
```
137+
138+
Returns:
139+
```json
140+
{
141+
"data": []
142+
}
143+
```
144+
145+
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 :content do
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+
def id
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+
def type
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+
def format_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+
def unformat_name(attribute_name)
190+
attribute_name.to_s.underscore
191+
end
192+
```
193+
```ruby
194+
# Override this to provide resource-object metadata.
195+
# http://jsonapi.org/format/#document-structure-resource-objects
196+
def meta
197+
end
198+
```
199+
```ruby
200+
def self_link
201+
"/#{type}/#{id}"
202+
end
203+
```
204+
```ruby
205+
def relationship_self_link(attribute_name)
206+
"#{self_link}/links/#{format_name(attribute_name)}"
207+
end
208+
```
209+
```ruby
210+
def relationship_related_link(attribute_name)
211+
"#{self_link}/#{format_name(attribute_name)}"
212+
end
213+
```
214+
215+
## Relationships
216+
217+
You can easily specify relationships with the `has_one` and `has_many` directives.
218+
219+
```ruby
220+
class BaseSerializer
221+
include JSONAPI::Serializer
222+
end
223+
224+
class PostSerializer < BaseSerializer
225+
attribute :title
226+
attribute :content
227+
228+
has_one :author
229+
has_many :comments
230+
end
231+
232+
class UserSerializer < BaseSerializer
233+
attribute :name
234+
end
235+
236+
class CommentSerializer < 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
105248

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".
250+
> [JSON:API Compound Documents](http://jsonapi.org/format/#document-structure-compound-documents)
251+
252+
JSONAPI::Serializers supports compound documents with a simple `include` parameter.
253+
254+
For example:
255+
256+
```ruby
257+
JSONAPI::Serializer.serialize(post, include: ['author', 'comments', 'comments.user'])
258+
```
259+
260+
Returns:
261+
262+
```json
263+
264+
"data": {
265+
"id": "1",
266+
"type": "posts",
267+
"attributes": {
268+
"title": "Hello World",
269+
"content": "Your first post"
270+
},
271+
"links": {
272+
"self": "/posts/1",
273+
"author": {
274+
"self": "/posts/1/links/author",
275+
"related": "/posts/1/author",
276+
"linkage": {
277+
"type": "users",
278+
"id": "1"
279+
}
280+
},
281+
"comments": {
282+
"self": "/posts/1/links/comments",
283+
"related": "/posts/1/comments",
284+
"linkage": [
285+
{
286+
"type": "comments",
287+
"id": "1"
288+
}
289+
]
290+
}
291+
}
292+
},
293+
"included": [
294+
{
295+
"id": "1",
296+
"type": "users",
297+
"attributes": {
298+
"name": "Post Author"
299+
},
300+
"links": {
301+
"self": "/users/1"
302+
}
303+
},
304+
{
305+
"id": "1",
306+
"type": "comments",
307+
"attributes": {
308+
"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.
342+
> [JSON:API Resource Relationships](http://jsonapi.org/format/#document-structure-resource-relationships)
343+
344+
#### Relationship path handling
345+
346+
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.
347+
348+
## Rails example
349+
350+
```ruby
351+
# app/serializers/base_serializer.rb
352+
class BaseSerializer
353+
include JSONAPI::Serializer
354+
355+
def self_link
356+
"/api/v1#{super}"
357+
end
358+
end
359+
360+
# app/serializers/post_serializer.rb
361+
class PostSerializer < BaseSerializer
362+
attribute :title
363+
attribute :content
364+
end
365+
366+
# app/controllers/api/v1/base_controller.rb
367+
class Api::V1::BaseController < ActionController::Base
368+
# Convenience methods for serializing models:
369+
def serialize_model(model, options = {})
370+
options[:is_collection] = false
371+
JSONAPI::Serializer.serialize(model, options)
372+
end
373+
374+
def serialize_models(models, options = {})
375+
options[:is_collection] = true
376+
JSONAPI::Serializer.serialize(models, options)
377+
end
378+
end
379+
380+
# app/controllers/api/v1/posts_controller.rb
381+
class Api::V1::ReposController < Api::V1::BaseController
382+
def index
383+
posts = Post.all
384+
render json: serialize_models(posts)
385+
end
386+
387+
def show
388+
post = Post.find(params[:id])
389+
render json: serialize_model(post)
390+
end
391+
end
392+
393+
# lib/jsonapi_mimetypes.rb
394+
# Without this mimetype registration, controllers will not automatically parse JSON API params.
395+
module JSONAPI
396+
MIMETYPE = "application/vnd.api+json"
397+
end
398+
Mime::Type.register(JSONAPI::MIMETYPE, :api_json)
399+
ActionDispatch::ParamsParser::DEFAULT_PARSERS[Mime::Type.lookup(JSONAPI::MIMETYPE)] = lambda do |body|
400+
JSON.parse(body)
401+
end
402+
```
107403

108-
> 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
109405

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.
111410

112411
## Contributing
113412

0 commit comments

Comments
 (0)