Запрос Openfigi php -> Тело запроса должно быть массивом JSON

#php #curl

#php #curl

Вопрос:

Я пытаюсь использовать openfigi api с php. Я продолжаю получать это сообщение об ошибке: «Тело запроса должно быть массивом JSON». Есть идеи о том, как это решить? Я попробовал несколько решений.

 $curlUrl = 'https://api.openfigi.com/v2/mapping';

    $data = array('idType' => 'ID_WERTPAPIER', 'idValue' => '851399', 'exchCode' => 'US');   
    $j = json_encode($data);


    //$apiToken = 'X-OPENFIGI-APIKEY: xxx';

    $httpHeadersArray = Array();
    
    $httpHeadersArray[] = 'Content-Type: application/json';
    //$httpHeadersArray[] = $apiToken;


    //open connection
    $ch = curl_init();

    //set the url, number of POST vars, POST data
    curl_setopt($ch, CURLOPT_URL, $curlUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $j);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeadersArray);


    $res = curl_exec($ch);

    echo "<pre>";
    print_r($res);
    echo "</pre>";
 

Ответ №1:

была такая же проблема, но решил ее.

Это мой рабочий код:

 // The url you wish to send the POST request to
$url = 'https://api.openfigi.com/v2/mapping/';

// Create a new cURL resource
$ch = curl_init($url);

// The data to send to the API
$postData = array(
    array(
        "idType" => "ID_ISIN",
        "idValue" => "US4592001014"
    )
);

// Setup cURL
curl_setopt_array($ch, array(
    CURLOPT_POST => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_POSTFIELDS => json_encode($postData)
));
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));


print_r(json_encode($postData));

// Send the request
$response = curl_exec($ch);

// Check for errors
if($response === FALSE){
die(curl_error($ch));
}

// Decode the response
$responseData = json_decode($response, TRUE);

// Print the date from the response
print_r($responseData);