How To Create Api in Symfony 4 using JSON data ?
Here, I will show you how to create Api in symfony for beginners.
Step 1:
Navigate to project directory & run below command for create fresh project.
composer create-project symfony/skeleton [project-name]
Step 2:
Now Navigate to project path & Create controller via below command.
php bin/console make:controller
Step 3:
Open that controller, now we need to create three methods for api, first of all we look into listing method which make the list of given JSON array [ index()
]
/**
* @Route("/api/user", name="api_user")
*/
public function index(Request $request)
{
//initilize array
$data = array();
$userArr = array();
// make api request
$request_user_url = '../users.json';
$request_user_result = file_get_contents( $request_user_url );
$user_details = json_decode( $request_user_result, true );
foreach ($user_details as $user)
{
$userArr['id'] = $user['id'];
$userArr['name'] = $user['name'];
$userArr['date'] = $user['date'];
$userArr['address'] = $user['address'];
$userArr['last_modified'] = $user['last_modified'];
array_push($data, $userArr);
}
return new JsonResponse(array('data' => $data, 'count' => count($data)));
}
Step 4:
Second method for update the JSON data [ update()
]
/** * @Route("/api/user-update/{id}/{name}/{date}/{address}", name="api_user_update") */
public function update( Request $request, $name = null, $date = null, $address = null ) {
$status = 'error';
$message = 'User not found!';
$id = $request->get('id');
$name = $request->get('name');
$date = $request->get('date');
$address = $request->get('address');
// make api request
$request_user_url = '../users.json';
$request_user_result = file_get_contents( $request_user_url );
$user_details = json_decode( $request_user_result, true );
foreach ( $user_details as $key => $value ) {
if( $value['id'] == $id ) {
if( $name != null ) {
$user_details[$key]['name'] = $name;
}
if( $date != null) {
$user_details[$key]['date'] = $date;
}
if( $address != null ) {
$user_details[$key]['address'] = $address;
}
$user_details[$key]['last_modified'] = date('Y-m-d H:i:s');
// updates the specific user..
$status = 'success';
$message = 'User details update successfully!';
}
}
// encode array to json and save to file
file_put_contents($request_user_url, json_encode($user_details));
return new JsonResponse(array('status' => $status, 'message' => $message));
}
Step 5:
Third method for delete the JSON data [ delete()
]
/** * @Route("/api/user-delete/{id}", name="api_user_delete") */
public function delete(Request $request) {
$status = 'error';
$message = 'User not found!';
$userId = $request->get('id');
// make api request
$request_user_url = '../users.json';
$request_user_result = file_get_contents( $request_user_url );
$user_details = json_decode( $request_user_result, true );
foreach ( $user_details as $key => $value )
{
if( $value['id'] == $userId ) {
// delete specific user..
unset($user_details[$key]); $status = 'success'; $message = 'User deleted successfully!';
}
}
// encode array to json and save to file
file_put_contents($request_user_url, json_encode($user_details));
return new JsonResponse(array('status' => $status, 'message' => $message));
}
That's all, thanks for reading our blog, hope this will help a lot to you.
5 thoughts
Hello there, You’ve done a fantastic job. I will definitely digg it and personally recommend to my friends.
I’m confident they’ll be benefited from this site.
Feel free to surf to my webpage; เครดิตฟรี50 ยืนยันเบอร์ ล่าสุด
Greetings I am so delighted I found your site, I really found you
by mistake, while I was looking on Digg for something else, Nonetheless I am here now and would just like
to say thanks for a incredible post and a all round entertaining
blog (I also love the theme/design), I don’t have time to read it all at the
minute but I have bookmarked it and also added in your RSS feeds, so when I
have time I will be back to read much more, Please do keep up the superb job.
Also visit my web page :: เครดิตฟรี 50
This is the right blog for anybody who would like to find out about
this topic. You know so much its almost tough to argue with you (not
that I really would want to…HaHa). You definitely put a brand new spin on a subject that’s been written about
for decades. Wonderful stuff, just great!
Check out my webpage – เครดิตฟรี30
It is the best time to make some plans for the longer term and it
is time to be happy. I have read this put up and if I could I
desire to counsel you some fascinating things
or suggestions. Perhaps you can write next articles relating to
this article. I desire to learn even more issues approximately it!
Here is my site – บาคาร่า ฝากถอนไม่มีขั้นต่ำ
This comment expresses gratitude, highlights specific aspects of the article that resonated with the commenter, acknowledges the author’s effort, and expresses genuine interest in the topic. It encourages the author to continue creating valuable content and fosters a positive and engaging environment.