Dre
Dre

Reputation: 723

How to upload a pdf by sending a POST Request to an API

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.

Upvotes: 4

Views: 21342

Answers (1)

Femi
Femi

Reputation: 64700

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.

Upvotes: 4

Related Questions