How should I pass text/plain data to python’s requests.post?
To demonstrate how this works, I’ll use the object: So in a normal request, that will look like: Question: I had created a simple python program to send Post Api request using request module However, I wish to replace the below string to use a variable something to below Solution 1: If you want to pass json data to your API, you can directly use the json attribute of the function with a dictionary variable. Question: I have an API which send request to system, we are sending body request as form-data option.
How to send form-data using python requests?
I’m trying to send a POST request using python 3 and the requests library. When I use postman I’m obtaining the result that I’m expecting, so I copy the code generated by Postman, and in that way it is working.
This is the code generated by postman code:
import requests payload = "name=\"claveElector\"\r\n\r\nABCDEF01234567H400\r\nname=\"numeroEmision\"\r\n\r\n01\r\nname=\"ocr\"\r\n\r\n4158093946570\r\nname=\"g-recaptcha-response\"\r\n\r\nsome-captcha\r\nname=\"modelo\"\r\n\r\na" url = "https://listanominal.ine.mx/scpln/resultado.html" payload = "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"claveElector\"\r\n\r\nTPRSJC95010209H400\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"numeroEmision\"\r\n\r\n01\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"ocr\"\r\n\r\n4158093946570\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"g-recaptcha-response\"\r\n\r\nsome-re-captcha\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"modelo\"\r\n\r\na\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--" headers = < 'content-type': "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW", >response = requests.request("POST", url, data=payload, headers=headers) print(response.text)
To be more clear in the part of why is not working is the difference that exists in both results.
With the postman code i got this
That code is generated with the following data:
So I tried to do the same using my own code, I’ve tried to send the data in the file part, and in the data part but is not working. Reading other StackOverflow questions, they suggest to use the MultipartEncoder that is part of the Requests Toolbelt library.
So my implementation ended up like this:
import requests from requests_toolbelt.multipart.encoder import MultipartEncoder clave_elector = "ABCDEF01234567H400" numero_emision = "01" ocr = "1234567846570" modelo = "a" params = < "claveElector": clave_elector, "numeroEmision": numero_emision, "ocr": ocr, "modelo": modelo, "g-recaptcha-response": '' >data = MultipartEncoder(fields = params) headers = < 'Content-type': data.content_type >response = requests.post( 'https://listanominal.ine.mx/scpln/resultado.html', data = data, headers = headers ) print(response.text)
With the custom code I got the following
If you try both codes, you can see how the results are different. And I’m interested in the first one, the one that is got with the code that was generated by Postman.
I don’t know why my code is not working, what I am doing wrong? What I’m trying to say is that somehow with my code the request is not being send properly so the website is not able to read it.
After so much try and error, the only way that I found to achieve this, was to use the following code:
from requests import Request, Session clave_elector = "TPRSJC95010209H400" numero_emision = "01" ocr = "4158093946570" modelo = "a" data = < "claveElector": clave_elector, "numeroEmision": numero_emision, "ocr": ocr, "modelo": modelo, "g-recaptcha-response": 'hjkkjgh' >request = Request( 'POST', 'https://listanominal.ine.mx/scpln/resultado.html', files = < 'claveElector': (None, data['claveElector']), 'numeroEmision': (None, data['numeroEmision']), 'ocr': (None, data['ocr']), 'modelo': (None, data['modelo']), 'g-recaptcha-response': (None, 'xxx'), >).prepare() s = Session() response = s.send(request) print(response.text)
I really don’t know why this was different from what I was trying to do, but it works. If someone could comment why this works I’ll really appreciate.
How to send form-data using python requests?, That code is generated with the following data: So I tried to do the same using my own code, I’ve tried to send the data in the file part, and in the data part but is not working. Reading other StackOverflow questions, they suggest to use the MultipartEncoder that is part of the Requests Toolbelt library. So my … Code sample).prepare()s = Session()response = s.send(request)print(response.text)Feedback
How should I pass text/plain data to python’s requests.post?
I am trying to convert this curl command in python requests, but I am unsure about how I should pass the data:
curl -X POST -u "apikey:" \ --header "Content-Type: text/plain" \ --data "some plain text data" \ ""
I have tried to pass the string directly and to encode it with str.encode(‘utf-8’) but I get an error 415 Unsupported Media Type
text = "some random text" resp = requests.post(url, data=text, headers=, auth=('apikey', self.apikey))
[EDIT]: Solution is not to specify the headers in the request When using requests library, it is usually a good idea not to set Content-Type header manually using headers= keyword.
requests will set this header for you if it is needed (for example posting JSON will always result in Content-Type: application/json header).
Another reason for not setting this type of header manually is encoding , because sometimes you should specify something like Content-Type: text/plain; charset=utf-8 .
One more important thing about Content-Type is that this header is not required for making POST requests. RFC 2616:
Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource. If the media type remains unknown, the recipient SHOULD treat it as type «application/octet-stream».
So depending on the server type you’re making request to, this header may be left empty.
Sorry for this explanation being a bit vague. I cannot give you an exact explanation why this approach worked for you unless you provide target URL.
How should I pass text/plain data to python’s, When using requests library, it is usually a good idea not to set Content-Type header manually using headers= keyword.. requests will set this header for you if it is needed (for example posting JSON will always result in Content-Type: application/json header).. Another reason for not setting this type …
Python requests to send POST request with form-data input
I have an API which send request to system, we are sending body request as form-data option.
How can achieve this in Pyhton script using Requests. This worked in Postman and I am trying to call this API with python script.
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 = < '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
So in a normal request, that will look like:
import requests import json request_dict = > 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)
Python requests to send POST request with form-data, What is the best solution to make form-data request in python ? – Selvakumar. Oct 27, 2020 at 20:18. Add a comment | 1 Answer Sorted by: Reset to default 3 For form-encoded data
How to pass variable into post request in Python [duplicate]
I had created a simple python program to send Post Api request using request module
# importing the requests library import requests import json headers = < 'PRIVATE-TOKEN': 'XXXXXXXXXXXXX', 'Content-Type': 'application/json', >data = '< "ref": "cd-pipeline", "variables": [ , ] >' response = requests.post('https://gitlab.kazan.atosworldline.com/api/v4/projects/28427/pipeline', headers=headers, data=data) print(response)
However, I wish to replace the below string to use a variable
If you want to pass json data to your API, you can directly use the json attribute of the request.post() function with a dictionary variable.
# importing the requests library import requests headers = < 'PRIVATE-TOKEN': 'XXXXXXXXXXXXX', 'Content-Type': 'application/json', >deployment_status = "failed" data = < "ref": "cd-pipeline", "variables": [ , ] > response = requests.post('https://gitlab.kazan.atosworldline.com/api/v4/projects/28427/pipeline', headers=headers, json=data) print(response)
You can use an «f-string» to format the value of the variable into your data string.
deployment_status = 'status' data = f'< "ref": "cd-pipeline", "variables": [ , "> ] >'
If you have a recent version of python you can use f-strings:
deployment_status = 'failed' data = f'< "ref": "cd-pipeline", "variables": [ , "> ] >'
Ok, so that turned out to be too deeply nested for f-strings.
import json deployment_status = 'failed' data = , ] > print(json.dumps(data))
How to pass variable into post request in Python, I had created a simple python program to send Post Api request using request module # importing the requests library import requests import json headers = < 'PRIVATE-TOKEN': 'XXXXXXXXXXXXX',