프로그래밍

PHP Restful API 클라이언트 예제

warpmemory 2017. 12. 12. 10:25

예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
require_once "restclient.php";
 
$api_url = "https://api.warpmemory.com";
$api_ver = "v1";
$id = "";
$passwd = "";
$api = new RestClient(array(
    'base_url' => "$api_url/$api_ver",
    'headers'      => array(
        //'Authorization' => "Basic ".base64_encode("$id:$passwd"),
        'Content-Type'  => "application/json",
    ),
    'curl_options' => array(
        CURLOPT_SSL_VERIFYPEER => FALSE,
        CURLOPT_TIMEOUT => 1
    ),
));
 
$server = "server-001.warpmemory.com";
$user = "test";
$passwd = "password";
$quota = 1000;
$bandwidth = 2000;
$domain = "test.warpmemory.com";
$charset = "utf8";
 
/*
    사용자 추가
*/
$result = $api->post("/hosting/users?server=$server&user=$user",
                     array('passwd'    => $passwd,
                           'quota'     => $quota,
                           'bandwidth' => $bandwidth,
                           'domain'    => $domain,
                           'charset'   => $charset
                     )
                );
if($result->info->http_code == 200)
    var_dump($result->decode_response());
 
/*
    사용자 트래픽 제한 변경
*/
$result = $api->put("/hosting/users/$user/properties/bandwidth?server=$server",
                    array(
                        'bandwidth' => 1000
                    )
                );
if($result->info->http_code == 200)
    var_dump($result->decode_response());
 
/*
    사용자 조회
*/
$result = $api->get("/hosting/users/$user?server=$server");
if($result->info->http_code == 200)
    var_dump($result->decode_response());
 
/*
    사용자 삭제
*/
$result = $api->delete("/hosting/users/$user?server=$server");
if($result->info->http_code == 200)
    var_dump($result->decode_response());
?>
cs

restclient.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
<?php
/**
 * PHP REST Client
 * https://github.com/tcdent/php-restclient
 * (c) 2013 Travis Dent <tcdent@gmail.com>
 */
