Kamil P
Kamil P

Reputation: 784

Symfony and Angular application

I have SF2 application and AngularJS client.

When I create some item symfony returns HTTP 201 status, which means item is created.

And... I want to know ID of this item, or better route to this item. So when I create something I want to return HTTP 201 status and also Location: http://my-app.dev/created-item/{id} and Access-Control-Expose-Headers: Location headers.

Of course I can create new response and add this headers. But I have to do this in any createAction in my controllers.

Is there some way to add this headers automatically to any 201 response after success POST request?

Or maybe I'm thinking in wrong way and should do otherwise?

Upvotes: 2

Views: 170

Answers (1)

Genti Saliu
Genti Saliu

Reputation: 2723

This can be done with a REST API with HATEOAS support.

What is HATEOAS?

What basically HATEOAS does, is automatically add URIs to every resource being returned by your API.

An example for an HATEOAS-based response for a call to http://localhost:8080/api/customers would be:

[{
    "name": "Alice",
    "links": [ {
        "rel": "self",
        "href": "http://localhost:8080/api/customers/1"
    } ]
}]

This returns all customers and for every customer the self-linking URI to that customer's resource.

How to use HATEOAS in SF2?

You can integrate it in Symfony2 using a combination of FOSRestBundle, BazingaHateoasBundle and JMSSerializerBundle.

Your relations (links to resources) can be configured in XML, YAML, PHP or Annotations. An example with annotations would be:

use JMS\Serializer\Annotation as Serializer;
use Hateoas\Configuration\Annotation as Hateoas;

/**
 * @Serializer\XmlRoot("customer")
 *
 * @Hateoas\Relation("self", href = "expr('/api/customers/' ~ object.getId())")
 */
class Customer
{
    private $id;
    private $name;

    ...
}

See this presentation for more details.

I've never used this myself, but according to this Google groups post, BazingaHateoasBundle builds on JMSSerializerBundle to generate automatically links and embedded objects for the serialized objects, so you don't need to do anything else.

Conclusion: When you create a new item in a POST request, return the created item. BazingaHateoasBundle will automatically add the URI/route of that item to the response.

Upvotes: 2

Related Questions