1

Uploading files and retrieving them with the REST API and Python

Hi Everyone,

In the docs for the REST API, we describe a method to upload a file (SwaggerHub link). Because an example is always good, here is some code:

import sys
import json
import requests

if len(sys.argv) != 5:
    print("Usage: python dopost.py <server> <project> <token> <path to file>")
    exit(1)

server = sys.argv[1]
project = sys.argv[2]
token = sys.argv[3]
filepath = sys.argv[4]

url = f"https://{server}/rest/1/{project}/file"

payload = {}
files=[
  ('file',('example.png',open(filepath,'rb'),'application/octet-stream'))
]

headers = {
  'authorization': 'Token ' + token
}

response = requests.request("POST", url, headers=headers, data=payload, files=files)

print(response.text)

fileAck = json.loads(response.text)
fileId = fileAck['fileId']
key = fileAck['key']
fileUrl = f"https://{server}/rest/1/{project}/file/{fileId}?key={key}"

print("To retrieve the file, GET this url: " + fileUrl)

With server, project and API token you can upload a file to the server. In the acknowledgement, you get a fileId and a key, which should be remembered in order to get the file again later. To refer to the image in a rich text control, embed that url in an img tag, for example:

 If I click on the View menu of the rich text control I can see the source code. The image is embedded as shown:

<p>The purpose of risk management is to identify potential problems before they occur so
that risk-handling activities may be planned and invoked as needed across the life
of the product or project to mitigate adverse impacts on achieving objectives.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>
  <img style="width: 604px; height: 453px;"
   src="https://sample.matrixreq.com/rest/1/WHEELY_MIKE/file/4712?key=key_k5unahgtjjvogh5rv02obv8m9v"
   alt="" width="5712" height="4284">
</p>

Let me know of any problems with the code above or other questions, all the best!

--Mike, Dev Team

Content aside

  • 1 Likes
  • 3 wk agoLast active
  • 13Views
  • 1 Following