Creating Rest API in Symfony

Updated 1 December 2018


Today we are going to create a Post API in symfony. Here I assume that you have a active symfony project thats already connected to database if you don’t have a project create one and connect it to a database by either creating a new one or connecting your project to existing database. So lets start with our project.

Firstly create a new controller in your bundle as I did with the name NewController.php and create a fuction in it with any name but having suffix as ‘Action’ as

As you have seen we decided the route (or you can say URL) over here only using annotations. Also we have mentioned the method as POST that meams the method will be called when the given route is called with the ‘POST’ method. We can check the response but in order to do that we have to start our server. So we are starting our server with the following comand

Now as our server is started just hit the “” but you cant just hit the request in your server. You can use various addons for REST, there are many available just search for them on Google.

Thats our API ready but lets now create a roe in our database using it. Here we have a entity User already in my database with five fields

  1. User_ID : Generated By default for each new entry.
  2. Name: Name of the user to be passed.
  3. Email: Email field by user.
  4. Age: Age of user.
  5. Contact: Contains Phone number of user.

So you have to send these in your request as POST body. So we will catch all these values from request in our createuserAction() as

So we have all the data we need to create a user so we are going to create a new User object and the will flush (commit) the object in our database and change the response as ‘USER IS CREATED’

And here you go run that API and get your reponse. You can also check in your database the value will be added. So thats it!! Happy Coding!!

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*

Be the first to comment.

Start a Project

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home