5

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.

4
  • 1
    Have you read the docs? Where did you get stuck? Commented Oct 27, 2020 at 18:27
  • I used this "r = requests.get('api.github.com/events')" for normal reqeust, but not sure what to use for "form-data" body request. I tried the Multipart-Encoded but it is giving 415 unsupported media type error in response Commented Oct 27, 2020 at 18:59
  • What did you do to try multipart encoded? Are you sure that endpoint is expecting form-encoded data? Or is it expecting json? Commented Oct 27, 2020 at 19:38
  • it is Json response. Sorry, I don't know what to use, just tried something in multipart. What is the best solution to make form-data request in python ? Commented Oct 27, 2020 at 20:18

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.