Home > Net >  Get the repository id based on repository name via azure API by python script
Get the repository id based on repository name via azure API by python script

Time:09-30

I have the pyhton script.it fetched Repo id for all repos.It is too big ouput file. I am interested only get repo id for specifiec repo(ex:XYZ)

CodePudding user response:

Please try this:

import azure.devops.connection as connection
import msrest.authentication as basic_authentication

PAT = "***" # personal access token
AZURE_DEVOPS_URI = ""
PROJECT = ""

def get_repository_id_by_repo_name(repo_name):
    credentials = basic_authentication.BasicAuthentication("", PAT)
    connection_to_clients = connection.Connection(base_url=AZURE_DEVOPS_URI , creds=credentials)
    clients = connection_to_clients.clients_v5_1
    git_client = clients.get_git_client()
    repositories = git_client.get_repositories(project=PROJECT)
    for repo in repositories:
        repository_name = str(repo.name)
        if repository_name == repo_name:
            return repo.id
    return "Repository not found"

Alternately use the Python request, in the following sample it will only print the specific repo content:

import requests
import base64
import json

pat = 'PAT-Here'
authorization = str(base64.b64encode(bytes(':' pat, 'ascii')), 'ascii')

headers = {
    'Accept': 'application/json',
    'Authorization': 'Basic ' authorization
}

response = requests.get(
    url="https://dev.azure.com/{org}/{project}/_apis/git/repositories?api-version=5.1", headers=headers).json()
 
# Filter python objects with list comprehensions
output_dict = [x for x in response["value"] if x['name'] == 'Your_Repo_Name']

print (output_dict)

CodePudding user response:

Import the libraries

from azure.devops.connection import Connection import requests import base64 from pprint import pprint import json

Check the authorization

pat = "tyd4WERTT2344" authorization = str(base64.b64encode(bytes(':' pat, 'ascii')), 'ascii')

headers = {

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

'Authorization': 'Basic ' authorization

}

Validate the API response & get the repository id

url="https://dev.azure.com/Org/Project/_apis/git/repositories/Repo_Name?api-version=6.0"

response = requests.get(url=url, headers=headers)

data = response.json()

repo_id = str(data['id'])

  • Related