【问题标题】:Post request to API to create a new client is not working向 API 发布创建新客户端的请求不起作用
【发布时间】:2018-11-26 15:06:39
【问题描述】:

我想向这个 API“https://invoicexpress.com/api/invoices/create”发出一个 post 请求来创建一个新的客户端。

在那个文档页面中说必填字段是:日期、到期日期、客户和项目。

我有下面的代码,但我得到一个错误:

Client error: POST https://nametest.app.invoicexpress.com/invoices.xml?api_key=... 
resulted in a `422 Unprocessable Entity` response: 
<?xml version="1.0" encoding="UTF-8"?> <errors> <error>
Expected &lt;invoice&gt;</error> </errors>

你知道为什么会出现这个错误吗?

代码:

public function createClient(){

        $client = new \GuzzleHttp\Client();
        $response = $client->request('POST', 'https://nametest.app.invoicexpress.com/invoices.xml', [
            'query' => ['api_key' => '...'],
            'date' => date('Y-m-d H:i:s'),
            'due_date' => date('Y-m-d H:i:s'),
            'client'   => 'John',
            'code'  => '',

            'items' => [
                'item' => [
                    'name' => 'item1',
                    'description' => 'item1 desc',
                    'unit_price' => '10',
                    'quantity' => '1'
                ],

                'item' => [
                    'name' => 'item2',
                    'description' => 'item2 des',
                    'unit_price' => '10',
                    'quantity' => '1'
                ]
            ]

        ]);
        dd($response->getStatusCode());

    }

【问题讨论】:

标签: php laravel api


【解决方案1】:

文档指出您的 XML 中的顶级元素必须是 &lt;invoice&gt;,您的数据中缺少该元素。它应该看起来更像:

$response = $client->request('POST', 'https://nametest.app.invoicexpress.com/invoices.xml', [
    'invoice' => [
        'query' => ['api_key' => '...'],
        ...
    ]
]);

还注意到您有'client' =&gt; 'John',,但文档表明它应该更像'client' =&gt; ['name' =&gt; 'John'],。

【讨论】:

  • 谢谢,所以“code”参数也应该在“client”数组中?
  • 使用:公共函数 createClient(){ $client = new \GuzzleHttp\Client(); $response = $client->request('POST', 'testname.invoicexpress.com/invoices.xml', ['query' => ['api_key' => '....'], 'invoice' => ['date' => date('Ymd H:i:s'), 'due_date' => date('Ymd H:i:s'), 'client' => ['name' => 'John', 'code' => ' '], 'items' => [ 'item' => [ 'name' => 'item1', 'description' => 'item1 desc', 'unit_price' => '10', 'quantity' => '1 ' ] ] ] ]); dd($response->getStatusCode()); }.
猜你喜欢
  • 1970-01-01
  • 2020-10-10
  • 1970-01-01
  • 2021-12-21
  • 1970-01-01
  • 1970-01-01
  • 2019-01-27
  • 2017-02-21
  • 1970-01-01
相关资源
最近更新 更多