Python POST到API请求问题

huangapple go评论133阅读模式
英文:

Python POST to API requests issue

问题

我一直在使用 Python 3.10.10 上的 pytest 进行 API 测试并在一个 post 请求时遇到了问题以下是我目前的代码

```python
import requests as req

api = '某个API'
header = {
    'Apikey': '某个令牌',
    'Content-Type': 'application/json'
}

payload = {
    "title": "标题",
    "description": "<p>描述</p>",
    "column_id": 12345,
    "lane_id": 1234
}

URL = api + '/cards'

card_id = 0

def test_get_card():
    x = req.get(
        URL,
        headers=header,
        params={'cards_id': 123456}
    )

    assert x.status_code == 200

def test_create_card():
    x = req.post(
        URL,
        headers=header,
        data=payload
    ).json()

    print(x)

    assert x.status_code == 200

第一个测试成功了!
第二个测试返回了 400 和 请为新卡提供参考 CCR 的 column_id,或通过使用 card_properties_to_copy 从现有卡中复制。

如果我在 Insomnia 中运行相同的请求,返回 200。我无法弄清楚为什么它失败了。

任何帮助都将不胜感激!


<details>
<summary>英文:</summary>

I&#39;ve been working on making API tests with pytest on Python 3.10.10 and I have stumbled on an issue with a post request. Here is the code I currently have:

import requests as req

api = 'some api'
header = {
'Apikey': 'some token',
'Content-Type': 'application/json'
}

payload = {
"title": "TItle",
"description": "<p>DEscription</p>",
"column_id": 12345,
"lane_id": 1234
}

URL = api + '/cards'

card_id = 0

def test_get_card():
x = req.get(
URL,
headers=header,
params={'cards_id': 123456}
)

assert x.status_code == 200

def test_create_card():
x = req.post(
URL,
headers=header,
data=payload
).json()

print(x)

assert x.status_code == 200

The first test is a success!
The second doe returns 400 and `Please provide a column_id for the new card with reference CCR or have it copied from an existing card by using card_properties_to_copy.`

If I run the same request in `Insomnia` it returns 200. I can&#39;t figure out why it fails.

Any help would me much appreciated!

</details>


# 答案1
**得分**: 1

根据您的反馈,这是您遇到的问题。从请求文档[https://requests.readthedocs.io/en/latest/user/quickstart/#passing-parameters-in-urls][1]中可以看到:

> 有时您可能希望发送非表单编码的数据。如果您传入一个字符串而不是字典,那些数据将会被直接发送。

因此,看起来您的端点接受JSON编码的数据。在这种情况下,您应该`import json`并更新您的`test_create_card`函数如下所示。
```python
def test_create_card():
    x = req.post(
        URL,
        headers=header,
        data=json.dumps(payload)
    ).json()

    print(x)

    assert x.status_code == 200

或者,如您所发现,可以使用json参数传递payload(在版本>= 2.4.2中),这将达到相同的效果。

英文:

Based on your feedback, here was the issue you were encountering. From the request docs [https://requests.readthedocs.io/en/latest/user/quickstart/#passing-parameters-in-urls][1]

> There are times that you may want to send data that is not form-encoded. If you pass in a string instead of a dict, that data will be posted directly.

So it seems your endpoint accepts JSON-ENCODED. In that case you'll want to import json and update your test_create_card function to the following.

def test_create_card():
    x = req.post(
        URL,
        headers=header,
        data=json.dumps(payload)
    ).json()

    print(x)

    assert x.status_code == 200

or as you discovered pass the payload using the json param (in versions >= 2.4.2) which will do the same thing.

答案2

得分: 0

One:
如果我修改负载如下:
payload = &quot;{\n \&quot;title\&quot;: \&quot;TItle\&quot;,\n \&quot;description\&quot;: \&quot;&lt;p&gt;DEscription&lt;/p&gt;\&quot;,\n \&quot;column_id\&quot;: 10124,\n \&quot;lane_id\&quot;: 8629\n}&quot;

它可以正常工作!

Two:
如果我将请求中的data=payload改为json=payload,也可以解决这个问题。

英文:

So I found two solutions!

One:
If I modify the payload as:
payload = &quot;{\n \&quot;title\&quot;: \&quot;TItle\&quot;,\n \&quot;description\&quot;: \&quot;&lt;p&gt;DEscription&lt;/p&gt;\&quot;,\n \&quot;column_id\&quot;: 10124,\n \&quot;lane_id\&quot;: 8629\n}&quot;

It goes through!

Two:
If I change in the request data=payload to json=payload that fixes the issue as well.

huangapple
  • 本文由 发表于 2023年5月25日 18:55:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76331527.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定