PHP中的REST API请求 - 查询错误

时间:2018-05-26 23:56:13

标签: php rest api

我正在使用post.rest网络服务向API发出请求。我使用Postman构建了请求。我收到了错误消息,"参数'查询'是必需的,它必须有一个值。"我一直试图解决这个问题好几天,而且我一直在努力工作。结束。我以为我可以自己解决,但没有成功。我似乎已经尝试了至少一百种不同的代码排列。

以下是我的请求的PHP代码:

     <?php
     $curl = curl_init();

     curl_setopt_array($curl, array(
     CURLOPT_URL => "https://SDMDataAccess.sc.egov.usda.gov/Tabular/post.rest",
     CURLOPT_RETURNTRANSFER => true,
     CURLOPT_ENCODING => "",
     CURLOPT_MAXREDIRS => 10,
     CURLOPT_TIMEOUT => 30,
     CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
     CURLOPT_CUSTOMREQUEST => "POST",
     CURLOPT_POSTFIELDS => 
        $data = array("query" => "SELECT l.areasymbol, l.areaname, l.lkey, 
          musym, muname, museq, mu.mukey
          FROM sacatalog sac 
          INNER JOIN legend l ON l.areasymbol = sac.areasymbol 
          AND l.areatypename = 'Non-MLRA Soil Survey Area' 
          INNER JOIN mapunit mu ON mu.lkey = l.lkey 
          AND mu.mukey IN (455997) 
          ", "FORMAT" => "JSON"),
     CURLOPT_HTTPHEADER => array(
        "Cache-Control: no-cache",
        "Content-Type: application/json",
        "Postman-Token: 520636bc-a062-4ab8-99e7-7edaae5118b4"
      ),
    ));

    file_put_contents('soil_request.txt', $data);
    $response = curl_exec($curl);

    $err = curl_error($curl);

    curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

我无法找到任何代码,用于在其文档或互联网上的其他地方向此API服务提交休息请求,即使他们的文档很多。

提前感谢您对此的考虑。我真的很感激。

1 个答案:

答案 0 :(得分:1)

https://en.1answer.info/676973-7a313939383734看起来您可能需要在发送之前将数据数组更改为json字符串

另外,你的行是

CURLOPT_POSTFIELDS=>$data=array("select ....

错了。

相反,定义您的数据数组,然后从中构建一个http查询字符串。此外,参数名称区分大小写,因此您希望使用query代替QUERYformat而不是FORMAT

工作代码 -

 <?php

    $data["query"]="SELECT l.areasymbol, l.areaname, l.lkey,
          musym, muname, museq, mu.mukey
          FROM sacatalog sac
          INNER JOIN legend l ON l.areasymbol = sac.areasymbol
          AND l.areatypename = 'Non-MLRA Soil Survey Area'
          INNER JOIN mapunit mu ON mu.lkey = l.lkey
          AND mu.mukey IN (455997)";

     $data["format"] = "JSON";

     $curl = curl_init();

     curl_setopt_array($curl, array(
     CURLOPT_URL => "https://SDMDataAccess.sc.egov.usda.gov/Tabular/post.rest",
     CURLOPT_RETURNTRANSFER => true,
     CURLOPT_ENCODING => "",
     CURLOPT_MAXREDIRS => 10,
     CURLOPT_TIMEOUT => 30,
     CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
     CURLOPT_CUSTOMREQUEST => "POST",
     CURLOPT_POSTFIELDS => http_build_query($data),
     CURLOPT_HTTPHEADER => array(
        "Cache-Control: no-cache",
        "Content-Type: application/json",
        "Postman-Token: 520636bc-a062-4ab8-99e7-7edaae5118b4"
      ),
    ));

    file_put_contents('soil_request.txt', $data);
    $response = curl_exec($curl);

    $err = curl_error($curl);

    curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}