【问题标题】:Passing an API parameter to url laravel/guzzle将 API 参数传递给 url laravel/guzzle
【发布时间】:2019-03-14 18:41:52
【问题描述】:

我有一个简单的控制器,它使用带有 guzzle 的 API(OpenWeatherMap)并在进入时生成一个获取请求。但是我希望我的 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');

【问题讨论】:

    标签: php laravel composer-php guzzle


    【解决方案1】:

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

    1. 带有查询字符串参数

    网址: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'
            ],
        ]);
    
        ...
    }
    

    【讨论】:

    • 非常感谢,这两种方法都有效!我实际上将采用这一点逻辑并创建一个可以拉入并且任何人都可以使用的作曲家包。但只是做一些事情来建立我的简历
    猜你喜欢
    • 2021-06-24
    • 2015-07-12
    • 1970-01-01
    • 2014-04-07
    • 1970-01-01
    • 2012-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多