Search code examples
pythonmultipartform-data

Post array of dictionary using multipart/form-data in python


I am having an issue while posting my array to some url. The requested url only supports content-type=multipart/form-data.

The documentation sample is in node.js, and it works fine. But I need to achieve it in python. After several tries I am able to send data, but it gives me error {"error":1,"message":"The data field must be an array"}

Below is my code.

# post_data = [{"x":0,"y":0,"value":"a1"}]
post_data = [
        ('x', ("data", 0)),
        ('y', ("data", 0)),
        ('value', ("data", 'x y orange')),
]
file_data ={"data":(None, str(post_data),"application/json")}
response = requests.post(post_url,files=file_data, headers=request_headers)
print(response.text)

Response:

{"error":1,"message":"The data field must be an array"}

If we use data or json in post parameter it gives us following error.

{"error":1,"message":"The Content-Type must be multipart/form-data"}

Any help will be appreciated.

Thanks in advance.


Solution

  • Thanks all for you quick support.

    Problem has been solved by updating file_data variable to this

    file_data = [
        ("data[0][x]",(None,'0')),
        ("data[0][y]",(None,'0')),
        ("data[0][value]",(None,'A1')),
    ]
    response = requests.post(post_url, files=file_data, headers=request_headers)
    print(response.text)