이전 목록 다음

Curl을 사용한 api 연결질문입니다.

상대방 서버에서 api 를 열어줬는데 처음 연결해 보는거라 사용법이 틀린건지 잘 몰라서 질문드립니다. 

/api/Price
Method POST
API 유형 REST
데이터포멧 JSON
요청변수(header) 항목명(국문) 항목명(영문)
API 키 X-API-Key
비밀 키 X-Secret-Key
요청변수(Request Parameter) 항목명(국문) 항목명(영문)
심볼명 symbol

상대방한테는 이렇게 정보를 받았습니다. 

 

구글링을 하다가 아래의 코드를 사용했습니다.

Copy
function get_http_status_message($_status) {
  $arr_http_status = array(
          100 => 'Continue',
          101 => 'Switching Protocols',
          200 => 'OK',
          201 => 'Created',
          202 => 'Accepted',
          203 => 'Non-Authoritative Information',
          204 => 'No Content',
          205 => 'Reset Content',
          206 => 'Partial Content',
          300 => 'Multiple Choices',
          301 => 'Moved Permanently',
          302 => 'Found',
          303 => 'See Other',
          304 => 'Not Modified',
          305 => 'Use Proxy',
          306 => '(Unused)',
          307 => 'Temporary Redirect',
          400 => 'Bad Request',
          401 => 'Unauthorized',
          402 => 'Payment Required',
          403 => 'Forbidden',
          404 => 'Not Found',
          405 => 'Method Not Allowed',
          406 => 'Not Acceptable',
          407 => 'Proxy Authentication Required',
          408 => 'Request Timeout',
          409 => 'Conflict',
          410 => 'Gone',
          411 => 'Length Required',
          412 => 'Precondition Failed',
          413 => 'Request Entity Too Large',
          414 => 'Request-URI Too Long',
          415 => 'Unsupported Media Type',
          416 => 'Requested Range Not Satisfiable',
          417 => 'Expectation Failed',
          500 => 'Internal Server Error',
          501 => 'Not Implemented',
          502 => 'Bad Gateway',
          503 => 'Service Unavailable',
          504 => 'Gateway Timeout',
          505 => 'HTTP Version Not Supported');

  if( $_status == null ) {
      // return http status array
      return $arr_http_status;
  }

  return ($arr_http_status[$_status]) ? $arr_http_status[$_status] : $status[500];
}

function curl_request_data($_target, $_data = "", $_arr_opt = "", $_timeout = 0) {
    $curl_handle = curl_init();
    curl_setopt($curl_handle, CURLOPT_URL, $_target);
    curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, $_timeout);

    if( $_data != "" ) {
        curl_setopt($curlsession, CURLOPT_POST, true);
        curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $_data);
    }

    if( $_arr_opt != "" ) {
        if( isset($_arr_opt["X-API-Key"]) && isset($_arr_opt["X-Secret-Key"]) ) {
            curl_setopt($curl_handle, CURLOPT_HEADER, "{$_arr_opt["X-API-Key"]}:{$_arr_opt["X-Secret-Key"]}");
        }
    }

    $response = curl_exec($curl_handle);
    $http_code = curl_getinfo($curl_handle, CURLINFO_HTTP_CODE);

    // 1. curl 오류 검출
    if( curl_errno($curl_handle) != 0 ) {
        curl_close($curl_handle);

        return '{
                "code": 503,
                "message": "Service Unavailable",
                "result": ""
        }';
    }
    curl_close($curl_handle);

    // 2. http response code 오류 검출
    if( $http_code != 200 ) {
        return '{
                "code": ' . $http_code . ',
                "message": "' . get_http_status_message($http_code) . '",
                "result": ""
        }';
    }

    // 3. json format 오류 검출
    json_decode($response);
    if( json_last_error() != JSON_ERROR_NONE ) {
        return '{
                "code": 500,
                "message": "Internal Server Error",
                "result": "invalid JSON format"
        }';
    }

    // 4. 정상 case 출력
    return $response;
}

이렇게 만들고

 

Copy
$api_key = 'xxx';
$secret_key = '1111';
$str_target = "https://xxxx.com/api/Price";  
$str_data    = "symbol=BRL";
$arr_opt    = array("X-API-Key" => $api_key, "X-Secret-Key" => $secret_key);

 

이렇게 요청을 했더니 

 { "Code": 500, "Message": "Internal Server Error", "Result": "Invalid JSON Format" }

라고만 뜨는데 이건 어디가 잘못 된건가요 ?ㅠ_ㅠ API 초보의 질문입니다.

|

답변 3개 / 댓글 2개

https://stackoverflow.com/questions/11079135/how-to-post-json-data-with-php-curl

 

참고하세요.

 

 

$url = 'url_to_post';

$data = array("first_name" => "First name","last_name" => "last name","email"=>"email@gmail.com","addresses" => array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" => "Mother","last_name" => "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );

 

$postdata = json_encode($data);

 

$ch = curl_init($url); 

curl_setopt($ch, CURLOPT_POST, 1);

curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

$result = curl_exec($ch);

curl_close($ch);

print_r ($result);

이렇게 해보는건 어떠실까요?

if ($_arr_opt != "") {
    if (isset($_arr_opt["X-API-Key"]) && isset($_arr_opt["X-Secret-Key"])) {
        $headers = array(
            "X-API-Key: {$_arr_opt["X-API-Key"]}",
            "X-Secret-Key: {$_arr_opt["X-Secret-Key"]}"
        );
        curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $headers);
    }
}


위의 코드는 CURLOPT_HTTPHEADER 옵션을 사용하여 헤더 정보를 전달하고 있습니다.
 

호출자가 어떠한 요구사항을 충족하지 않고 요청을 전송해 문제가 발생했을지언정

500 Internal Server Error 는 서비스 제공자 쪽에서 문제가 있어서 발생하는 응답이기 때문에

상대방에게 문의를 해야 합니다만

API 서버쪽에서 나는 에러가 아닌 수신자측에서 가공한 오류메세지가 출력되는것 같습니다.

답변에 대한 댓글 2개

아... 그런가요? 일단 상대방 쪽에도 문의를 남겼습니다. 감사합니다
[code]
$response = curl_exec($curl_handle);
$http_code = curl_getinfo($curl_handle, CURLINFO_HTTP_CODE);
[/code]

이후 라인부터 수신자측에서 가공한 오류메세지 형태가 있습니다.
가공부분 보다 먼저 다음처럼 응답 직후 정상 데이터가 수신됐는지 확인해볼 필요가 있습니다.

[code]
$response = curl_exec($curl_handle);
$http_code = curl_getinfo($curl_handle, CURLINFO_HTTP_CODE);
var_dump($response);
var_dump($http_code);
[/code]

답변을 작성하려면 로그인이 필요합니다.