Building a RESTFull API with Symfony 2, Part 1

June 18, 2021

In this series of blog posts we will be following the steps to build a simple To-do App, using AngularJS and Symfony 2.In this first two parts we will be building a REST API with Symfony 2.

For this tutorial we will assume you are running a *Nix environment (Mac OS X, Linux), and have at least PHP, Composser and MySQL installed. And you have a good understanding of PHP.

Setting up our project

As you can imagine our very first task is to install our dev environment, and for this we will install symfony using its command line installer. For this we will have to download the installer to our machine, if you already have the command line installer you can skip the next step:

$ sudo curl -LsS http://symfony.com/installer -o /usr/local/bin/symfony
$ sudo chmod a+x /usr/local/bin/symfony

After we have the installer in our machine, you will need to navigate to the folder containing your REST API code, for this tutorial I’ll be working with two folders, so I’ll have the following layout:

  • ToDoExample/
    • backend/
    • frontend/

So in this case I’ll have to navigate to the ToDoExample folder and run the next command:

$ symfony new backend

This will create the folder backend, and copy the required symfony files. We will have a basic installation of Symfony already ready to develop, if you are running PHP5.4+ you could easily test our symfony installation by running in the console:

$ cd backend
$ php app/console server:run

If you navigate to the url provided in the output of that command (http://127.0.0.1:8000) you will be getting a 404 error from the Symfony Framework, this is not bad, this means you are already seeing the output of your basic symfony installation.

Now we need to install the Bundles we will be using to build our REST API: FosRestBundle, JMSSerializerBundle, NelmioCorsBundle, to accomplish this task you will need to run the following commands in your console:

$ composer require friendsofsymfony/rest-bundle
$ composer require jms/serializer-bundle
$ composer require nelmio/cors-bundle

After this is done, now we have to tell symfony to load our newly installed bundles, this is done by registering them in our kernel, now go to app/AppKernel.php and in the bundles array, add our bundles:

public function registerBundles()
{
    $bundles = array(
        …
        new FOS\RestBundle\FOSRestBundle(),
        new JMS\SerializerBundle\JMSSerializerBundle(),
        new Nelmio\CorsBundle\NelmioCorsBundle(),
        ...
    );
    ...
}

Now we have to configure our bundles, the first bundle we will need to configure is NelmioCorsbundle, in your app/config.yml copy the following lines at the end:

nelmio_cors:
    defaults:
        allow_credentials: false
        allow_origin: ['*']
        allow_headers: ['X-Custom-Auth']
        allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
        max_age: 3600
        hosts: []
        origin_regex: false

Now we will have to configure the FosRestbundle, in the same file (app/config.yml) write down this lines:

fos_rest:
    param_fetcher_listener: true
    body_listener: true
    format_listener: true
    view:
        view_response_listener: 'force'
        formats:
            xml: true
            json : true
        templating_formats:
            html: true
        force_redirects:
            html: true
        failed_validation: HTTP_BAD_REQUEST
        default_engine: twig
    routing_loader:
        default_format: json

For th JMSSerializerBundle the configurations will be created when we create our model in the next part of our tutorial. The next step is to create our REST bundle, we will use a command line tool in the symfony console, open your terminal and type:

$ php app/console generate:bundle

And follow the wizard, you can use the following values to setup your bundle:

  • Bundle name space: Rootstack/TaskBundle
  • Confirm the name, just press enter
  • Confirm the folder, just press enter
  • We will use annotations for our controller, so write down annotation
  • We will just confirm the following four questions, so hit enter on each one.
Where are we now?

Now we have our basic bundle, but we are still far away from having a functional REST API, now let me explain a bit what of each of these bundles that we installed will do for us:

FosRestBundle

Is the base for our REST API, it will handle the repetitive processes in every REST Call, that are verify the request, and that the endpoint support the correct verb, call our action, and serialize our data into the desired format, it handles various serialization methods but the main two are json and XML.

JMSSerializerBundle

This is the bundle that handles the actual serialization of our objects, arrays and values. What it comes to solve is the problem of having to speak the correct “language” of our visitor, we will respond in our “language” and this bundle will translate to the requested “language” of the user.

NelmioCorsBundle:

If you have done some ajax on the web, you know that you can not make a call from one domain to another, the same principle applies for REST API’s calls in AngularJS, so CORS are some headers that our server will output in order to allow a different domain to call our API.

What’s next?

In the next tutorial we will be creating our model and implementing a CRUD with REST, in order to consume it with an AngularJS front end. In the meantime, you can continue practicing your Symfony skills, while we post part 2 of this multi part story.

Yes, I liked thiscontent.