[Python] Posting to API with cURL works while Python requests fails

Discussão em 'Python' iniciado por Stack, Abril 10, 2025.

  1. Stack

    Stack Membro Participativo

    I have a cURL command that works when uploading a file while the equivalent Python requests fails.

    Here is the cURL command

    curl -X POST "http://<DOMAIN>/polarion/rest/v1/projects/<PROJECT_ID>/workitems/<WORKITEM_ID>/attachments" \
    -H "Authorization: Bearer <TOKEN>" \
    -H "accept: application/json" \
    -H "Content-Type: multipart/form-data" \
    -F resource="{\"data\": [{\"type\": \"workitem_attachments\",\"attributes\": {\"fileName\": \"test.txt\",\"title\": \"test\"}}]}" \
    -F files=@"test.txt"


    And here is the Python

    import requests
    import json

    url = "http://<DOMAIN>/polarion/rest/v1/projects/<PROJECT_ID>/workitems/<WORKITEM_ID>/attachments"

    headers = {
    "Content-Type": "multipart/form-data",
    "accept": 'application/json',
    "Authorization": "Bearer " + token
    }

    data = {
    "data": [
    {
    "type": "workitem_attachments",
    "attributes": {
    "fileName": "test.txt",
    "title": "test"
    }
    }
    ]
    }

    files = {
    'resource': (None, json.dumps(data)),
    'files': ("test.txt", open('test.txt', 'rb'))
    }

    r = requests.post(url, files=files, headers=headers)


    While the cURL command works the Python fails with:

    {"errors":[{"status":"400","title":"Bad Request","detail":null,"source":null}]}


    I've compared the body for both from --trace-ascii and Request.prepare and they appear to be identical. Unless there is an encoding issue, I'm not sure what's wrong.

    Here is the API reference: https://testdrive.polarion.com/pola...i-WorkItemAttachments-postWorkItemAttachments

    Continue reading...

Compartilhe esta Página