Aerendir
Aerendir

Reputation: 6379

How to manually serialize a resource to Json in Api-Platform?

I have a custom operation that, once called, performs some more tasks than simply adding an entity.

The result of these operations is the creation of a new entity that is then persisted in the database.

Now, as a return value I'm currently using the IRI of the just created entity.

I generate the IRI using \ApiPlatform\Core\Api\IriConverterInterface.

This approach works but has a drawback: in the frontend I have to issue a new call to retrieve the data of the just created entity.

To avoid this call, I'd like to simply return the entity in the JSON format, but I don't find a way to immediately serialize it to return it.

In practice: I currently return simply the IRI of the entity: how can I return the fully serialized entity, according to its serialization configuration?

Upvotes: 4

Views: 2168

Answers (3)

yivi
yivi

Reputation: 47298

If your custom operation controller returns an instance (or a collection of instances) of an Api-Platform managed entity instead of a Response, the object will be automatically serialized with your desired serializer configuration (using the same serialization groups you've already defined, etc).

If you return instead an instance of Response, the SerializeListener will not serialize it and just return it unchanged. If not, it will serialize it. You can see it working here.

Upvotes: 2

Juergen
Juergen

Reputation: 68

I am not sure, if you are just asking for the php-internal json-serialization:

https://www.php.net/manual/de/function.json-encode.php

Which can be included in any Model-class by just implementing the JsonSerializable Interface. Just return an alternative structure, which will be serialized.

https://www.php.net/manual/de/class.jsonserializable.php

Upvotes: 2

WinterSilence
WinterSilence

Reputation: 409

You can use spl_object_hash() or spl_object_id(), see SplObjectStorage::getHash()

Upvotes: -1

Related Questions