Talk To Us For FREE

We are in the Business of Support and that starts before you even become a client.

  • Please prove you are human by selecting the Key.

REST APIs with Symfony2: The Right Way

Categories : Article, Symfony

For this tutorial, let’s check how to create user API as an example.

Clients need to know how to talk to your API. In the HTTP protocol, the AcceptHeader will receive the format the clients want to talk to your API. The FOSRestBundle handles all this communication. You only need to configure the formats that you wish to support. JSON can be used for this purpose. XML can be used for semantic problematics.


Get is used to return resources in Symfony 2 – either a collection of resources or a single resource.

pattern: /users
defaults: { _controller: AcmeDemoBundle:User:all, _format: 
requirements:_method: GET
pattern: /users/{id}
defaults: { _controller: AcmeDemoBundle:User:get, _format: 
requirements: _method: GET
id: "\d+"

The following code is used in the UserController Class :


Using fetch the object using get*() method is always beneficial.

Ensure that you enter status codes. If user does not exist, make sure that you use NotFoundHttpException that returns a 404 status code.

View Annotation renders the user object using the right format – in accordance with the Accept Header.

The allAction() method – you can fetch all the users and then return them again.

A user basically has 4 properties:

Id, email, User name and password

The password should never be disclosed. This can be easily configured with a serializer.

# In Propel, the most part of the code is located in base classes# src/Acme/DemoBundle/Resources/config/serializer/
exclusion_policy: ALL
expose: true
expose: true
expose: true

This was using the YAML. 

The following JSON response is given

"id": 999,
"username": "xxxx",
"email": ""

This covered only one portion, for building a USER API. 

[Total: 1    Average: 5/5]

Client Saying

If you're starting a new business or want to upgrade an existing site, I strongly recommend…
Mr. Manjesh Singh
Daniel Coburn, the president of gives the honest opinion regarding his experience working with Brainvire…
Mr. Daniel Coburn
Chad Gundry, the CEO of says that he has worked extensively with Brainvire team since…
Mr. Chad Gundry
The best thing about Brainvire is Compatibility. Whenever we have a query Brainvire is always ready…
Mr Craig Agranoff
Brainvire is a professional company with professional developers who understand the problems that we are facing…
Mr. Clarke Verdel

Latest Happenings

  • 27 Mar 2017
    Brainvire to showcase retail expertise in world’s most anticipated retail event IRCE 2017 [ + ]
  • 17 Mar 2017
    Brainvire - Walmart Collaboration Hits Another Retail Height [ + ]