
In the previous installment of this series, I helped you upgrade your Symfony 2.x apps to Symfony 3.1.
Symfony is fast becoming the favourite framework among developers for rapid application development. And despite releasing Symfony 3.1 and 3.2 in the previous quarter, they are still introducing many changes and upgrades.
Yes! We know that Symfony is one of the best frameworks to develop REST API, so in this article, we will make simple REST API in Symfony 3.1.. By the end of this article, we will have covered the following topics
- Understanding REST API
- Bundles Required For REST API
- Bundles Registration
- Configuration
- Create User Entity
- GET, POST, PUT, DELETE
We are also going to use postman to test our API, so it is recommended to install postman from chrome extensions. Let’s get started with our REST API in Symfony 3.1.
Understanding REST API
REST is an abbreviation for Representational State Transfer. This is a bridge or medium between data resource and application interface whether it’s on mobile devices or desktops. REST provides a block of HTTP methods which are used to alter the data. The following are common HTTP methods:
- GET – Used for reading and retrieving data
- POST – Used for inserting data.
- PUT – Used for updating data.
- DELETE – Used for deleting data
Basically, REST phenomena works on actions and resources. Whenever any action URL is invoked, it performs an individual method (or a set of methods) on that URL. I will discuss this further with examples. For the purpose of this article, I assume that you’ve already Signup and setup a PHPstack application on Cloudways.
You can use promo code: PHP15 to get FREE Cloudways hosting credit of $15 on signup.
Now to install Symfony on Cloudways server for PHP, you can follow the simple guide on How To Install Symfony 3 On Cloud.
Bundles Required For REST API
For making REST API with Symfony we must need FOSRestBundle but along with it we also need to install 2 more bundles:
- JMSSerializerBundle
- NelmioCorsBundle
FOSRestBundle is the backbone of REST API in Symfony. It accepts the client request and returns the appropriate response accordingly. JMSSerializerBundle helps in serialization of data according to your requested format namely json,xml or yaml. NelmiCorsBundle allows different domains to call our API.
To install these bundles simply run the following commands in SSH terminal:
composer require friendsofsymfony/rest-bundle composer require jms/serializer-bundle composer require nelmio/cors-bundle
Bundles Registration
After successfully installing the bundle, you need to register them in AppKernel.php file located in app folder. Open the file and add these lines in bundles array.
new FOS\RestBundle\FOSRestBundle(), new JMS\SerializerBundle\JMSSerializerBundle(), new Nelmio\CorsBundle\NelmioCorsBundle(),
The registration will enable bundles in symfony project. You can now start working with these but before this we need to do a little configuration.
Configuration in config.yml
As I’ve said before, we need to enable our API to call different domains for outputting headers. This action needs a little configuration in config.yml file. Open it and add the following code in it:
# Nelmio CORS Configuration nelmio_cors: defaults: allow_credentials: false allow_origin: ['*'] allow_headers: ['*'] allow_methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'] max_age: 3600 hosts: [] origin_regex: false # FOSRest Configuration fos_rest: body_listener: true format_listener: rules: - { path: '^/', priorities: ['json'], fallback_format: json, prefer_extension: false } param_fetcher_listener: true view: view_response_listener: 'force' formats: json: true
So we have configured both FOSRestBundle and NelmioCorsBundle. Now we are all set to make our first entity for manipulating data from different calls.
Stop Wasting Time on Servers
Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.
Create a User Entity in Symfony:
We need some data to create, update, and delete. For this, we are going to make an entity User. To simplify things we just add only name and role of user to make different entities. Move to your application folder and run the following command in SSH terminal:
$ php bin/console generate:doctrine:entity
This command will open entity creator and ask for your entity name. You must enter entity with application bundle like AppBundle:User. It will ask about annotation now. Just hit enter and one by one enter your entity fields of name and role. Id is created by default.
After creating the entity we need to update database schema in order to add table in database. Run the following command to update schema:
$ php bin/console doctrine:schema:update --force
Check your database for the new table created.
Now our database is ready. You can insert some data in it by running insert query in your db:
INSERT INTO `user` (`name`, `role`) VALUES ('tony', 'community manager'), ('sandy', 'digital content producer'), ( 'michael', 'php community manager');
Let’s start developing API calls for simple REST API with Symfony.
Getting records from database:
Move to AppBundle/Controller and create UserController.php file and add the following namespace and dependency file URLS at the top
namespace AppBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use FOS\RestBundle\Controller\Annotations as Rest; use FOS\RestBundle\Controller\FOSRestController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use FOS\RestBundle\View\View; use AppBundle\Entity\User;
After this, make first controller class UserController which extend FOSUserBundle. All the methods and request routes will be made in this class.
class UserController extends FOSRestController { }
Make a first Get route and its method to retrieve user data from database. if there is no record exist it will show the response message in view. Copy the code below into the UserController class:
/** * @Rest\Get("/user") */ public function getAction() { $restresult = $this->getDoctrine()->getRepository('AppBundle:User')->findAll(); if ($restresult === null) { return new View("there are no users exist", Response::HTTP_NOT_FOUND); } return $restresult; }
Lets check if the data is retrieved or not in our API call in postman. You need to find your application URL in Application Access page on Cloudways. Copy the URL in postman with /user suffix.
If you want to retrieve only one record then pass the user ID in idAction() and find() method. you can make a new route and method like this:
/** * @Rest\Get("/user/{id}") */ public function idAction($id) { $singleresult = $this->getDoctrine()->getRepository('AppBundle:User')->find($id); if ($singleresult === null) { return new View("user not found", Response::HTTP_NOT_FOUND); } return $singleresult; }
To check API call in postman run this URL:
Posting records in database:
To post new record in database add the following code in UserController class.
/** * @Rest\Post("/user/") */ public function postAction(Request $request) { $data = new User; $name = $request->get('name'); $role = $request->get('role'); if(empty($name) || empty($role)) { return new View("NULL VALUES ARE NOT ALLOWED", Response::HTTP_NOT_ACCEPTABLE); } $data->setName($name); $data->setRole($role); $em = $this->getDoctrine()->getManager(); $em->persist($data); $em->flush(); return new View("User Added Successfully", Response::HTTP_OK); }
Let’s try to add records from postman.
You can check by running the GET call to fetch all users whether the user added or not.
You Might Also Like: Create Token Based API Authentication in Symfony
Updating record in database:
To update record, add PUT call in route and write the code provided below. Basically it will take the ID of the user to retrieve the name and role of user, after which you can edit the fields and update it by PUT header in postman.
/** * @Rest\Put("/user/{id}") */ public function updateAction($id,Request $request) { $data = new User; $name = $request->get('name'); $role = $request->get('role'); $sn = $this->getDoctrine()->getManager(); $user = $this->getDoctrine()->getRepository('AppBundle:User')->find($id); if (empty($user)) { return new View("user not found", Response::HTTP_NOT_FOUND); } elseif(!empty($name) && !empty($role)){ $user->setName($name); $user->setRole($role); $sn->flush(); return new View("User Updated Successfully", Response::HTTP_OK); } elseif(empty($name) && !empty($role)){ $user->setRole($role); $sn->flush(); return new View("role Updated Successfully", Response::HTTP_OK); } elseif(!empty($name) && empty($role)){ $user->setName($name); $sn->flush(); return new View("User Name Updated Successfully", Response::HTTP_OK); } else return new View("User name or role cannot be empty", Response::HTTP_NOT_ACCEPTABLE); }
Now move to postman enter the user id in URL and change the header to PUT. Add the update records in Params and send the request.
Deleting record in database:
To delete records via API call, you need to pass the ID of user in URL. Add the below route and method in class:
/** * @Rest\Delete("/user/{id}") */ public function deleteAction($id) { $data = new User; $sn = $this->getDoctrine()->getManager(); $user = $this->getDoctrine()->getRepository('AppBundle:User')->find($id); if (empty($user)) { return new View("user not found", Response::HTTP_NOT_FOUND); } else { $sn->remove($user); $sn->flush(); } return new View("deleted successfully", Response::HTTP_OK); }
Let’s test the API call in postman.
Conclusion:
So we are done with our startup API and all the calls are running perfectly. Just follow the steps and you will be able to create simple REST API in Symfony 3.1. In the next installment, I will show you how to add reCAPTCHA to your Symfony 3.1 forms. Here is a short introduction and list of major topics in this Symfony 3.1 series.
Customer Review at
“Cloudways hosting has one of the best customer service and hosting speed”
Sanjit C [Website Developer]
Shahroze Nawaz
Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. Besides his work life, he loves movies and travelling.