Read complete story

Creating Rest API in Symfony

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 “http://127.0.0.1:8000/api/create” 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!!

. . .

Comment

Add Your Comment

Be the first to comment.

css.php
Hire Us!
Brief us about your requirements and we'll get back to you.
Woo! Hooy!
We have just recieved your project brief and our expert will contact you shortly.
Send Again
Close