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 favorite 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 for developing REST API, so in this article, we will make a 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 resources and application interfaces, whether it’s on mobile devices or desktops. REST provides a block of HTTP methods that 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 work 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 signed up and set up 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 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’s request and returns the appropriate response accordingly. JMSSerializerBundle helps in the 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 the 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 the AppKernel.php file located in the app folder. Open the file and add these lines to the bundle array.
new FOS\RestBundle\FOSRestBundle(), new JMS\SerializerBundle\JMSSerializerBundle(), new Nelmio\CorsBundle\NelmioCorsBundle(),
The registration will enable bundles in the 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 the config.yml file. Open it and add the following code to 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 handles 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 the user to make different entities. Move to your application folder and run the following command in the SSH terminal:
$ php bin/console generate:doctrine:entity
This command will open entity creator and ask for your entity name. You must enter an entity with an 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 the database schema in order to add a table to the database. Run the following command to update the 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, 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 the first controller class UserController which extends FOSUserBundle. All the methods and request routes will be made in this class.
class UserController extends FOSRestController { }
Make a first Get a route and its method to retrieve user data from the database. if there is no record exists, 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; }
Let’s check if the data is retrieved or not in our API call in postman. You need to find your application URL on the Application Access page on Cloudways. Copy the URL in postman with the /user suffix.
If you want to retrieve only one record, then pass the user ID in the idAction() and then find the () 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 calls in postman, run this URL:
Posting records in database
To post a new record in the database, add the following code in the 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 has been added or not.
You Might Also Like:Â Create Token-Based API Authentication in Symfony
Updating record in database
To update a record, add a 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 the 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 the URL and change the header to PUT. Add the updated records in Params and send the request.
Deleting record in database
To delete records via an API call, you need to pass the ID of the user in the 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 a 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.
Shahzeb Ahmed
Shahzeb is a Digital Marketer with a Software Engineering background, works as a Community Manager — PHP Community at Cloudways. He is growth ambitious and aims to learn & share information about PHP & Laravel Development through practice and experimentation. He loves to travel and explore new ideas whenever he finds time. Get in touch with him at [email protected]