Membaca API dengan Laravel sangat mudah. Kita akan membaca api yang disediakan oleh https://jsonplaceholder.typicode.com. Endpointnya adalah https://jsonplaceholder.typicode.com/posts/{post_id}
Langkah 1 : Buat Route
Modifikasi routes/web.php dengan menambahkan baris berikut:
1 |
Route::get('/test-api', 'TestController@get_api'); |
Langkah 2 : Buat Controller dan Method get_api()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class TestController extends Controller { public function get_api(){ $post_id = $_REQUEST['post_id']; $url = "https://jsonplaceholder.typicode.com/posts/".$post_id; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); curl_close($ch); $response_json = json_decode($output); $response_array = json_decode($output,true); echo "Response JSON : "; echo "<pre>"; print_r($response_json); echo "</pre>"; echo "Response Array : "; echo "<pre>"; print_r($response_array); echo "</pre>"; } } |
Langkah 3 : Jalankan URL
Ketik di browser : http://localhost:8000/test-api?post_id=3
Hasilnya seperti ini :