azureapiface

azure face api return 401 when sent with php


https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395236/console

When send the request through here with my api key, response returned successfully.

When send through cURL with php, return 401

$request_url = 'https://westus.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&recognitionModel=recognition_01&returnRecognitionModel=false&detectionModel=detection_01';
$header  = array('Ocp-Apim-Subscription-Key'=> '{sub_key}', 'Content-Type' => "application/json");
$test_data = array('url' => '{image_url}');

$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_URL, $request_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_POSTFIELDS, $test_data);

$result = curl_exec($curl);

Please tell me where I did wrong


Solution

  • I think the way how you set the headers is wrong. Here is my successful sample:

    <?php
        $request_url = 'https://southeastasia.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&recognitionModel=recognition_01&returnRecognitionModel=false&detectionModel=detection_01';
        $headers      = [
               "Ocp-Apim-Subscription-Key:1fb1105*********92c6eb8b",
               "Content-Type:application/json"
        ];
    
    
        $test_data = array('url' => 'https://storagetest789.blob.core.windows.net/pub/Untitled.png');
    
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($curl, CURLOPT_URL, $request_url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($test_data));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    
    
        $strResponse = curl_exec($curl);
        $curlErrno   = curl_errno($curl);
        if ($curlErrno) {
               $curlError = curl_error($curl);
               throw new Exception($curlError);
        }
    
        $http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
    
        print_r($http_status."\n");
        print_r($strResponse."\n");  
    ?>
    

    The Result:

    enter image description here