Talk To Us For FREE

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

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 HTTP verb

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

src/Acme/DemoBundle/Resources/config/routing.yml
acme_demo_user_all:
pattern: /users
defaults: { _controller: AcmeDemoBundle:User:all, _format: 
}
requirements:_method: GET
acme_demo_user_get:
pattern: /users/{id}
defaults: { _controller: AcmeDemoBundle:User:get, _format: 
}
requirements: _method: GET
id: "\d+"

The following code is used in the UserController Class :

?php

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/Model.om.BaseUser.yml
Acme\DemoBundle\Model\om\BaseUser:
exclusion_policy: ALL
properties:
id:
expose: true
username:
expose: true
email:
expose: true

This was using the YAML. 

The following JSON response is given

{
"user": 
{
"id": 999,
"username": "xxxx",
"email": "xxxx@example.org"
}
}

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

[Total: 1    Average: 5/5]