Search code examples
pythonbitbucketbitbucket-api

Extract list of Sources (branches) from Bitbucket using Python


I'm new to python and trying to update someone else's code.

I need to pull a list of Sources (branches) from Bitbucket to allow user selection from that list. The existing code successfully used URL requests to retrieve lists from Bitbucket for both Projects and Repositories but I can't find a way to access the Source location to change from the default "Master" to a user selected branch. For reference, this excerpt of code worked to extract the Repositories information:

@app.route("/initial3" , methods=['GET', 'POST'])
def initial3():
    selected_git_project = str(request.form.get('git_project'))
    selected_git_repository = str(request.form.get('git_information'))
    #checkbox_all_selection = str(request.form.get('checkbox_all'))
    confluence_information = [str(request.form.get('confluence_information'))]
    selected_page = request.form.get('page_id')
    returnlistsearch = []
    url = 'https://git.ourcompanyname.com/rest/api/1.0/projects/'+selected_git_project+'/repos/'+selected_git_repository+'/files?limit=1000'
    resources_json = requests.get(url, auth=(git_user, git_password)).json()
    resources_json_dump = (json.dumps(resources_json, indent=4, sort_keys=False))
    decoded = json.loads(resources_json_dump)
    for x in decoded['values']:
        if '.robot' in x:
            location=os.path.dirname(x)
            if location!='':
                returnlistsearch.append(location)
    returnlistsearch =remove_duplicated(returnlistsearch)
    return render_template('initial3.html',git_repository=selected_git_repository,git_project=selected_git_project ,git_information=returnlistsearch)

I thought I could reuse the same code but with a modified URL (some references on docs.atlassian seemed to indicate that would work):

url = 'https://git.ourcompanyname.com/rest/api/1.0/projects/'+selected_git_project+'/repos/'+selected_git_repository+'/files?limit=1000'

Any suggestions would be much appreciated - My first look EVER at python was two days ago.


Solution

  • After significant trial and error I've discovered the syntax that works. The branch reference is applied at the end of the HTTP request.

    Retrieve the branch information:

    url = 'https://git.ourcompanyname.com/rest/api/1.0/projects/'+project+'/repos/'+repository+'/files?limit=10000&at='+branch
    

    Retrieve the list of files within the branch:

    url2 = 'https://git.ourcompanyname.com/rest/api/1.0/projects/'+project+'/repos/'+repository+'/browse/' + results + '?at='+branch