pythonflaskazure-devops-rest-api

Azure DevOps API giving random 500 errors -python flask


from flask_cors import CORS
from azure.devops.connection import Connection
from msrest.authentication import BasicAuthentication
from azure.devops.v7_1.work_item_tracking.models import Wiql

app = Flask(__name__)
CORS(app)


ORGANIZATION = "preet442727"  
PROJECT = "test"  
PAT = ""  


credentials = BasicAuthentication('', PAT)
connection = Connection(base_url=f"https://dev.azure.com/{ORGANIZATION}", creds=credentials)


wit_client = connection.clients.get_work_item_tracking_client()

@app.route("/work-items", methods=["GET"])
def get_work_items():
    
    work_item_id = 1  
    
    try:
        # Get work item by ID
        work_item = wit_client.get_work_item(work_item_id)
        return jsonify(work_item.as_dict())
    except Exception as e:
        return jsonify({"error": "Failed to fetch work item", "details": str(e)}), 500

@app.route("/all-work-items", methods=["POST"])
def get_all_work_items():
    # Create the WIQL query to retrieve work items
    wiql_query = Wiql(
        query="""
        SELECT [System.Id], [System.WorkItemType], [System.State]
        FROM WorkItems
        WHERE [System.TeamProject] = 'test'
        ORDER BY [System.ChangedDate] DESC
        """
    )
    
    try:
        result = wit_client.query_by_wiql(wiql_query)
        work_items = result.work_items
        
        detailed_work_items = []
        for item in work_items:
            work_item_id = item.id
            work_item = wit_client.get_work_item(work_item_id)
            detailed_work_items.append(work_item.as_dict())
        
        return jsonify({"workItems": detailed_work_items})
    except Exception as e:
        return jsonify({"error": "Failed to fetch work items", "details": str(e)}), 500

@app.route("/all-work-items", methods=["GET"])
def get_work_item():
    return get_all_work_items()

if __name__ == "__main__":
    app.run(debug=True)

Both the get requests randomly give error 500 sometimes it works and gives me the correct response other times it gives me this error. error 500 VSC terminal

Same thing happens on postman with the local server url if I use the devops URL on postman which is this one https://dev.azure.com/preet442727/test/_apis/wit/workitems/1?api-version=7.1 it works and gives me the correct response every time but not the local server


Solution

  • Based the code snippet of your python app, I tested with the GET API in my sample hello-world app, it was working. (I added from flask import jsonify.)

    from datetime import datetime
    from flask import Flask, render_template, jsonify
    from . import app
    import os, json
    from flask_cors import CORS
    from azure.devops.connection import Connection
    from msrest.authentication import BasicAuthentication
    from azure.devops.v7_1.work_item_tracking.models import Wiql
    
    ORGANIZATION = "MyOrgName"  
    PROJECT = "TheProjectName"  
    PAT = "xxxxxx"
    credentials = BasicAuthentication('', PAT)
    connection = Connection(base_url=f"https://dev.azure.com/{ORGANIZATION}", creds=credentials)
    wit_client = connection.clients.get_work_item_tracking_client()
    
    @app.route("/work-items", methods=["GET"])
    def get_work_items():
        work_item_id = 1  
        work_item = wit_client.get_work_item(work_item_id)      
        try:
            # Get work item by ID
            work_item = wit_client.get_work_item(work_item_id)
            return jsonify(work_item.as_dict())
        except Exception as e:
            return jsonify({"error": "Failed to fetch work item", "details": str(e)}), 500
    
    @app.route("/")
    def home():
        return render_template("home.html")
    

    Image

    Image

    You may try with another script for test to help isolate if the issue was caused by the Azure DevOps API itself.

    import json
    from azure.devops.connection import Connection
    from msrest.authentication import BasicAuthentication
    from azure.devops.v7_1.work_item_tracking.models import Wiql
    
    ORGANIZATION = "MyOrgName"  
    PROJECT = "TheProjectName"  
    PAT = "xxxxxx"
    
    credentials = BasicAuthentication('', PAT)
    connection = Connection(base_url=f"https://dev.azure.com/{ORGANIZATION}", creds=credentials)
    wit_client = connection.clients.get_work_item_tracking_client()
    
    work_item_id = 1  
    work_item = wit_client.get_work_item(work_item_id)
    print(json.dumps(work_item.as_dict(), indent=4))
    

    If the issue was gone at the moment, it could be related to the Azure DevOps event.