首页 > 解决方案 > 使用 Laravel 和 Guzzle 检索 API 响应

问题描述

我想从我的 Laravel 项目中的 API 中得到答案。显然 Guzzle 似乎是最好的解决方案。这是版本 1.6.0b6 中的 Check_MK API

我创建了一个模型来与 API 通信以尊重 MVC 模型

模型

<?php

namespace App;

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;

class Hostgroup
{
    public static function all() {
        $client = new \GuzzleHttp\Client();
        $request = new Request('GET', 'https://my-api-uri.tld', [
            'query' => [
                'action' => 'get_all_host',
                '_username' => 'user',
                '_secret' => 'secret',
                'output_format' => 'json'
            ]]);
        $hostgroup = $client->send($request, ['timeout' => 2]);
        return $hostgroup;
    }
}

控制器

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Hostgroup;

class MainDashboardController extends Controller
{

    public function index() {
        $hostgroup = Hostgroup::all();
        return view('dashboard.main', [
            'hostgroup' => $hostgroup
        ]);
  }
}

目前,我在项目页面上收到错误 500,但 API 向我发送了带有请求标头的代码 200。

其实我得到了这个:

Response {#209 ▼
  -reasonPhrase: "OK"
  -statusCode: 200
  -headers: array:9 [▶]
  -headerNames: array:9 [▶]
  -protocol: "1.1"
  -stream: Stream {#207 ▼
    -stream: stream resource @278 ▼
      wrapper_type: "PHP"
      stream_type: "TEMP"
      mode: "w+b"
      unread_bytes: 0
      seekable: true
      uri: "php://temp"
      options: []
    }
    -size: null
    -seekable: true
    -readable: true
    -writable: true
    -uri: "php://temp"
    -customMetadata: []
  }
}

标签: laravelapiguzzle

解决方案


$hostgroupPsr\Http\Message\ResponseInterface你可能不想要的。您将需要响应的实际内容。尝试添加这个:

return $hostgroup->getBody()->getContents();

推荐阅读