Instantiating at new.json


#1

Let’s say I’m a restaurant, and I am setting up a form to create a new menu for the day. I have a Menu which has many MenuItems. My form should automatically populate with one menu item, “Fish of the Day”, whose price field should default to the current market price (coming from the server).

I typically do this by hitting a /menus/new.json endpoint. Questions:

  • Is this recommended? What is the alternative when instantiation data needs to come from the server?
  • How can this work? The relationships and included will not have id populated since these are unpersisted entities.

#2

We don’t have an official way to support templates yet, but would like to in the future.


#3

I’m not really sure I understand what you’re asking. Are you saying your client doesn’t know the structure of a menu resource, and so needs a template? Or just that you always want to check some item’s price before putting it in the new menu?


#4

My scenario is I already know the structure, but filling in the data for an item’s price (the default price that should appear on the form before anything is persisted) comes from the server. So the server needs to respond with an unpersisted resource that has data filled in.

Currently I’m avoiding jsonapi for this, or hitting ‘create’ to get this data, faking the id, then actually persisting in ‘update’.


#5

Ahh, ok, I think I understand now.

So, here’s one option that seems decent, at least until JSON API adds support for write templates:

GET /defaults/menu-items

{
  "data": {
    "type": "defaults",
    // id is name of the collection that
    // these defaults apply to
    "id": "menu-items", 
    "attributes": {
      "price": ""// the default price,
       // ...
    },
    "relationships": {
      // any default relationship values
    }
  }
}

Then, you can add "defaults" resources like this for any other resource types that need them. When a client wants to create a new menu item, it fetches /defaults/menu-items and uses that resource object to pre-populate the form.

(If these resources aren’t editable by clients, you simply don’t have to support any methods for them other than GET.)


#6

@ethanresnick sorry, I only just now saw your latest reply! I think what you’re saying sounds like good API design, now I’ll just have to do the work to get Ember and Rails/AMS to support this.