Hello Developers,
Sometimes you find that you need to call a simple GET
request to fetch any data. You see in Laravel, to call any API different types of packages are used. But there is an efficient to call any GET
request without any package. In this demonstration, you will see that.
For that, first, you need to create a controller, I have created a TestController by the following command:
php artisan make:controller
After that, you need to define a route.
<?php
use App\Http\Controllers\TestController;
Route::get('/get_data', [TestController::class, 'get_data'])->name('get_data');
Now in the controller, you have to call file_get_contents()
the function and wrap it with json_decode()
. The code is given below:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class TestController extends Controller
{
public function get_data(){
$json = json_decode(file_get_contents('https://countriesnow.space/api/v0.1/countries/positions'), true);
return $json;
}
}
Then you need to call the below command to start the project:
php artisan serve
After that, just call the route in the browser.
http://127.0.0.1:8000/get_data
Hope this might help you in your journey of development.