将API参数传递给网址laravel / guzzle

时间:2018-10-09 22:44:36

标签: php laravel composer-php guzzle

我有一个简单的控制器,该控制器消耗大量的API(OpenWeatherMap),并在输入时生成get请求。但是,我希望我的zipcode参数不在代码库中进行硬编码,但可以是动态的,可以通过URL进行调用。请参阅参考代码。

控制器

<?php

namespace App\Http\Controllers;

use GuzzleHttp\Client;
use Illuminate\Http\Request;

class GuzzleController extends Controller
{
    public  function index()
{

    try {

        $client = new Client([
    // Base URI is used with relative requests
            'base_uri' => 'http://api.openweathermap.org/data/2.5/',
        ]);

        $response = $client->request('GET', 'forecast', [
            'query' => [
                'zip' => '32811',
                'country code' => 'us',
                'APPID' => '02f129190a8736e107260eadce1d781e'

            ],

        ]);

        if($response->getStatusCode() == 200) {
            return $response->getBody()->getContents();

        }
    } catch(Exception $e) {
        echo "Error: " . $e->getMessage();
    }
}
}

路线

Route::get('forecast', 'GuzzleController@index');

1 个答案:

答案 0 :(得分:1)

有两种方法可以实现这一目标。

  1. 带有查询字符串参数

URL:app.tld/forecast?zip=32811

您的控制器:

public function index(Request $request)
{
    ...

    $response = $client->request('GET', 'forecast', [
        'query' => [
            'zip' => $request->input('zip'),
            'country code' => 'us',
            'APPID' => '02f129190a8736e107260eadce1d781e'
        ],
    ]);

    ...
}
  1. 具有更好的网址:

URL:app.tld/forecast/32811(32811是邮政编码)

您的路线:

Route::get('forecast/{zip}', 'GuzzleController@index');

您的控制器:

public function index(string $zip)
{
    ...

    $response = $client->request('GET', 'forecast', [
        'query' => [
            'zip' => $zip,
            'country code' => 'us',
            'APPID' => '02f129190a8736e107260eadce1d781e'
        ],
    ]);

    ...
}