A serializer/deserializer for JSON payloads that comply to the JSON API - jsonapi.org v1.1 spec in go.
This package was forked from google/jsonapi and adds several enhancements such as links and polymorphic relationships.
go get -u github.com/hashicorp/jsonapi
Or, see Alternative Installation.
You are working in your Go web application and you have a struct that is
organized similarly to your database schema. You need to send and
receive json payloads that adhere to the JSON API spec. Once you realize that
your json needed to take on this special form, you go down the path of
creating more structs to be able to serialize and deserialize JSON API
payloads. Then there are more models required with this additional
structure. Ugh! With JSON API, you can keep your model structs as is and
use StructTags to indicate
to JSON API how you want your response built or your request
deserialized. What about your relationships? JSON API supports
relationships out of the box and will even put them in your response
into an included side-loaded slice--that contains associated records.
JSON API uses StructField tags to annotate the structs fields that you already have and use in your app and then reads and writes JSON API output based on the instructions you give the library in your JSON API tags. Let's take an example. In your app, you most likely have structs that look similar to these:
type Blog struct {
ID int `json:"id"`
Title string `json:"title"`
Posts []*Post `json:"posts"`
CurrentPost *Post `json:"current_post"`
CurrentPostId int `json:"current_post_id"`
CreatedAt time.Time `json:"created_at"`
ViewCount int `json:"view_count"`
}
type Post struct {
ID int `json:"id"`
BlogID int `json:"blog_id"`
Title string `json:"title"`
Body string `json:"body"`
Comments []*Comment `json:"comments"`
}
type Comment struct {
Id int `json:"id"`
PostID int `json:"post_id"`
Body string `json:"body"`
Likes uint `json:"likes_count,omitempty"`
}These structs may or may not resemble the layout of your database. But these are the ones that you want to use right? You wouldn't want to use structs like those that JSON API sends because it is difficult to get at all of your data easily.
This program demonstrates the implementation of a create, a show, and a list http.Handler. It outputs some example requests and responses as well as serialized examples of the source/target structs to json. That is to say, I show you that the library has successfully taken your JSON API request and turned it into your struct types.
To run,
- Make sure you have Go installed
- Create the following directories or similar:
~/go - Set
GOPATHtoPWDin your shell session,export GOPATH=$PWD go get github.com/hashicorp/jsonapi. (Append-uaftergetif you are updating.)cd $GOPATH/src/github.com/hashicorp/jsonapi/examplesgo build && ./examples
The jsonapi StructTags
tells this library how to marshal and unmarshal your structs into
JSON API payloads and your JSON API payloads to structs, respectively.
Then Use JSON API's Marshal and Unmarshal methods to construct and read
your responses and replies. Here's an example of the structs above
using JSON API tags:
type Blog struct {
ID int `jsonapi:"primary,blogs"`
Title string `jsonapi:"attr,title"`
Posts []*Post `jsonapi:"relation,posts"`
CurrentPost *Post `jsonapi:"relation,current_post"`
CurrentPostID int `jsonapi:"attr,current_post_id"`
CreatedAt time.Time `jsonapi:"attr,created_at"`
ViewCount int `jsonapi:"attr,view_count"`
}
type Post struct {
ID int `jsonapi:"primary,posts"`
BlogID int `jsonapi:"attr,blog_id"`
Title string `jsonapi:"attr,title"`
Body string `jsonapi:"attr,body"`
Comments []*Comment `jsonapi:"relation,comments"`
}
type Comment struct {
ID int `jsonapi:"primary,comments"`
PostID int `jsonapi:"attr,post_id"`
Body string `jsonapi:"attr,body"`
Likes uint `jsonapi:"attr,likes-count,omitempty"`
}`jsonapi:"primary,<type field output>"`
This indicates this is the primary key field for this struct type.
Tag value arguments are comma separated. The first argument must be,
primary, and the second must be the name that should appear in the
type* field for all data objects that represent this type of model.
* According the JSON API spec, the plural record types are shown in the examples, but not required.
`jsonapi:"attr,<key name in attributes hash>,<optional: omitempty>"`
These fields' values will end up in the attributeshash for a record.
The first argument must be, attr, and the second should be the name
for the key to display in the attributes hash for that record. The optional
third argument is omitempty - if it is present the field will not be present
in the "attributes" if the field's value is equivalent to the field types
empty value (ie if the count field is of type int, omitempty will omit the
field when count has a value of 0). Lastly, the spec indicates that
attributes key names should be dasherized for multiple word field names.
`jsonapi:"relation,<key name in relationships hash>,<optional: omitempty>"`
Relations are struct fields that represent a one-to-one or one-to-many
relationship with other structs. JSON API will traverse the graph of
relationships and marshal or unmarshal records. The first argument must
be, relation, and the second should be the name of the relationship,
used as the key in the relationships hash for the record. The optional
third argument is omitempty - if present will prevent non existent to-one and
to-many from being serialized.
`jsonapi:"polyrelation,<key name in relationships hash>,<optional: omitempty>"`
Polymorphic relations can be represented exactly as relations, except that an intermediate type is needed within your model struct that provides a choice for the actual value to be populated within.
Example:
type Video struct {
ID int `jsonapi:"primary,videos"`
SourceURL string `jsonapi:"attr,source-url"`
CaptionsURL string `jsonapi:"attr,captions-url"`
}
type Image struct {
ID int `jsonapi:"primary,images"`
SourceURL string `jsonapi:"attr,src"`
AltText string `jsonapi:"attr,alt"`
}
type OneOfMedia struct {
Video *Video
Image *Image
}
type Post struct {
ID int `jsonapi:"primary,posts"`
Title string `jsonapi:"attr,title"`
Body string `jsonapi:"attr,body"`
Gallery []*OneOfMedia `jsonapi:"polyrelation,gallery"`
Hero *OneOfMedia `jsonapi:"polyrelation,hero"`
}During decoding, the polyrelation annotation instructs jsonapi to assign each relationship
to either Video or Image within the value of the associated field, provided that the
payload contains either a "videos" or "images" type. This field value must be
a pointer to a special choice type struct (also known as a tagged union, or sum type) containing
other pointer fields to jsonapi models. The actual field assignment depends on that type having
a jsonapi "primary" annotation with a type matching the relationship type found in the response.
All other fields will be remain empty. If no matching types are represented by the choice type,
all fields will be empty.
During encoding, the very first non-nil field will be used to populate the payload. Others will be ignored. Therefore, it's critical to set the value of only one field within the choice struct. When accepting input values on this type of choice type, it would a good idea to enforce and check that the value is set on only one field.
`jsonapi:"links,omitempty"`
A field annotated with links will have the links members of the request unmarshaled to it. Note
that this field should always be annotated with omitempty, as marshaling of links members is
instead handled by the Linkable interface (see Links below).
All Marshal and Unmarshal methods expect pointers to struct
instance or slices of the same contained with the interface{}s
Now you have your structs prepared to be serialized or materialized, What about the rest?
You can Unmarshal a JSON API payload using jsonapi.UnmarshalPayload. It reads from an io.Reader containing a JSON API payload for one record (but can have related records). Then, it materializes a struct that you created and passed in (using new or &). Again, the method supports single records only, at the top level, in request payloads at the moment. Bulk creates and updates are not supported yet.
After saving your record, you can use, MarshalOnePayload, to write the JSON API response to an io.Writer.