Symfony RESTful API example

Share

In this post we are going to create RESTfull APIs using PHP framework Symfony 3. This will be exemplified on a “Car” entity.

1. Creating Symfony Application

First make sure you have composer globally installed and then run the next command that will install the latest version of Symfony:

composer create-project symfony/framework-standard-edition my_project

2. Bundles configuration

To implement the web services you will need the following 3 bundles: JMSSerializerBundle, FOSRestBundle, NelmioApiDocBundle. Run the commands from below:

composer require jms/serializer-bundle
composer require friendsofsymfony/rest-bundle
composer require nelmio/api-doc-bundle

After installing them using composer, the 3 bundles must be included in AppKernel.php.

The next thing to do is register the route for the NelmioBundle in app/config/routing.yml.

Now the bundles configurations must be enabled in app/config/config.yml.

This configuration is for minimal usage. For more options,please visit the following websites: FOSRestBundle and NelmioApiDocBundle

3. Creating new bundle (CarBundle)

To create a bundle run the next command and follow the installation steps:

php app/console generate:bundle.

As we said this tutorial is based on a “Car” entity. So we need a class “Car” in Entity folder.

As you can see, Doctrine is used to map the Entitiy to the car table.
The next step is to create a controller (CarController) and register the route in Resources/config/routing.yml.

“getCarsAction()” method returns all records coresponding to Car entity. The web service that callls the method has the route “/cars”.

Resources/config/routing.yml

Finally you can see the result in the following image where the webservice is tested and returns a JSON response:

b4e37cd81662ac65b70ad2a61b785bf39e4438c3c04e9a2a67pimgpsh_fullsize_distr

We hope this helps you. Good luck.

By continuing to use the site, you agree to the use of cookies. More information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close