Spread the love

In this article we will learn to call an external Url API in Laravel. Whenever we want to access the third party data we need to access the data using the APIs, we send a request to another server means outside our application and they respond with preformatted structure.

In laravel there is multiple ways to call the Rest APIs Url using the file_get_contents, curl or Guzzel package. file_get_contents is php core function which we can use to call the external api both Post and Get. curl basically a command line software which used for transferring data between servers and php provides its inbuilt library in php core then final Guzzel is a package which is a http client makes easy to send HTTP requests.

In this article i will use a simple example to send the Rest get and post request using both these 3 methods and will use a controller and routes.

So let’s start the tutorial of Call an External Url API in Laravel

Send GET HTTP Request in Laravel

In this example we will send a GET request to another server using three methods as follow

Method 1 : Send Request Using file_get_contents

This one is easiest method to send the request to external server

<?php 
use Illuminate\Support\Facades\Route;


Route::get("/send-request",function(){

    $response = file_get_contents("https://api.sampleapis.com/cartoons/cartoons2D");
    dump($http_response_header);
    dump(json_decode($response));
    return $response;
});

Output :

php file get contents
php file get contents

Method 2 : Send Request Using curl

Second method is to use the Curl to send the request

<?php 
use Illuminate\Support\Facades\Route;


Route::get("/send-request",function(){

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.sampleapis.com/cartoons/cartoons2D");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    dump($httpcode);
    dump(json_decode($output));
    return $output;


});

Output :

Php curl
Php curl

Method 3 : Send Request Using Guzzel

Third method is to use the Guzzel package to send the request

<?php 
use Illuminate\Support\Facades\Route;


Route::get("/send-request",function(){

$client = new \GuzzleHttp\Client();
$res = $client->get('https://api.sampleapis.com/cartoons/cartoons2D');
dump( $res->getStatusCode()); // 200
echo (  $res->getBody());
return 1;


});

Output :

Php curl
Php curl

Leave a Reply