Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 949
Mahendra Pratap Avatar asked May 10 '19 05:05

Mahendra Pratap


Video Answer


1 Answers

Update For Laravel 7.x and 8.x. Now we can use inbuilt Http(Guzzle HTTP) client.

docs:: https://laravel.com/docs/8.x/http-client#making-requests

use Illuminate\Support\Facades\Http;

$response = Http::get('https://jsonplaceholder.typicode.com/posts');

$response = Http::post('https://jsonplaceholder.typicode.com/posts', [
    'title' => 'foo',
    'body' => 'bar',
    'userId' => 1
]);

$response = Http::withHeaders([
    'Authorization' => 'token' 
])->post('http://example.com/users', [
    'name' => 'Akash'
]);

$response->body() : string;
$response->json() : array|mixed;
$response->object() : object;
$response->collect() : Illuminate\Support\Collection;
$response->status() : int;
$response->ok() : bool;
$response->successful() : bool;
$response->failed() : bool;
$response->serverError() : bool;
$response->clientError() : bool;
$response->header($header) : string;
$response->headers() : array;

For Laravel < 7 you need to install Guzzle pacakge

docs: https://docs.guzzlephp.org/en/stable/index.html

Installation

composer require guzzlehttp/guzzle

GET

$client = new \GuzzleHttp\Client();
$response = $client->get('https://jsonplaceholder.typicode.com/posts'); 
return $response;

POST

$client = new \GuzzleHttp\Client();
$body = [
    'title' => 'foo',
    'body' => 'bar',
    'userId' => 1
]; 
$response = $client->post('https://jsonplaceholder.typicode.com/posts', ['form_params' => $body]); 
return $response;

Some Usefull Methods

$response->getStatusCode(); 
$response->getHeaderLine('content-type');  
$response->getBody();  
  • we can also add headers
$header = ['Authorization' => 'token'];
$client = new \GuzzleHttp\Client();
$response = $client->get('example.com', ['headers' => $header]); 

Helper For this Method

we can create a common helper for these methods.

  • Create a Helpers folder in app folder
app\Helpers
  • then create a file Http.php inside Helpers folder
app\Helpers\Http.php
  • add this code in Http.php
<?php

namespace App\Helpers;

use GuzzleHttp;

class Http
{

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


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


  • Now in controller you can use this helper.
<?php

namespace App\Http\Controllers;
 
use Illuminate\Routing\Controller as BaseController;
use App\Helpers\Http;

class Controller extends BaseController
{

    /* ------------------------ Using Custom Http Helper ------------------------ */
    public function getPosts()
    {
        $data = Http::get('https://jsonplaceholder.typicode.com/posts');
        $posts = json_decode($data->getBody()->getContents());
        dd($posts);
    }


    public function addPost()
    {
        $data = Http::post('https://jsonplaceholder.typicode.com/posts', [
            'title' => 'foo',
            'body' => 'bar',
            'userId' => 1
        ]);
        $post = json_decode($data->getBody()->getContents());
        dd($post);
    }
}

Without Helper

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

namespace App\Http\Controllers;

use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{

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


    public function post($url,$body) {
        $client = new GuzzleHttp\Client();
        $response = $client->post($url, ['form_params' => $body]);
        return $response;
    }
}
  • Now in controllers we can call
<?php

namespace App\Http\Controllers;
   
class PostController extends Controller
{
    public function getPosts()
    {
        $data = $this->get('https://jsonplaceholder.typicode.com/posts');
        $posts = json_decode($data->getBody()->getContents());
        dd($posts);
    }


    public function addPost()
    {
        $data = $this->post('https://jsonplaceholder.typicode.com/posts', [
            'title' => 'foo',
            'body' => 'bar',
            'userId' => 1
        ]);
        $post = json_decode($data->getBody()->getContents());
        dd($post);
    }
}
like image 168
Akash Kumar Verma Avatar answered Sep 26 '22 07:09

Akash Kumar Verma