Forums

Uploading a file with the API

I have the following code to upload a file to my account:

import requests

TOKEN = '#######################################'
FILEPATH = 'files/path/home/ArtyBot/web'
API = 'https://www.pythonanywhere.com/api/v0/user/ArtyBot/'

res = requests.post(API + FILEPATH + '/app.py',
                    params={'content': 'import flask'},
                    headers={'Authorization': 'Token ' + TOKEN})
print(res)
print(res.json())

However I think I have done it wrong as I receive the following output:

<Response [400]>
{'detail': "You must provide a file with the name 'content'."}

I am quite new to using APIs, how should I do what I am trying to achieve?

Try something like this:

 res = requests.post(API + FILEPATH + '/app.py',
     files={'content': 'import flask'},
     headers={'Authorization': 'Token ' + TOKEN}
 )

Thanks, it worked!

How would it work if I have a dataframe/csv to be uploaded?

You're just uploading a file. Whether it's a text file, a dataframe or a csv makes no difference.

maybe help me with what im doing wrong...I get response 400

I have tried both

csv= pd.read_excel('xyz.xlsx').to_records(index=False).tostring()

csv = pd.read_excel('xyz.xlsx')

resp = requests.post( urljoin(api_base, "files/path/home/{username}/xyz.xlsx".format(username=username)), files={"content": csv}, headers={"Authorization": "Token {api_token}".format(api_token=api_token)} )

Thanks

What is the content of the 400 response?

Apologies.... The response is 201 when I convert the dataframe to bytes but the file uploaded remains unreadable.

And direct upload of dataframe doesn't work as content can only be bytes.

Ah. Looks like I have some apologies, too. The dataframe would need to be serialised to send it across the network. I would suggest using one of the methods here https://pandas.pydata.org/pandas-docs/stable/reference/frame.html#serialization-io-conversion to serialise it to a file and then read the file into the content for the upload. Then you can deserialise it at the other end.

that works thanks!!

Hi is it possible to upload a video file to the server using the api? If so then can you tell me how?

Yes, that should be possible. What have you tried?