How to call API from controller Laravel without using curl and guzzle as its not working

Mahendra Pratap picture Mahendra Pratap · May 10, 2019 · Viewed 12.3k times · Source

How to call an API from a controller using a helper in laravel without using curl and guzzle because both returing nothing. I have tested in postman the api is working fine but not in laravel. I need to call several API's from different controllers so what would be a good way to do this? Should i build a helper?

I used curl but it is always giving me a false response.

EDIT:

I am looking for a reliable way to make api calls to various url's without having to rewrite the sending and receiving code for each api I want to use. Preferably a solution that implements "dry" (don't repeat yourself) principles and would serve as a base for any api specific logic, (parsing the response /translating for a model). That stuff would extend this base.

Answer

Akash Kumar Verma picture Akash Kumar Verma · May 10, 2019

you can use Guzzle pacakge docs: https://github.com/guzzle/guzzle

installation

composer require guzzlehttp/guzzle

GET

    $client = new \GuzzleHttp\Client();
    $request = $client->get('example.com');
    $response = $request->getBody();
    return $response;

POST

    $client = new \GuzzleHttp\Client();
    $body['name'] = "Testing";
    $url = "http://my-domain.com/api/v1/post";
    $response = $client->request("POST", $url, ['form_params'=>$body]);
    $response = $client->send($response);
    return $response;

Some Usefull Methods

    $response->getStatusCode(); # 200
    $response->getHeaderLine('content-type'); # 'application/json; charset=utf8'
    $response->getBody(); # '{"id": 1420053, "name": "guzzle", ...}'
  • We can also send asynchronous request
    $request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
    $promise = $client->sendAsync($request)->then(function ($response) {
        echo 'I completed! ' . $response->getBody();
    });
    $promise->wait();
  • we can also add headers
    $header = array('Authorization'=>'token');
    $client = new \GuzzleHttp\Client();
    $request = $client->get('example.com',array('headers' => $header));
    $response = $request->getBody();

Helper For this Method

we can create a common helper for these methods.

  • firstly create folder in app folder
    app\Helper
  • then create a file inside Helper folder
    app\Helper\Helper.php
  • add this code in Helper.php
<?php 

namespace App\Helper;
class Helper
{

    public static function GetApi($url)
    {
        $client = new \GuzzleHttp\Client();
        $request = $client->get($url);
        $response = $request->getBody();
        return $response;
    }


    public static function PostApi($url,$body) {
        $client = new \GuzzleHttp\Client();
        $response = $client->request("POST", $url, ['form_params'=>$body]);
        $response = $client->send($response);
        return $response;
    }
}

  • Now in controller use
    use App\Helper\Helper;
    Helper::GetApi('ultimateakash.com');

We can also do this without helper

  • In Main controller we can create these functions
<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function GetApi($url)
    {
        $client = new \GuzzleHttp\Client();
        $request = $client->get($url);
        $response = $request->getBody();
        return $response;
    }


    public function PostApi($url,$body) {
        $client = new \GuzzleHttp\Client();
        $response = $client->request("POST", $url, ['form_params'=>$body]);
        $response = $client->send($response);
        return $response;
    }
}
  • Now in controllers we can call
    $this->GetApi('ultimateakash.com');