Insights

REST APIs with Symfony2: The Right Way

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": "[email protected]"
}
}

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

Banner
In search for strategic sessions?
Let us understand your business thoroughly and help you strategies your digital product..
Book a session