首页 > 解决方案 > 如何在 PHP 中使用 cURL/HTTP 将数据插入 CloudTables 数据库?错误:需要 API 密钥

问题描述

我正在使用 cURL 请求向 CloudTables 数据库中插入一行。以下是他们的 [文档][1] 上提供的示例 cURL 请求:

curl \
    -X POST \
    -d key=:apiKey \
    https://sub-domain.cloudtables.io/api/1/dataset/:id

在哪里

下面是我的 PHP 代码:

    $post = array(
        'clientId' => $user_id,
        'clientName' => $user_email,
        'dp-01' => $user_id,
        'dp-02' => $user_type,
        'dp-03' => $fullname,
        'dp-04' => $address,
    );

    $ch = curl_init('https://sub-domain.cloudtables.io/api/1/dataset/my-dataset-id');
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('key: my-api-key'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    $response = curl_exec($ch);
    curl_close($ch);

但每次回复都说:

[
  {
     "msg":"API key is required",
     "name":"key"
  }
]

为什么!!!发送 API 密钥的正确方法是什么?

我还尝试在 $post 数组和 URL 中发送 API 密钥,但得到相同的响应。[1]:https ://cloudtables.com/docs/cloud/api/rest/post-dataset

标签: phpapirestcurl

解决方案


为 , 传递一个数组CURLOPT_POSTFIELDS将使它发送一个multipart/form-data请求 - 而 API 显然期望application/x-www-form-urlencoded

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));改为使用


推荐阅读