JiraAPI Oauth2.0 app jql issue

Username
I'm New Here
I'm New Here
Those new to the Atlassian Community have posted less than three times. Give them a warm welcome!
November 27, 2024

In this code when i create webhook for issue then it gets triggered when issue is updated but when i create child issues in it webhook doesn't trigger. This an OAuth2.0 app is there some other way?

 

 

        # Create JQL filter specific to the issue
        jql_filter = f'project = "{project_key}" AND issuekey = "{issue_key}"'

        webhook_url = Config.WEBHOOK_URL
        # Prepare the payload
        data = {
            "url": webhook_url,
            "webhooks":[
                {
                "events": [
                    "jira:issue_created",
                    "jira:issue_updated"
                ],
                "jqlFilter": jql_filter,
                "enabled": True
                }
            ]
        }

1 answer

0 votes
Humashankar VJ
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
November 28, 2024

Hi @Username 

By including the jira:subtask_created event and modifying the JQL filter to include child issues, you can ensure that the webhook triggers when sub-tasks are created under the specified parent issue.

This approach should work as expected and cover your requirements for monitoring child issues.

Ensure Jira API token and event names are accurate

python

import requests

import json

# Create JQL filter specific to the issue

project_key = "YOUR_PROJECT_KEY"

issue_key = "YOUR_ISSUE_KEY"

jql_filter = f'project = "{project_key}" AND (issuekey = "{issue_key}" OR parent = "{issue_key}")'

webhook_url = "YOUR_WEBHOOK_URL"

# Prepare the payload

data = {

"url": webhook_url,

"webhooks": [

{

"events": [

"jira:issue_created",

"jira:issue_updated",

"jira:subtask_created" # Listen for sub-task creation

],

"jqlFilter": jql_filter,

"enabled": True

}

]

}

# Authentication headers (assuming OAuth 2.0 token)

headers = {

"Authorization": f"Bearer YOUR_OAUTH_TOKEN",

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

"Accept": "application/json"

}

# Jira API endpoint for creating webhooks

jira_webhook_url = f"https://your-jira-instance.atlassian.net/rest/api/3/webhook"

# Send the POST request to create the webhook

response = requests.post(jira_webhook_url, headers=headers, data=json.dumps(data))

if response.status_code == 201:

print("Webhook created successfully.")

else:

print(f"Failed to create webhook. Status code: {response.status_code}")

print(response.text)

 

Hope this helps - Happy to help further!!
Thank you very much and have a great one!
Warm regards

Username
I'm New Here
I'm New Here
Those new to the Atlassian Community have posted less than three times. Give them a warm welcome!
November 28, 2024

because of jql limitation in jira API I am unable to use parent clause and subtask_created event because both of them gives error stating parent clause unsupported and invalid subtask_created event

this is the full code ->

 

    @staticmethod
    def add_issue_webhook(project_key, issue_key):
        user_id = session.get('user_id')
        if not user_id:
            return ('Not authenticated'), 401

        user_token = UserToken.query.filter_by(user_id=user_id).first()
        if not user_token:
            return ('No tokens found for the authenticated user'), 400

        access_token = user_token.access_token

        headers = {
            'Authorization': f'Bearer {access_token}',
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        }

        # Get cloud_id
        resources_response = requests.get(resources_url, headers=headers)

        if resources_response.status_code != 200:
            return ('Failed to fetch accessible resources.', resources_response.text), resources_response.status_code

        try:
            resources = resources_response.json()
        except ValueError:
            return ('Failed to parse resources response as JSON', resources_response.text), resources_response.status_code

        if not resources:
            return ('No accessible resources found for the user.'), 404

        cloud_id = resources[0].get('id')
        if not cloud_id:
            return ('Could not determine cloud_id from accessible resources.'), 400

        base_api_url = f"https://api.atlassian.com/ex/jira/{cloud_id}/rest/api/2"

        # Validate the project and issue
        project_url = f"{base_api_url}/project/{project_key}"
        project_response = requests.get(project_url, headers=headers)

        if project_response.status_code != 200:
            return ('Invalid project key. No project found with the given key'), 404

        # Validate the specific issue
        issue_url = f"{base_api_url}/issue/{issue_key}"
        issue_response = requests.get(issue_url, headers=headers)

        if issue_response.status_code != 200:
            return ('Invalid issue key. No issue found with the given key in the project'), 404

        # Check if a webhook already exists for this target and user
        existing_webhook = WebhookInfo.query.filter_by(
            user_id=user_id,
            target_id=project_key,
            target_issue_key=issue_key
        ).first()
        if existing_webhook:
            return ('Webhook already exists for the given project and issue'), 400

        # Create JQL filter specific to the issue
        jql_filter = f'project = "{project_key}" AND issuekey = "{issue_key}"'

        webhook_url = Config.WEBHOOK_URL
        # Prepare the payload
        data = {
            "url": webhook_url,
            "webhooks":[
                {
                "events": [
                    "jira:issue_created",
                    "jira:issue_updated"
                ],
                "jqlFilter": jql_filter,
                "enabled": True
                }
            ]
        }
        create_webhook_url = f"{base_api_url}/webhook"
       
        # Send the request to create the webhook
        response = requests.post(create_webhook_url, headers=headers, json=data)
       
        if response.status_code not in [200, 201]:
            try:
                error_details = response.json()
            except ValueError:
                error_details = response.text
            return ('Failed to create webhook', error_details), response.status_code

        try:
            response_data = response.json()
        except ValueError:
            return ('Failed to parse webhook creation response as JSON', response.text), response.status_code

        webhook_results = response_data.get('webhookRegistrationResult', [])
        print(response_data)
        if webhook_results:
            webhook_id = webhook_results[0].get('createdWebhookId')
        else:
            webhook_id = None

        if not webhook_id:
            return ('No webhook id returned'), 500

        # Store webhook information in the database
        webhook_info = WebhookInfo(
            user_id=user_id,
            target_id=project_key,
            webhook_id=webhook_id,
            target_type='issue',
            target_issue_key=issue_key
        )
        db.session.add(webhook_info)
        db.session.commit()
        logging.info(f"WebhookInfo added for issue: {webhook_info}")
        return ('Webhook created successfully for specific issue', webhook_id), 201
Like Humashankar VJ likes this
Humashankar VJ
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
November 28, 2024

Thanks for insight,

To overcome the limitations of Jira's JQL and webhook events, you can utilize Jira Automation to monitor subtask creation and trigger external webhooks.

This can be achieved by creating an automation rule in Jira, which involves setting a trigger for issue creation, a condition to specify that the issue type is a subtask, and an action to call your external webhook.

Otherwise, you can leverage Jira's Automation API to dynamically create these rules, particularly useful when dealing with multiple parent issues.

Regards

Suggest an answer

Log in or Sign up to answer
DEPLOYMENT TYPE
CLOUD
PRODUCT PLAN
FREE
PERMISSIONS LEVEL
Product Admin
TAGS
AUG Leaders

Atlassian Community Events