I have a problem trying to upload a file into an API. In the swagger UI I have not problem uploading an excel file manually. When I try tu upload using request, I recive a 415 error (Invalid format of my file). Here is a simple code of that post request:
headers = {
'Authorization':"bearer "+ CLIENT.token,
'Content-Type': 'form-data'
}
files = [('file', open(path_to_file, 'rb'))]
response = requests.post(api_url,
files=files,
headers=headers)
My response has status code 415, I dont Know what is happening. When I used the swagger, I inspected the newtwork browser, and I saw this header in the request
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarywkrdGd3ROh0GkfsW
But, I don't know what is the term "boundary", and if I pass this header manually into the requests, the API throws a 500.
The server is saying that your Content-Type is wrong. If you're uploading a .xls file use:
'Content-Type': 'application/vnd.ms-excel'
If you're uploading a .xlsx file use:
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
Related
I have an API I am building out that will allow me to upload media to my WordPress website using their new API. I have searched all over the internet and SO for a solution to this problem, but all of the answers seem to be using an older WordPress API so I have not had much success in finding an answer.
I have the following code written out in a function to send a multipart/form-data request to the API:
img = open(image_path, 'rb')
file_name = os.path.basename(image)
print('Compressing and sending data...')
NEW_HEADER = {
'Authorization': f'BEARER {WORDPRESS_ACCESS_TOKEN}',
'Content-Disposition': f'attachment; filename={file_name}',
'Content-Type': 'multipart/form-data'
}
response = requests.post(
url=WORDPRESS_MEDIA_URL,
files={'media': img.read()},
headers=NEW_HEADER
)
print(response.request)
print(response.text)
return response
Which returns me:
{"media":[],"errors":[]}
<Response [200]>
OK
So, it sends something to the endpoint, but it's return an empty array and empty error box. Again, I can't seem to find any solution for the new WP, so forgive me if the Python seems a little hacky and put-together, I've just been putting together what appears to work.
Further Reading Since Original Posting
I pinged the API with Postman and it returns data as expected:
{"media":[{"id":"xxxx","date":"2022-11-03T20:06:54-05:00","parent":0,"link":"https:mywebsite","title":"mypicture","caption":"","description":"",...}
So, Since the post request seems to not be the issue, I tried to debug my request in Postman and my local console to see what was being sent:
{'User-Agent': 'python-requests/2.28.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Authorization': 'BEARER QnkXS43KhiqO7Oa!9G!zN2gnz90hHhZEribF2ddZu0h8&5V0p5M69^OwDb9E6H%B', 'Content-Type': 'multipart/form-data', 'Content-Length': '6'}
media=
And I see that the media returns empty from my local console. In Postman, the media is returned as undefined (though I'm not sure if that's just Postman being unable to parse the image in a JSON format in the console/debugger.
This leads me to believe that either the way I am accessing/calling the directory with the image is wrong, or the way I am trying to encode it to the request.
Even Further Reading Since Posting
I have since circumnavigated any concerns about directory issues by copying the photos from an external directory to that of one inside the project folder.
Since then, it appears that the current way I am sending the data returns the same response as if I am sending nothing at all:
response = requests.post(
url=WORDPRESS_MEDIA_URL, # there is no data sent in this request.
headers=NEW_HEADER
)
Which still returns me:
{"media":[],"errors":[]}
<Response [200]>
OK
This leads me to believe that the way I am sending the data is incorrect, as WordPress is receiving my request, but is not getting the information that it needs.
So, doing some further reading and research, I come across requests-toolbelt, which is to help sending multipart/form-data:
data = MultipartEncoder(fields={'media': (file_name, img, 'image/jpeg')})
new_header = {
'Authorization': f'BEARER {WORDPRESS_ACCESS_TOKEN}',
'Content-Type': data.content_type,
'Content-Disposition': 'form-data; name="media"; filename="%s"' % name_img,
}
response = requests.post(WORDPRESS_MEDIA_URL, data=data, headers=new_header)
Now, when I send a request with this data, I get this response:
{"error":"unsupported_mime_type","message":"File type unknown"}
<Response [400]>
Bad Request
So sending the request with the MultipartEncoder returns an error of an unsupported MIME type. So while it isn't a blank 200 response, it gives me reason to think that perhaps I am using the MultipartEncoder wrong, or I am not making the proper adjustments to the picture I am trying to upload.
Any insight into this would be greatly appreciated.
I've created an Azure app to update OneDrive files automatically via Python. I want it to enter someone else's drive and download files from or upload files there. However, I'm struggling forming the correct request link.
I'm currently doing something like this:
r = requests.post(f"https://graph.microsoft.com/v1.0/me/drive", headers = {"Authorization": "Bearer "+at, "content-type":"Application/Json"}) #at = authorization token
and get the error
'{\r\n "error": {\r\n "code": "BadRequest",\r\n "message": "Empty Payload. JSON content expected.",\r\n "innerError": {\r\n "date": "2021-02-01T07:52:02",\r\n "request-id": "6d159ace-252a-41a3-8805-dad6cd633348",\r\n "client-request-id": "6d159ace-252a-41a3-8805-dad6cd633348"\r\n }\r\n }\r\n}'
I'd like to enter one drive with link like this: https://xxx-my.sharepoint.com/personal/someemail_xxx_ru/_layouts/15/onedrive.aspx
How should I form the request?
You just sent a post request to the endpoint, but in this request, you did not specify other required information, such as directory, source file object, etc.These informations should be included in the json carried in the request.By the way, your endpoint also seems to be missing your onddrive path
Here's exampel document
you can using python like this:
requests.post(
'<endpoint>',
headers={'Authorization': 'Bearer ' + <token>, 'Content-type': 'application/json'},
data=json.dumps(<json_information>).json())
Fill in the <> with your information
I've written an API to return a CSV to a user based on content they fill into a form in a web application. When running the code below, I can see the response in my console and am certain that the content is properly being returned by my API, but I can't seem to get the file to automatically start downloading.
csv = final_df.to_csv()
response = make_response(csv)
response.headers['Content-Disposition'] = "attachment; filename=export.csv"
response.headers['Content-type'] = "application/force-download"
return response
A working example of mine differs by quoting the filename (which the Developer Docs hint at being required), and using a correct mimetype.
Try
return bytes(csv, encoding='UTF-8'), 200, {
'Content-Type': 'text/csv',
'Content-Disposition': 'attachment; filename="export.csv"'}
I am having a real headache with the way of sending a pdf file to a Telegram Bot.
Apparently I am following the documentation but never get it sent.
I am using the url: https://api.telegram.org/botBOTID/sendDocument?chat_id=CHATID&document=/home/lix/Downloads/2.pdf
It is a pdf file storaged locally, but I think it is just the way I am presenting it.
The error getting is:
{"ok":false,"error_code":400,"description":"Bad Request: URL host is empty"}
Does anybody knows how to send a pdf local file?
Many thanks
You should send a POST request, with the PDF as a payload, using the Python Requests library, your code should look something like this:
import requests
# Url with bot token + user id
url = "https://api.telegram.org/bot<MY-BOT-TOKEN>/sendDocument?chat_id=<MY_CHAT_ID>"
# Create payload with PDF file
payload = {}
files = [
('document', open('/home/lix/Downloads/2.pdf','rb'))
]
headers= {}
# Request
response = requests.request("POST", url, headers=headers, data = payload, files = files)
# Log reponse as UTF-8
print(response.text.encode('utf8'))
I am trying to upload an MP4 file, using requests.post. I'm not sure if it is due to the size of the file, as it is 3.2MB and I have seen people saying they have issues over 1.5MB. Any help is appreciated. Thanks
def post_video(URL):
files = {'file': open(file_path, 'rb')}
response = requests.post(URL, files=files)
return response
The response code should 204, however it is returning 500. The request works on Swagger UI
It won't let me comment,
The most likely cause is that you're not adding a header to your post that is required. I'd look at the REST API's documentation or even the Swagger UI and enter the developer console, watch the output and ensure you're adding everything needed.
Headers usually include the content type and sometimes include an authentication token, have you authenticated with the end point?
Here is an example of my proposition:
def getresponse:
userpass = b64encode(b"<username>:<password>").decode("ascii")
headers = {'Content-type':'video/mp4', 'Authorization': 'Basic ' + userpass}
files = {'file': open(file_path, 'rb')}
response = requests.post(URL, files=files, headers=headers)
return response