K
K
Konstantin2015-11-21 08:20:20
symfony
Konstantin, 2015-11-21 08:20:20

How to display only entity_id in JMSSerializer instead of whole entity?

Hello.
There was a task to organize a trivial RESTful API for internal use, I connected FOSRestBundle, but I don’t use it 100% - I only took View from there.
There was a question with data de/serialization: I have entities Group (id, name) and Item with fields (id, name, group).
First I do a POST /groups with a body

{
  "name": "foo"
}

After that GET /groups and get something like
[
  {
    "id": "8215471f-834b-49fa-8a32-ff4a2f849bdf",
    "name": "foo"
  }
]

Everything is ok here. It's time to save the Item: doing a POST /items with the body
{
  "name": "bar",
  "group": "8215471f-834b-49fa-8a32-ff4a2f849bdf"
}

Item is saved, I go to read it GET /items/d3e197d2-6df5-4335-9eb8-d1ee1da83fa3 and get
{
  "name": "bar",
  "group": {
    "id": "8215471f-834b-49fa-8a32-ff4a2f849bdf",
    "name": "foo"
  }
}

Although the client expects to see exactly what he sent + id:
{
  "name": "bar",
  "group": "8215471f-834b-49fa-8a32-ff4a2f849bdf"
}

Question: Am I misunderstanding the REST logic, or have I configured the serializer incorrectly?
I proceed from the logic that the client after GET will want to take the response body, modify one field in it (for example, name) and send it back using PUT, but in this case the request will be invalid.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
B
bears, 2015-11-21
@bears

Everything is right with you, you cannot get it like this in the standard way:
{
"name": "bar",
"group": "8215471f-834b-49fa-8a32-ff4a2f849bdf"
}
since the item group is a link, so you get its id as an array/object.

S
Sergey, 2015-11-21
Protko @Fesor

Or have I misconfigured the serializer?

Exactly. Although I'm not 100% sure that you organized the resource correctly (if you have connections there). In general, the inline option
will help solve your serialization problems . Unfortunately, it does not work in the opposite direction (what to do, jms serializer has not been actively maintained for a couple of years). An alternative - for an object of your type, you can simply declare your handler for serialization / deserialization.

D
Denis, 2015-11-21
@prototype_denis

Both ways can be done like this...

/** @Accessor(getter="getMethod", setter="setMethod") */
    private $group;

jmsyst.com/libs/serializer/master/reference/annota...
Addition to Sergey Protko's answer and inline options

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question