首页 > 解决方案 > How to call API from controller Laravel without using curl and guzzle as its not working

问题描述

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.

标签: laravelapilaravel-5guzzle

解决方案


Laravel 7.x 和 8.x 的更新。现在我们可以使用内置的 Http(Guzzle HTTP) 客户端了。

文档:: 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;

对于 Laravel < 7,你需要安装 Guzzle 包

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

安装

composer require guzzlehttp/guzzle

得到

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

邮政

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

一些有用的方法

$response->getStatusCode(); 
$response->getHeaderLine('content-type');  
$response->getBody();  
  • 我们还可以添加标题
$header = ['Authorization' => 'token'];
$client = new \GuzzleHttp\Client();
$response = $client->get('example.com', ['headers' => $header]); 

此方法的助手

我们可以为这些方法创建一个通用助手。

  • 在 app 文件夹中创建 Helpers 文件夹
app\Helpers
  • 然后在 Helpers 文件夹中创建一个文件 Http.php
app\Helpers\Http.php
  • 在 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;
    }
}


  • 现在在控制器中你可以使用这个助手。
<?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);
    }
}

没有助手

  • 在主控制器中,我们可以创建这些功能
<?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;
    }
}
  • 现在在控制器中我们可以调用
<?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);
    }
}

推荐阅读