4

I have tried to upload a pdf by sending a POST Request to an API in R and in Python but I am not having a lot of success.

Here is my code in R

library(httr)

url <- "https://envoc-apply-api.azurewebsites.net/api/apply"
POST(url, body = upload_file("filename.pdf"))

The status I received is 500 when I want a status of 202

I have also tried with the exact path instead of just the filename but that comes up with a file does not exist error

My code in Python

import requests

url ='https://envoc-apply-api.azurewebsites.net/api/apply'
files = {'file': open('filename.pdf', 'rb')}
r = requests.post(url, files=files)

Error I received

FileNotFoundError: [Errno 2] No such file or directory: 'filename.pdf'

I have been trying to use these to guides as examples.

R https://cran.r-project.org/web/packages/httr/vignettes/quickstart.html

Python http://requests.readthedocs.io/en/latest/user/quickstart/

Please let me know if you need any more info. Any help will be appreciated.

Dre
  • 713
  • 1
  • 8
  • 27

1 Answers1

4

You need to specify a full path to the file:

import requests

url ='https://envoc-apply-api.azurewebsites.net/api/apply'
files = {'file': open('C:\Users\me\filename.pdf', 'rb')}
r = requests.post(url, files=files)

or something like that: otherwise it never finds filename.pdf when it tries to open it.

Femi
  • 64,273
  • 8
  • 118
  • 148
  • 1
    thank you for your answer. I entered the full path and here is the error I received. `SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape` – Dre Mar 24 '17 at 22:04
  • Try escaping your backslashes: `open('C:\\Users\\me\\filename.pdf')` – Femi Mar 24 '17 at 22:18
  • Once I added the backlashes it ran with no errors but I did not receive a status update I am not sure if my upload went through. – Dre Mar 24 '17 at 22:33
  • 1
    Looking at https://envoc-apply-api.azurewebsites.net/ you may need to add a bunch of extra parameters, not just the filename. – Femi Mar 24 '17 at 22:45
  • http://chat.stackoverflow.com/rooms/138988/upload-load-file-by-post-request-in-python – Dre Mar 24 '17 at 23:08