Forum Discussion
elik1001
Jan 03, 2025Copper Contributor
Azure DevOps - How to Publish Artifacts Using REST API in Python?
I'm struggling to implement this functionality and could use some help. Here's my setup: I'm using YAML pipelines in Azure DevOps. Part of the pipeline includes a Python task with a long and compl...
Kidd_Ip
Jan 04, 2025MVP
Try below with logging which help to diagnose the issue:
import os
import requests
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
organization = 'your_organization'
project = 'your_project'
build_id = 'your_build_id'
artifact_name = 'your_artifact_name'
artifact_files = ['path/to/your/artifact1', 'path/to/your/artifact2']
container_url = f"https://dev.azure.com/{organization}/{project}/_apis/resources/Containers/c82916f3-4665-43bf-8927-e05a3b6492a9"
# Part 1 - Create artifact metadata
url = f"https://dev.azure.com/{organization}/{project}/_apis/build/builds/{build_id}/artifacts?artifactName={artifact_name}&api-version=7.1-preview.5"
headers = {
"Authorization": f"Basic {ACCESS_TOKEN}",
"Accept": "application/json",
"Content-Type": "application/json",
}
payload = {
"name": artifact_name,
"resource": {
"type": "Container",
"data": artifact_name,
"properties": {
"RootId": artifact_name
}
},
}
logger.info("Creating artifact metadata...")
response = requests.post(url, headers=headers, json=payload)
if response.status_code == 200:
logger.info("Artifact metadata created successfully.")
response_json = response.json()
logger.info(f"Create Pre-Payload Response: {response_json}")
else:
logger.error(f"Failed to create artifact metadata: {response.status_code}, {response.text}")
# Part 2 - Upload artifacts
headers = {
"Authorization": f"Basic {ACCESS_TOKEN}",
"Content-Type": "application/octet-stream",
}
for artifact_file in artifact_files:
if not os.path.exists(artifact_file):
logger.warning(f"File {artifact_file} does not exist. Skipping.")
continue
item_path = f"{artifact_name}/{os.path.basename(artifact_file)}"
upload_url = f"{container_url}?itemPath={item_path}"
logger.info(f"Uploading: {artifact_file} to {upload_url}")
with open(artifact_file, "rb") as f:
response = requests.put(upload_url, headers=headers, data=f)
if response.status_code == 201:
logger.info(f"File {artifact_file} uploaded successfully.")
else:
logger.error(f"Failed to upload {artifact_file}: {response.status_code}, {response.text}")