php - 为什么我使用 Guzzle 对 API 的发布请求不起作用?
问题描述
我想向 API 发出发布请求以创建新客户端,但出现错误:
Client error: `POST https://testname.app.invoicexpress.com/document-type.json?api_key=...`
resulted in a `404 Not Found` response: <!doctype html>
<!--[if lt IE 7]> <html class="no-js ie6 oldie" lang="en">
<![endif]--> <!--[if IE 7]> <html class="n (truncated...)
在文档“ https://developers.invoiceexpress.com/docs/versions/2.0.0/resources/invoices ”中说要创建一个新客户端以及发票,curl 命令如下:
curl --request POST \
--url 'https://account_name.app.invoicexpress.com/:document-type.json?api_key=YOUR%20API%20KEY%20HERE' \
--header 'accept: application/json' \
--header 'content-type: application/json' \
--data '{"invoice":{"date":"03/12/2017","due_date":"03/12/2017","client":{"name":"Client Name","code":"A1"},"items":[{"name":"Item Name","description":"Item Description","unit_price":"100","quantity":"5"}]}}'
但是使用下面的代码而不是 curl 命令,它会显示该错误。
public function generateInvoice()
{
$client = new \GuzzleHttp\Client();
$array = [
'invoice' => [
'date' => '03/12/2017',
'due_date' => '03/12/2017',
'client' => [
'name' => 'Client Name',
'code' => 'A1'
],
'items' => [
[
'name' => 'Item Name',
'description' => 'Item Description',
'unit_price' => '100',
'quantity' => '5'
]
]
]
];
$response = $client->request('POST', 'https://testname.app.invoicexpress.com/invoices.json', [
'query' => ['api_key' => '...'], 'form_params' => [$array],
]);
dd($response->getStatusCode());
}
Wihout [] 并且只有 $array 在 'form_params' 显示:
Client error:
`POST https://testname.app.invoicexpress.com/invoices.json?api_key=...` resulted
in a `422 Unprocessable Entity`
response: {"errors":[{"error":"Items element should be of type array"}]}
解决方案
尝试用'json'重命名你的参数'form_param'
喜欢:'form_params' => [$array] to
'json' => [$array]
推荐阅读
- javascript - 你知道任何 SaaS 构建器框架(登录、用户管理、密码重置、数据库管理、CMS)
- c++ - 从方法返回指向 flatbuffer 的指针
- python - HTTP 服务器重定向不起作用(Python)
- java - Spring -@Recover - 找不到恢复方法
- c# - 如何在 OpenTK .NET Core 中设置 OpenGL API 版本?
- cytoscape.js - 单击 cytoscape 图上的节点调用方法
- python - 熊猫数据透视表返回字符串不是值
- android - Android Studio 小部件在相对布局中消失
- python - 函数名后的冒号不会导致语法错误
- python - 我如何检查一个字符串是否包含另一个字符串