class RestClientException extends Exception {}
class RestClient implements Iterator, ArrayAccess {
    public $options;
    public $handle// cURL resource handle.
    // Populated after execution:
    public $response// Response body.
    public $headers// Parsed reponse header object.
    public $info// Response info object.
    public $error// Response error string.
    // Populated as-needed.
    public $decoded_response// Decoded response body.
    private $iterator_positon;
    public function __construct($options=array()){
        $default_options = array(
            'headers' => array(),
            'parameters' => array(),
            'curl_options' => array(),
            'user_agent' => "PHP RestClient/0.1.2",
            'base_url' => NULL,
            'format' => NULL,
            'format_regex' => "/(\w+)\/(\w+)(;[.+])?/",
            'decoders' => array(
                'json' => 'json_decode',
                'php' => 'unserialize'
            ),
            'username' => NULL,
            'password' => NULL
        );
        $this->options = array_merge($default_options$options);
        if(array_key_exists('decoders'$options))
            $this->options['decoders'= array_merge(
                $default_options['decoders'], $options['decoders']);
    }
    public function set_option($key$value){
        $this->options[$key= $value;
    }
    public function register_decoder($format$method){
        // Decoder callbacks must adhere to the following pattern:
        //   array my_decoder(string $data)
        $this->options['decoders'][$format= $method;
    }
    // Iterable methods:
    public function rewind(){
        $this->decode_response();
        return reset($this->decoded_response);
    }
    public function current(){
        return current($this->decoded_response);
    }
    public function key(){
        return key($this->decoded_response);
    }
    public function next(){
        return next($this->decoded_response);
    }
    public function valid(){
        return is_array($this->decoded_response)
            && (key($this->decoded_response) !== NULL);
    }
    // ArrayAccess methods:
    public function offsetExists($key){
        $this->decode_response();
        return is_array($this->decoded_response)?
            isset($this->decoded_response[$key]) : isset($this->decoded_response->{$key});
    }
    public function offsetGet($key){
        $this->decode_response();
        if(!$this->offsetExists($key))
            return NULL;
        return is_array($this->decoded_response)?
            $this->decoded_response[$key] : $this->decoded_response->{$key};
    }
    public function offsetSet($key$value){
        throw new RestClientException("Decoded response data is immutable.");
    }
    public function offsetUnset($key){
        throw new RestClientException("Decoded response data is immutable.");
    }
    // Request methods:
    public function get($url$parameters=array(), $headers=array()){
        return $this->execute($url'GET'$parameters$headers);
    }
    public function post($url$parameters=array(), $headers=array()){
        return $this->execute($url'POST'$parameters$headers);
    }
    public function put($url$parameters=array(), $headers=array()){
        return $this->execute($url'PUT'$parameters$headers);
    }
    public function delete($url$parameters=array(), $headers=array()){
        return $this->execute($url'DELETE'$parameters$headers);
    }
    public function execute($url$method='GET'$parameters=array(), $headers=array()){
        $client = clone $this;
        $client->url = $url;
        $client->handle = curl_init();
        $curlopt = array(
            CURLOPT_HEADER => TRUE,
            CURLOPT_RETURNTRANSFER => TRUE,
            CURLOPT_USERAGENT => $client->options['user_agent']
        );
        if($client->options['username'&& $client->options['password'])
            $curlopt[CURLOPT_USERPWD] = sprintf("%s:%s",
                $client->options['username'], $client->options['password']);
        if(count($client->options['headers']) || count($headers)){
            $curlopt[CURLOPT_HTTPHEADER] = array();
            $headers = array_merge($client->options['headers'], $headers);
            foreach($headers as $key => $value){
                $curlopt[CURLOPT_HTTPHEADER][] = sprintf("%s:%s"$key$value);
            }
        }
        if($client->options['format'])
            $client->url .= '.'.$client->options['format'];
        $parameters = array_merge($client->options['parameters'], $parameters);
        if(strtoupper($method== 'POST'){
            $curlopt[CURLOPT_POST] = TRUE;
            if ($headers['Content-Type'== "application/json"){
                $curlopt[CURLOPT_POSTFIELDS] = json_encode($parameters);
            }
            else {
                $curlopt[CURLOPT_POSTFIELDS] = $client->format_query($parameters);
            }
        }
        elseif(strtoupper($method!= 'GET'){
            $curlopt[CURLOPT_CUSTOMREQUEST] = strtoupper($method);
            if ($headers['Content-Type'== "application/json"){
                $curlopt[CURLOPT_POSTFIELDS] = json_encode($parameters);
            }
            else {
                $curlopt[CURLOPT_POSTFIELDS] = $client->format_query($parameters);
            }
        }
        elseif(count($parameters)){
            $client->url .= strpos($client->url, '?')? '&' : '?';
            $client->url .= $client->format_query($parameters);
        }
        if($client->options['base_url']){
            if($client->url[0!= '/' && substr($client->options['base_url'], -1!= '/')
                $client->url = '/' . $client->url;
            $client->url = $client->options['base_url'] . $client->url;
        }
        $curlopt[CURLOPT_URL] = $client->url;
        if($client->options['curl_options']){
            // array_merge would reset our numeric keys.
            foreach($client->options['curl_options'as $key => $value){
                $curlopt[$key= $value;
            }
        }
        curl_setopt_array($client->handle, $curlopt);
        $client->parse_response(curl_exec($client->handle));
        $client->info = (object) curl_getinfo($client->handle);
        $client->error = curl_error($client->handle);
        curl_close($client->handle);
        return $client;
    }
    public function format_query($parameters$primary='='$secondary='&'){
        $query = "";
        foreach($parameters as $key => $value){
            $pair = array(urlencode($key), urlencode($value));
            $query .= implode($primary$pair) . $secondary;
        }
        return rtrim($query$secondary);
    }
    public function parse_response($response){
        $headers = array();
        $http_ver = strtok($response"\n");
        while($line = strtok("\n")){
            if(strlen(trim($line)) == 0break;
            list($key$value= explode(':'$line2);
            $key = trim(strtolower(str_replace('-''_'$key)));
            $value = trim($value);
            if(empty($headers[$key]))
                $headers[$key= $value;
            elseif(is_array($headers[$key]))
                $headers[$key][] = $value;
            else
                $headers[$key= array($headers[$key], $value);
        }
        $this->headers = (object$headers;
        $this->response = strtok("");
    }
    public function get_response_format(){
        if(!$this->response)
            throw new RestClientException(
                "A response must exist before it can be decoded.");
        // User-defined format.
        if(!empty($this->options['format']))
            return $this->options['format'];
        // Extract format from response content-type header.
        if(!empty($this->headers->content_type))
        if(preg_match($this->options['format_regex'], $this->headers->content_type, $matches))
            return $matches[2];
        throw new RestClientException(
            "Response format could not be determined.");
    }
    public function decode_response(){
        if(empty($this->decoded_response)){
            $format = $this->get_response_format();
            if(!array_key_exists($format$this->options['decoders']))
                throw new RestClientException("'${format}' is not a supported ".
                    "format, register a decoder to handle this response.");
            $this->decoded_response = call_user_func(
                $this->options['decoders'][$format], $this->response);
        }
        return $this->decoded_response;
    }
}
cs