Sobes.tech
Junior — Middle

How to implement file transfer to a server via REST API?

sobes.tech AI

Answer from AI

To upload a file to a server via REST API, a multipart/form-data content type HTTP request is usually used. In Python, using the requests library, it is done as follows:

import requests

url = 'https://example.com/upload'
files = {'file': open('path/to/file.txt', 'rb')}
response = requests.post(url, files=files)
print(response.status_code)

Here, the key 'file' is the parameter name expected by the server. The file is transmitted in binary form in the request body. The server must be configured to accept multipart requests and handle the file.

If you need to send additional data, you can add it to the data parameter:

data = {'param1': 'value1'}
response = requests.post(url, files=files, data=data)