How to implement httpclient api

Hello,

I installed yii2-httpclient:


$ composer require --prefer-dist yiisoft/yii2-httpclient

My goal is to display the JSON result of a GET request of an external api in a page.

How to achieve that ?

what to add in web.php , in config / components ?


'Client’ => [ 'class' => 'yii\httpclient\Client' ] 

?

should I create a controller + view ? ( how to ? do you have a sample example ? )

Could you please describe a step by step on how to implement that ?

like this snippet:


use yii\httpclient\Client;


$client = new Client();

$response = $client->createRequest()

    ->setMethod('GET')

    ->setUrl('the api url')

    ->send();

And display


$response

in a new page.

Thanks for your support

You don’t have to add it to your config you just need to composer install it. You can put your code into an a controller action and pass the response data to the view just like you have. Here is another way from the HttpClient docs.





public function actionTest() {

        $client = new \yii\httpclient\Client([

            'baseUrl' => 'http://example.com/api/1',

            'requestConfig' => [

                'format' => Client::FORMAT_JSON

            ],

            'responseConfig' => [

                'format' => Client::FORMAT_JSON

            ],

        ]);

        $request = $client->createRequest();

        echo $request->format;

    }



Hello,

Thank you very much, I really appreciate.

Do composer require yiisoft/yii2-httpclient