简体   繁体   中英

Consume REST API using Guzzle 6

I try to consume REST API using Guzzle 6. I read the documentation of Guzzle and I got way to consume REST API like below :

<?php

class Index extends CI_Controller {

    use GuzzleHttp\Client;

    $client = new Client([    
        'base_uri' => 'https://api.rajaongkir.com/basic/'
    ]); //LINE ERROR

    public function __construct() {
        parent::__construct();
        $this->load->helper('url');
    }

    function index() {
        // $client = new GuzzleHttp\Client(['base_uri' => 'https://api.rajaongkir.com/basic/']);
        $key = "b5231ee43b8ee75764bd6a289c4c576d";
        $response = $client->request('GET','province?key='.$key);
        $data['data'] = json_decode($response->getBody());
        $this->load->view('index', $data);
    }
}

If I declare variable $client in function index() there is no problem. I get the JSON and I success to show in my view. I want just once declare base uri and key and I can use the base uri and key to all function I have.

So I try to declare variable that contains base uri and key as global variable. But I got error in line $client . The error is :

syntax error, unexpected '$client' (T_VARIABLE), expecting function (T_FUNCTION) or const (T_CONST)

How to fix it? What wrong with my code?

You can not write any code directly in class definition. You need to define class variable (field) and create instance of class in constructor, eg:

class Index extends CI_Controller {

    use GuzzleHttp\Client;
    protected $client;

    public function __construct() {
        parent::__construct();
        $this->load->helper('url');
        $this->client = new Client([    
            'base_uri' => 'https://api.rajaongkir.com/basic/'
        ]); //LINE ERROR
    }

    function index() {
        // $client = new GuzzleHttp\Client(['base_uri' => 'https://api.rajaongkir.com/basic/']);
        $key = "b5231ee43b8ee75764bd6a289c4c576d";
        $response = $client->request('GET','province?key='.$key);
        $data['data'] = json_decode($response->getBody());
        $this->load->view('index', $data);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM