My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
API REST in Symfony 2.0 and more

API REST in Symfony 2.0 and more

Sergio's photo
Sergio
·Nov 23, 2016

I want to share some knowladge about make an api rest project with Symfony.

In my last company we use an API REST to communicate the frontend and the backend, and the first approach was not so well implemented, for this reason i make a github repository with a little implementation of some bundles and a basic configuration to have an API REST in Symfony 2 and future versions.

I will put all the bundles I used and explain a little of everyone to make a resume of my reasons.

FOSOAuthServerBundle

https://github.com/FriendsOfSymfony/FOSOAuthServerBundle

This bundle make it easy the implementation of an Oauth2 authentication system, providing all the classes and infrastructure you need.

You need to add some entities to your project:

  • AccessToken
  • AuthCode
  • Client
  • RefreshToken

And a bit of configuration in config.yml

fos_oauth_server:
    service:
        user_provider: fos_user.user_manager
    db_driver: orm
    client_class: OptcRestApi\Components\OAuth\Entity\Client
    access_token_class: OptcRestApi\Components\OAuth\Entity\AccessToken
    refresh_token_class: OptcRestApi\Components\OAuth\Entity\RefreshToken
    auth_code_class: OptcRestApi\Components\OAuth\Entity\AuthCode

And a bit of the configuration in security.yml

firewalls:
    oauth_token:
        pattern: ^/oauth/v2/token
        security: false
    api:
        pattern: ^/
        fos_oauth: true
        stateless: true
        anonymous: false

The interesting point of this bundle is making the oauth integration so easy, and with the entities I mentioned earlier you can generate, remove and refresh every token you need.

Here you have an example of a console command to generate token, but you can make a screen or whatever you want.

In the repository you have all the information you need for the correct implementation, and in my repo you have all the classes with all the fields needed for the Oauth2 correc authentication.

FOSUserBundle

https://github.com/FriendsOfSymfony/FOSUserBundle

With this bundle we make easier the managment of the User in our App or API, an add some interesting things, and can integrate with the Oauth2 authentication.

The first of all, give you a console command to generate user by the console, and this is so interesting because when you are developing an app and you don't have any graphic interface you can't make it easy the user generation, for example with this line we can generate a new user:

php bin/console fos:user:create testuser test@example.com p@ssword

Maybe this is the most interesting, but you have another commands too

It's interesting to that you can save all the roles in the database and put all you need with zero effort. You can automatize the email sending, to make it easy and decide if you wan to log in by username or email too.

In the official documentation you can find all the options and configurations that offer.

FOSRestBundle

https://github.com/FriendsOfSymfony/FOSRestBundle

This bundle is so useful because make it so much easy all the RESTing integration with your controllers and the responses.

It's interesting to make the things more easy, to install the JSMSerializerBundle, to make super-easy the entities serialization, and make all the controllers send and receive data from json.

For manage all the parameters that recive the controller, you have the QueryParam, RequestParam and FileParam, that make super easy the parsing of the params by POST/GET.

To manage more easy the request and if you want to get entire entities, you have a custom ParamConverter, that works with the previous serializer and make posible to retrieve the entity in the controller without doing anything! You can implement the validation too without doing an extra effort and only putting in the action as argument, and can define the groups you want.

To make the API most versatile and flexible, you can specify the format listener for the routes of your app, and put the priorities, accepted formats, returned formats with no complication, super useful to make it posible for example returning data in XML, JSON or CSV.

Another interesting point is the handleView method that make posible to send all the contend serialized to the response and not is necessary to send a JsonResponse every time, or make a serialization of the data, the bundle handle by itself, you can find in the official documentation.

There is a few things that the bundle can do for you, but can handle exceptions, add differents body listeners, versioning, and other so interesting options.

BazingaHateoasBundle

https://github.com/willdurand/BazingaHateoasBundle

This bundle didn't used in my repository but I think it's interesting to make more easy the navigation between resources. If you don't know what is HATEOAS is basically make every response or resource have their URL, I think it's useful for the pagination or to have the entire url of every item in a list.

NelmioApiDocBundle

https://github.com/nelmio/NelmioApiDocBundle

And the last but not least importat what is an API without documentation? Nothing!

With the nelmio documentation you can make you api full documentat in an easy way. Only add the annotations in the action, and all is auto-generated for you.

Here is an example of the documentation:

title here

You can find all the annotations here, it's pretty easy to understand, and you can put all the information you want.

The nice point it's that every url have a sandbox toy make some testing and view if all is correct, the bundle integrate with the FOSRestBundle with the QueryParam and RequestParam to make more painless the generation.

I hope this can help someone a bit lost in the Symfony REST API ecosystem, and if you have any doubt or question or anything, tell me, I'm glad to help!