How to Create Simple REST API in Symfony 3.1

by Shahroze Nawaz  August 26, 2016

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.

how to make simple rest api in symfony 3.1

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 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:

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.

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:

So we have configured both FOSRestBundle and NelmioCorsBundle. Now we are all set to make our first entity for manipulating data from different calls.

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:

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.  

image01

After creating the entity we need to update database schema in order to add table in database. Run the following command to update schema:

Check your database for the new table created.

database

Now our database is ready. You can insert some data in it by running insert query in your db:

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

After this, make first controller class UserController which extend FOSUserBundle. All the methods and request routes will be made in this class.

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:

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.

get all records

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:

To check API call in postman run this URL:

get single record

Posting records in database:

To post new record in database add the following code in UserController class.

Let’s try to add records from postman.

post records

You can check by running the GET call to fetch all users whether the user added or not.

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.

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.

update record

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:

Let’s test the API call in postman.

delete single record

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.

Start Creating Web Apps on Managed Cloud Servers Now!

Easy Web App Deployment for Agencies, Developers and E-Commerce Industry

About Shahroze Nawaz

Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. He’s always in search of new frameworks and methods to implement them. Besides his coding life, he loves movies and playing soccer with friends. You can email him at shahroze.nawaz@cloudways.com

Stay Connected:

You Might Also Like...

  • Dan Costinel

    Nice. Thank you!

  • Ivan Nikulin

    This is a great example of a really bad code. The worst part is that code is actually works.

    Just from the top of my mind:
    – a fat controller. Just create a service for managing your entities and inject it into cotroller
    – mixed output. One action returns a json, the next action returns a string.
    – using annotation for routing. It is much better and cleaner to define them in a routing.yml

    • Shahroze Nawaz

      @disqus_XV8bQrNUZK:disqus have you tried it? string response just show the success message on view. for routing, since it is a simple and kick start API that’s why I have defined it here indeed not a bad idea. in routing.yaml you can define route as

      app_user_all:
      pattern: /user
      defaults: { _controller: AppBundle:User:all, _format: ~ }
      requirements:
      _method: GET

      json format is enabled in config.

      • Mathieu Dorméval

        @Shahroze Nawaz I’m not agree with him for the first point : I think you do that in controller only for the example !
        Second point : It will be more useful to use a dedicated view in your Bundle Resource
        Third point : Using Annotations in this case isn’t a bad idea because that one extends FosRestBundle Annotations…

        My point of view : Don’t use if / else / elseif statement blocks when you do a return in your functions, the if statement is sufficient for most cases !

        I have send a similar “kick start” in start overflow documentation, see them an tell me what is your idea : https://t.co/X5drBmK7aB

        Great “kick start” post, in my sense !!!

  • Hassan

    Great tutorial , thanks .

  • Andjii

    if ($singleresult === null) {
    return new View(“user not found”, Response::HTTP_NOT_FOUND);
    }
    crashes with following error: “Catchable Fatal Error: Argument 1 passed to SensioBundleFrameworkExtraBundleConfigurationConfigurationAnnotation::__construct() must be of the type array, string given.”

    How to fix it properly?