Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the JSON reponse from an API with Laravel

I am just messing with APIs and now I'm trying to use Google Directions API in my app.

I made a form to get the user's input and retrieve this data and create the URI just in the routes.php file:

Route::get('/directions', function() {
    $origin = Input::get('origin');
    $destination = Input::get('destination');

    $url = "http://maps.googleapis.com/maps/api/directions/json?origin=" . $origin . "&destination=" . $destination . "&sensor=false";
});

That URL's response is a JSON. But now, how am I supposed to store that response with Laravel? I have been looking at the Http namespace in Laravel and I didn't find a way. If it can't be done with Laravel, how can it be done with plain php?

like image 395
dabadaba Avatar asked Dec 01 '22 18:12

dabadaba


2 Answers

You can use file_get_contents()

Route::get('/directions', function() {
    $origin = Input::get('origin');
    $destination = Input::get('destination');

    $url = urlencode ("http://maps.googleapis.com/maps/api/directions/json?origin=" . $origin . "&destination=" . $destination . "&sensor=false");

    $json = json_decode(file_get_contents($url), true);

    dd($json);
});
like image 128
Laurence Avatar answered Dec 03 '22 23:12

Laurence


you can try this step...

set route...

Route::get('/json', [yourController::class, 'getJSON']);

and the method for get value as json format

public function getJSON(Request $request)
{

    $url = 'https://api******';

    $response = file_get_contents($url);
    $newsData = json_decode($response);


    return response()->json($newsData);         

}
like image 37
Shuvo Avatar answered Dec 03 '22 23:12

Shuvo