Python requests to send POST request with form-data input

Viewed 8608

I have an API which send request to system, we are sending body request as form-data option.

  1. Key: Document, value: sample.doc, type: file
  2. Key: Request, value: {"Data": { "Number": "17329937082", "Format": "MSW" }}, type: Text

How can achieve this in Pyhton script using Requests. This worked in Postman and I am trying to call this API with python script.

1 Answers

For form-encoded data, you'll want the data kwarg paired with a dictionary, not a string. To demonstrate how this works, I'll use the requests.Request object:

from requests import Request
import json

request_dict = {'Data': {'Number': "17329937082", "Format": "MSW"}}

data = {
    'Document': open('sample.doc', 'rb'),   # open in bytes-mode
    'Request': json.dumps(request_dict)     # formats the dict to json text
}

r = Request('GET', 'https://my-url.com', data=data)
req = r.prepare()

r.headers
{'Content-Length': '80595', 'Content-Type': 'application/x-www-form-urlencoded'}

So in a normal request, that will look like:

import requests
import json

request_dict = {'Data': {'Number': "17329937082", "Format": "MSW"}}

data = {
    'Document': open('sample.doc', 'rb'),   # open in bytes-mode
    'Request': json.dumps(request_dict)     # formats the dict to json text
}

r = requests.get('my_url.com', data=data)
Related