Uploading and associating attachments using REST API

Tuesday, May 26, 2020
Avatar

If you want to upload an attachment using REST API and optionally associate it to an artifact in a project in Spiraplan, use the following code:

Python Code:

import requests
import json
import base64
from pathlib import Path

# Change the path to the your file path. Filename will be read from path.
file = Path(r'C:\Users\Documents\Files\Capture.PNG')
filename = file.name

# ArtifactTypeId (Requirement=1, Test Cases=2, Incident=3, Test Run=5, Test Sets=8)
# ArtifactId is the spiraplan id for the selected artifact type
ArtifactId = 25991
ArtifactTypeId = 3

# Endpoint URL. 44 is the project id.
URL = "https://api.inflectra.com/SpiraPlan/Services/v6_0/RestService.svc/projects/44/documents/file?username=username&api-key={API-KEY}"

# Headers for the endpoint
headers = {"Accept": "application/json", "Content-Type" : "application/json"}

# Encoding the file to base64 format
with open(file, 'rb') as fd:
    b64data = base64.b64encode(fd.read()).decode("utf-8")

# Generating payload to just upload the attachment to a project
payload = f'{{"AttachmentTypeId": 1, "BinaryData": "{b64data}", "FilenameOrUrl": "{filename}"}}'

# Generating payload to upload and associate the attachment to an artifact in a project
payload = f'{{"AttachmentTypeId": 1, "BinaryData": "{b64data}", "FilenameOrUrl": "{filename}", "AttachedArtifacts": [{{"ArtifactId": {ArtifactId}, "ArtifactTypeId": {ArtifactTypeId}}}]}}'

# Calling POST method 
response = requests.post(URL, headers=headers, data = payload)
print(response)
print(response.text)

 

Postman:

URL: https://api.inflectra.com/SpiraPlan/Services/v6_0/RestService.svc/projects/44/documents/file?username=username&api-key={API-KEY}

Header:  'Accept': 'application/json', 'Content-Type': 'application/json'

Body (Type: Raw-JSON) :  {"AttachmentTypeId": 1, "BinaryData": "VGVzdGluZyBmaWxlIHVwbG9hZA==", "FilenameOrUrl": "Test_Postman.txt", "AttachedArtifacts": [{"ArtifactId": 25991, "ArtifactTypeId": 3}]}

Optionally you can generate the code for the post method from within Postman by selecting the language of your choice.

2 Replies
Tuesday, May 26, 2020
Avatar
re: nchauras Tuesday, May 26, 2020

Thanks :-)

Spira Helps You Deliver Quality Software, Faster and With Lower Risk

And if you have any questions, please email or call us at +1 (202) 558-6885

 

Statistics
  • Started: Tuesday, May 26, 2020
  • Last Reply: Wednesday, January 19, 2022
  • Replies: 2
  • Views: 9726