Search code examples
pythonpython-3.xhttpspytest

Python POST to API requests issue


I'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 though 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't figure out why it fails.


Solution

  • 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.