Documentation ¶
Overview ¶
Package jsonapi provides a serializer and deserializer for jsonapi.org spec payloads.
You can keep your model structs as is and use struct field tags to indicate to jsonapi how you want your response built or your request deserialzied. What about my relationships? jsonapi supports relationships out of the box and will even side load them in your response into an "included" array--that contains associated objects.
jsonapi uses StructField tags to annotate the structs fields that you already have and use in your app and then reads and writes jsonapi.org output based on the instructions you give the library in your jsonapi tags.
Example structs using a Blog > Post > Comment structure,
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"` }
jsonapi Tag Reference
Value, primary: "primary,<type field output>"
This indicates that 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.
Value, attr: "attr,<key name in attributes hash>[,<extra arguments>]"
These fields' values should end up in the "attribute" hash for a record. The first argument must be, "attr', and the second should be the name for the key to display in the the "attributes" hash for that record.
The following extra arguments are also supported:
"omitempty": excludes the fields value from the "attribute" hash. "iso8601": uses the ISO8601 timestamp format when serialising or deserialising the time.Time value.
Value, relation: "relation,<key name in relationships hash>"
Relations are struct fields that represent a one-to-one or one-to-many to other structs. jsonapi 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.
Use the methods below to Marshal and Unmarshal jsonapi.org json payloads.
Visit the readme at https://github.com/google/jsonapi
Index ¶
- Constants
- Variables
- func MarshalErrors(w io.Writer, errorObjects []*ErrorObject) error
- func MarshalManyPayload(w io.Writer, models interface{}) error
- func MarshalManyPayloadWithoutIncluded(w io.Writer, models interface{}) error
- func MarshalOnePayload(w io.Writer, model interface{}) error
- func MarshalOnePayloadEmbedded(w io.Writer, model interface{}) error
- func MarshalOnePayloadWithoutIncluded(w io.Writer, model interface{}) error
- func UnmarshalManyPayload(in io.Reader, t reflect.Type) ([]interface{}, error)
- func UnmarshalPayload(in io.Reader, model interface{}) error
- type ErrorObject
- type ErrorsPayload
- type Event
- type Events
- type Link
- type Linkable
- type Links
- type ManyPayload
- type Meta
- type Metable
- type Node
- type OnePayload
- type RelationshipLinkable
- type RelationshipManyNode
- type RelationshipMetable
- type RelationshipOneNode
- type Runtime
- func (r *Runtime) Instrument(key string) *Runtime
- func (r *Runtime) MarshalManyPayload(w io.Writer, models interface{}) error
- func (r *Runtime) MarshalOnePayload(w io.Writer, model interface{}) error
- func (r *Runtime) MarshalOnePayloadEmbedded(w io.Writer, model interface{}) error
- func (r *Runtime) UnmarshalManyPayload(reader io.Reader, kind reflect.Type) (elems []interface{}, err error)
- func (r *Runtime) UnmarshalPayload(reader io.Reader, model interface{}) error
- func (r *Runtime) Value(key string) interface{}
- func (r *Runtime) WithValue(key string, value interface{}) *Runtime
- type SILinkable
- type SIRelationshipLinkable
- type ServerInformation
Constants ¶
const ( // MediaType is the identifier for the JSON API media type // // see http://jsonapi.org/format/#document-structure MediaType = "application/vnd.api+json" // KeyFirstPage is the key to the links object whose value contains a link to // the first page of data KeyFirstPage = "first" // KeyLastPage is the key to the links object whose value contains a link to // the last page of data KeyLastPage = "last" // KeyPreviousPage is the key to the links object whose value contains a link // to the previous page of data KeyPreviousPage = "prev" // KeyNextPage is the key to the links object whose value contains a link to // the next page of data KeyNextPage = "next" // QueryParamPageNumber is a JSON API query parameter used in a page based // pagination strategy in conjunction with QueryParamPageSize QueryParamPageNumber = "page[number]" // QueryParamPageSize is a JSON API query parameter used in a page based // pagination strategy in conjunction with QueryParamPageNumber QueryParamPageSize = "page[size]" // QueryParamPageOffset is a JSON API query parameter used in an offset based // pagination strategy in conjunction with QueryParamPageLimit QueryParamPageOffset = "page[offset]" // QueryParamPageLimit is a JSON API query parameter used in an offset based // pagination strategy in conjunction with QueryParamPageOffset QueryParamPageLimit = "page[limit]" // QueryParamPageCursor is a JSON API query parameter used with a cursor-based // strategy QueryParamPageCursor = "page[cursor]" )
Variables ¶
var ( // ErrInvalidTime is returned when a struct has a time.Time type field, but // the JSON value was not a unix timestamp integer. ErrInvalidTime = errors.New("Only numbers can be parsed as dates, unix timestamps") // ErrInvalidISO8601 is returned when a struct has a time.Time type field and includes // "iso8601" in the tag spec, but the JSON value was not an ISO8601 timestamp string. ErrInvalidISO8601 = errors.New("Only strings can be parsed as dates, ISO8601 timestamps") // ErrUnknownFieldNumberType is returned when the JSON value was a float // (numeric) but the Struct field was a non numeric type (i.e. not int, uint, // float, etc) ErrUnknownFieldNumberType = errors.New("The struct field was not of a known number type") // ErrUnsupportedPtrType is returned when the Struct field was a pointer but // the JSON value was of a different type ErrUnsupportedPtrType = errors.New("Pointer type in struct is not supported") // ErrInvalidType is returned when the given type is incompatible with the expected type. ErrInvalidType = errors.New("Invalid type provided") // I wish we used punctuation. )
var ( // ErrBadJSONAPIStructTag is returned when the Struct field's JSON API // annotation is invalid. ErrBadJSONAPIStructTag = errors.New("Bad jsonapi struct tag format") // ErrBadJSONAPIID is returned when the Struct JSON API annotated "id" field // was not a valid numeric type. ErrBadJSONAPIID = errors.New( "id should be either string, int(8,16,32,64) or uint(8,16,32,64)") // ErrExpectedSlice is returned when a variable or arugment was expected to // be a slice of *Structs; MarshalMany will return this error when its // interface{} argument is invalid. ErrExpectedSlice = errors.New("models should be a slice of struct pointers") )
Functions ¶
func MarshalErrors ¶
func MarshalErrors(w io.Writer, errorObjects []*ErrorObject) error
MarshalErrors writes a JSON API response using the given `[]error`.
For more information on JSON API error payloads, see the spec here: http://jsonapi.org/format/#document-top-level and here: http://jsonapi.org/format/#error-objects.
func MarshalManyPayload ¶
MarshalManyPayload writes a jsonapi response with many records, with related records sideloaded, into "included" array. This method encodes a response for a slice of records, hence data will be an array of records rather than a single record. To serialize a single record, see MarshalOnePayload
For example you could pass it, w, your http.ResponseWriter, and, models, a slice of Blog struct instance pointers as interface{}'s to write to the response,
func ListBlogs(w http.ResponseWriter, r *http.Request) { // ... fetch your blogs and filter, offset, limit, etc ... blogs := testBlogsForList() w.Header().Set("Content-Type", jsonapi.MediaType) w.WriteHeader(http.StatusOK) if err := jsonapi.MarshalManyPayload(w, blogs); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } }
Visit https://github.com/google/jsonapi#list for more info.
models interface{} should be a slice of struct pointers.
func MarshalManyPayloadWithoutIncluded ¶
MarshalManyPayloadWithoutIncluded writes a jsonapi response with many records, without the related records sideloaded into "included" array. If you want to serialize the relations into the "included" array see MarshalManyPayload.
models interface{} should be a slice of struct pointers.
func MarshalOnePayload ¶
MarshalOnePayload writes a jsonapi response with one, with related records sideloaded, into "included" array. This method encodes a response for a single record only. Hence, data will be a single record rather than an array of records. If you want to serialize many records, see, MarshalManyPayload.
See UnmarshalPayload for usage example.
model interface{} should be a pointer to a struct.
func MarshalOnePayloadEmbedded ¶
MarshalOnePayloadEmbedded - This method not meant to for use in implementation code, although feel free. The purpose of this method is for use in tests. In most cases, your request payloads for create will be embedded rather than sideloaded for related records. This method will serialize a single struct pointer into an embedded json response. In other words, there will be no, "included", array in the json all relationships will be serailized inline in the data.
However, in tests, you may want to construct payloads to post to create methods that are embedded to most closely resemble the payloads that will be produced by the client. This is what this method is intended for.
model interface{} should be a pointer to a struct.
func MarshalOnePayloadWithoutIncluded ¶
MarshalOnePayloadWithoutIncluded writes a jsonapi response with one object, without the related records sideloaded into "included" array. If you want to serialize the relations into the "included" array see MarshalOnePayload.
model interface{} should be a pointer to a struct.
func UnmarshalManyPayload ¶
UnmarshalManyPayload converts an io into a set of struct instances using jsonapi tags on the type's struct fields.
func UnmarshalPayload ¶
UnmarshalPayload converts an io into a struct instance using jsonapi tags on struct fields. This method supports single request payloads only, at the moment. Bulk creates and updates are not supported yet.
Will Unmarshal embedded and sideloaded payloads. The latter is only possible if the object graph is complete. That is, in the "relationships" data there are type and id, keys that correspond to records in the "included" array.
For example you could pass it, in, req.Body and, model, a BlogPost struct instance to populate in an http handler,
func CreateBlog(w http.ResponseWriter, r *http.Request) { blog := new(Blog) if err := jsonapi.UnmarshalPayload(r.Body, blog); err != nil { http.Error(w, err.Error(), 500) return } // ...do stuff with your blog... w.Header().Set("Content-Type", jsonapi.MediaType) w.WriteHeader(201) if err := jsonapi.MarshalOnePayload(w, blog); err != nil { http.Error(w, err.Error(), 500) } }
Visit https://github.com/google/jsonapi#create for more info.
model interface{} should be a pointer to a struct.
Types ¶
type ErrorObject ¶
type ErrorObject struct { // ID is a unique identifier for this particular occurrence of a problem. ID string `json:"id,omitempty"` // Title is a short, human-readable summary of the problem that SHOULD NOT change from occurrence to occurrence of the problem, except for purposes of localization. Title string `json:"title,omitempty"` // Detail is a human-readable explanation specific to this occurrence of the problem. Like title, this field’s value can be localized. Detail string `json:"detail,omitempty"` // Status is the HTTP status code applicable to this problem, expressed as a string value. Status string `json:"status,omitempty"` // Code is an application-specific error code, expressed as a string value. Code string `json:"code,omitempty"` // Meta is an object containing non-standard meta-information about the error. Meta *map[string]interface{} `json:"meta,omitempty"` }
ErrorObject is an `Error` implementation as well as an implementation of the JSON API error object.
The main idea behind this struct is that you can use it directly in your code as an error type and pass it directly to `MarshalErrors` to get a valid JSON API errors payload. For more information on Golang errors, see: https://golang.org/pkg/errors/ For more information on the JSON API spec's error objects, see: http://jsonapi.org/format/#error-objects
func (*ErrorObject) Error ¶
func (e *ErrorObject) Error() string
Error implements the `Error` interface.
type ErrorsPayload ¶
type ErrorsPayload struct {
Errors []*ErrorObject `json:"errors"`
}
ErrorsPayload is a serializer struct for representing a valid JSON API errors payload.
type Linkable ¶
type Linkable interface {
JSONAPILinks() *Links
}
Linkable is used to include document links in response data e.g. {"self": "http://example.com/posts/1"}
type Links ¶
type Links map[string]interface{}
Links is used to represent a `links` object. http://jsonapi.org/format/#document-links
type ManyPayload ¶
type ManyPayload struct { Data []*Node `json:"data"` Included []*Node `json:"included,omitempty"` Links *Links `json:"links,omitempty"` Meta *Meta `json:"meta,omitempty"` }
ManyPayload is used to represent a generic JSON API payload where many resources (Nodes) were included in an [] in the "data" key
func MarshalMany ¶
func MarshalMany(models []interface{}) (*ManyPayload, error)
MarshalMany does the same as MarshalManyPayload except it just returns the payload and doesn't write out results. Useful is you use your JSON rendering library.
func MarshalManyWithSI ¶
func MarshalManyWithSI(models []interface{}, si ServerInformation) (*ManyPayload, error)
type Meta ¶
type Meta map[string]interface{}
Meta is used to represent a `meta` object. http://jsonapi.org/format/#document-meta
type Metable ¶
type Metable interface {
JSONAPIMeta() *Meta
}
Metable is used to include document meta in response data e.g. {"foo": "bar"}
type Node ¶
type Node struct { Type string `json:"type"` ID string `json:"id"` ClientID string `json:"client-id,omitempty"` Attributes map[string]interface{} `json:"attributes,omitempty"` Relationships map[string]interface{} `json:"relationships,omitempty"` Links *Links `json:"links,omitempty"` Meta *Meta `json:"meta,omitempty"` }
Node is used to represent a generic JSON API Resource
type OnePayload ¶
type OnePayload struct { Data *Node `json:"data"` Included []*Node `json:"included,omitempty"` Links *Links `json:"links,omitempty"` Meta *Meta `json:"meta,omitempty"` }
OnePayload is used to represent a generic JSON API payload where a single resource (Node) was included as an {} in the "data" key
func MarshalOne ¶
func MarshalOne(model interface{}) (*OnePayload, error)
MarshalOne does the same as MarshalOnePayload except it just returns the payload and doesn't write out results. Useful is you use your JSON rendering library.
func MarshalOneWithSI ¶
func MarshalOneWithSI(model interface{}, si ServerInformation) (*OnePayload, error)
type RelationshipLinkable ¶
type RelationshipLinkable interface { // JSONAPIRelationshipLinks will be invoked for each relationship with the corresponding relation name (e.g. `comments`) JSONAPIRelationshipLinks(relation string) *Links }
RelationshipLinkable is used to include relationship links in response data e.g. {"related": "http://example.com/posts/1/comments"}
type RelationshipManyNode ¶
type RelationshipManyNode struct { Data []*Node `json:"data"` Links *Links `json:"links,omitempty"` Meta *Meta `json:"meta,omitempty"` }
RelationshipManyNode is used to represent a generic has many JSON API relation
type RelationshipMetable ¶
type RelationshipMetable interface { // JSONRelationshipMeta will be invoked for each relationship with the corresponding relation name (e.g. `comments`) JSONAPIRelationshipMeta(relation string) *Meta }
RelationshipMetable is used to include relationship meta in response data
type RelationshipOneNode ¶
type RelationshipOneNode struct { Data *Node `json:"data"` Links *Links `json:"links,omitempty"` Meta *Meta `json:"meta,omitempty"` }
RelationshipOneNode is used to represent a generic has one JSON API relation
type Runtime ¶
type Runtime struct {
// contains filtered or unexported fields
}
func NewRuntime ¶
func NewRuntime() *Runtime
func (*Runtime) Instrument ¶
func (*Runtime) MarshalManyPayload ¶
func (*Runtime) MarshalOnePayload ¶
func (*Runtime) MarshalOnePayloadEmbedded ¶
func (*Runtime) UnmarshalManyPayload ¶
func (*Runtime) UnmarshalPayload ¶
type SILinkable ¶
type SILinkable interface {
LinksWithSI(ServerInformation) *Links
}
LinksWithSI provides server information to implementer for constructing the self link object. Return nil pointer mean no link object will be contructed. This is lower priority than Linkable and only active if marshal with server information.
type SIRelationshipLinkable ¶
type SIRelationshipLinkable interface {
RelationshipLinksWithSI(string, ServerInformation) *Links
}
RelationshipLinksWithSI provides server information to implementer for constructing the relationships link object. Return nil pointer mean no link object will be contructed. This is lower priority than RelationshipLinkable and only active if marshal with server information.