Skip to content

Representation Definition

Andreas Fast edited this page May 22, 2014 · 2 revisions

What are representations for?

To handle abstract data types. When defining a new operation in the operations.yml of a resource you need to specify each field and it's type.

By default Angus uses JSON in the body of the requests and it will convert objects returned by a resource action to the corresponding representation.

There are 4 types you can use:

  • string
  • integer
  • array
  • custom object

How do I define a representation?

It's really easy, here are two examples:

comment:
  - field: id
    description: Comment id.
    type: integer
    required: true
  - field: content
    description: The comment.
    type: string
    required: true

post:
  - field: id
    description: Post id.
    type: integer
    required: true
  - field: content
    description: The blog posts content.
    type: string
    required: true
  - field: tags
    description: Post tags.
    elements_type: string
    required: false
  - field: comments
    description: Comments added to the post.
    elements_type: comment
    required: false

Now let's unpack what is happening here with an example. If a show action inside angus would return a post, it would try to convert the object to this structure, returning something like this:

{
  "id": 1,
  "content": "This is my first blog post",
  "tags": ["first", "post", "angus"],
  "comments": [{"id": 1, "content": "testing"}]
}

What's in a field

For each field we indicate it's name, a description, it's type and whether it's required or not. The use of integer and string is natural and needs no further explanation.

Handling arrays

To declare an array though, we need to say two things, namely that it's an array and also the type of the contents of the array. That's where elements_type comes in. It completely replaces type, this tells angus we are dealing with an array here. And the type indicated for elements_type will be the type for each element of the array.

Custom Types

Each representation can be used as a custom type. You can see that we simply indicated that the comments field of post is an array of comment. Angus will serialize the associated comments to post into that array.

Required

When a field is marked as required and the object does not respond to the value it will raise and error. Make sure to use this feature wisely. Marking everything as required or everything as not required is bad practice.