Search code examples
pythonazurerestazure-devopsartifact

Download Azure Devops artifact in Python


I am able to use Azure Rest API in Python (https://github.com/microsoft/azure-devops-python-api) to get a download URL for an Artifact e.g.

artifacts = build_client.get_artifacts(project_name, build_id)

I then want to download them all with something like

for artifact in artifacts:
    urllib.request.urlretrieve(artifact.resource.download_url, artifactDownloadPath + artifact.name)

However rather than downloading the artifact it downloads the HTML page. The same link does work in a web browser.

How can I download the artifacts like I would in YAML?


Solution

  • Import requests in your script and use this API of type GET:

    https://dev.azure.com/{organization}/{project}/_apis/build/builds/{build_id}/artifacts?artifactName={artifactName}&api-version=6.0&%24format=zip

    The artifact name is the name you provide in the publish build task in your build pipeline (by default it is drop)

    Then retrieve the contents and create the file locally.

    resp = requests.get(api, auth=("", PAT))
    with open(f"{artifact_name}.zip", "wb") as f:
     f.write(resp.content)
    

    You'll then get a zip file of the published artifacts in the current working directory.