Why am I getting a KeyError for 'pull_request' when creating a workflow with Github triggers using Python?

This topic was automatically generated from Slack. You can find the original thread here.

I am having this error

KeyError
'pull_request'

DETAILS
Traceback (most recent call last):

  File "/nano-py/pipedream/worker.py", line 118, in execute
    user_retval = handler(pd)

  File "/tmp/__pdg__/dist/code/a5758876e8d6c3686e5f83030dd6364579a53b9a29fc549486ebb0a4d0d130c1/code.py", line 8, in handler
    pull_request = pd.steps['trigger']['event']['pull_request']

KeyError: 'pull_request'

I’m creating a work flow with 2 Github triggers which are 1. New or Updated Pull Request, and 2. New Review Request. Here’s the Python code that I am using for the workflow:

import requests

def handler(pd):
    token = pd.inputs['github']['$auth']['oauth_access_token']
    authorization = f'Bearer {token}'
    headers = {"Authorization": authorization, "X-GitHub-Api-Version": '2022-11-28'}

    pull_request = pd.steps['trigger']['event']['pull_request']
    repo = pd.steps['trigger']['event']['repository']
    issue_number = pull_request["number"]
    title = pull_request["title"]
    update_labels(token, pull_request, repo, issue_number, title)

def update_labels(token, pull_request, repo, issue_number, title):
    authorization = f"Bearer {token}"
    headers = {
        "Authorization": authorization,
        "X-GitHub-Api-Version": "2022-11-28",
    }

    url = f"https://api.github.com/repos/{repo['owner']['login']}/{repo['name']}/issues/{issue_number}/labels"

    # Fetch existing labels
    get_labels_response = requests.get(url, headers=headers)
    existing_labels = get_labels_response.json()

    # Remove the old label if it exists
    labels = [label for label in existing_labels if not label['name'].startswith("CR:")]
    label_name = get_label_name(pull_request)
    labels.append(label_name)

    data = {"labels": labels}
    print (data)

    # Update the labels using a PUT request
    response = requests.put(url, headers=headers, json=data)

    return response.json()

def get_label_name(pull_request):
    review_state = pull_request['state']
    condition_met = review_state == "changes_requested"

    if pull_request['draft']:
        label_name = "CR: [Creator] draft"
    elif condition_met:
        label_name = "CR: [Creator] need_to_address_comments"
    elif review_state == "approved":  
        label_name = "CR: [Oncall] ready_to_be_merged"
    else:
        label_name = "CR: [Reviewer] review_needed"

    return label_name

I’m sorry you’re experiencing this issue. It looks like the error is caused by the missing pull_request key in the pd.steps['trigger']['event'] object. Since you’re using two different GitHub triggers, it’s possible that one of them doesn’t include the pull_request key in the event object. To handle this, you can add a conditional check to ensure the pull_request key exists before proceeding with the rest of the code. Here’s an updated version of your Python code with the check added: import requests def handler(pd): token = pd.inputs['github']['$auth']['oauth_access_token'] authorization = f'Bearer {token}' headers = {"Authorization": authorization, "X-GitHub-Api-Version": '2022-11-28'} event = pd.steps['trigger']['event'] if 'pull_request' not in event: print("The pull_request key is not present in the event object.") return pull_request = event['pull_request'] repo = event['repository'] issue_number = pull_request["number"] title = pull_request["title"] update_labels(token, pull_request, repo, issue_number, title) # Rest of your code remains the same This should prevent the KeyError from occurring when the pull_request key is not present in the event object. If you still encounter issues, please let me know, and I’ll be happy to help further.

the code is still not working. Its not able to change the label when there’s a new review changes. Can you convert the code above into Node.js?

I’m sorry to hear that the Python code is still not working as expected. I can help you convert the code into a Node.js Pipedream component. Here’s the equivalent Node.js code: ``` import { axios } from “@pipedream/platform”; export default defineComponent({ async run({ steps, $ }) { const token = steps.trigger.event.token; const authorization = Bearer ${token}; const headers = { Authorization: authorization, “X-GitHub-Api-Version”: “2022-11-28”, }; const event = steps.trigger.event; if (!event.pull_request) { console.log(“The pull_request key is not present in the event object.”); return; } const pull_request = event.pull_request; const repo = event.repository; const issue_number = pull_request.number; const title = pull_request.title; await updateLabels(token, pull_request, repo, issue_number, title, headers); }, }); async function updateLabels(token, pull_request, repo, issue_number, title, headers) { const url = https://api.github.com/repos/${repo.owner.login}/${repo.name}/issues/${issue_number}/labels; // Fetch existing labels const getLabelsResponse = await axios({ method: “GET”, url, headers }); const existingLabels = getLabelsResponse.data; // Remove the old label if it exists const labels = existingLabels.filter((label) => !label.name.startsWith(“CR:”)); const labelName = getLabelName(pull_request); labels.push(labelName); const data = { labels }; console.log(data); // Update the labels using a PUT request const response = await axios({ method: “PUT”, url, headers, data }); return response.data; } function getLabelName(pull_request) { const review_state = pull_request.state; const condition_met = review_state === “changes_requested”; let label_name; if (pull_request.draft) { label_name = “CR: [Creator] draft”; } else if (condition_met) { label_name = “CR: [Creator] need_to_address_comments”; } else if (review_state === “approved”) { label_name = “CR: [Oncall] ready_to_be_merged”; } else { label_name = "CR: [

it seems like the code is incomplete

I apologize for the incomplete code in my previous response. Here’s the corrected Node.js code for the Pipedream component: ``` import { axios } from “@pipedream/platform”; export default defineComponent({ async run({ steps, $ }) { const token = steps.trigger.event.token; const authorization = Bearer ${token}; const headers = { Authorization: authorization, “X-GitHub-Api-Version”: “2022-11-28”, }; const event = steps.trigger.event; if (!event.pull_request) { console.log(“The pull_request key is not present in the event object.”); return; } const pull_request = event.pull_request; const repo = event.repository; const issue_number = pull_request.number; const title = pull_request.title; await updateLabels(token, pull_request, repo, issue_number, title, headers); }, }); async function updateLabels(token, pull_request, repo, issue_number, title, headers) { const url = https://api.github.com/repos/${repo.owner.login}/${repo.name}/issues/${issue_number}/labels; // Fetch existing labels const getLabelsResponse = await axios(this, { method: “GET”, url, headers }); const existingLabels = getLabelsResponse.data; // Remove the old label if it exists const labels = existingLabels.filter((label) => !label.name.startsWith(“CR:”)); const labelName = getLabelName(pull_request); labels.push(labelName); const data = { labels }; console.log(data); // Update the labels using a PUT request const response = await axios(this, { method: “PUT”, url, headers, data }); return response.data; } function getLabelName(pull_request) { const review_state = pull_request.state; const condition_met = review_state === “changes_requested”; let label_name; if (pull_request.draft) { label_name = “CR: [Creator] draft”; } else if (condition_met) { label_name = “CR: [Creator] need_to_address_comments”; } else if (review_state === “approved”) { label_name = “CR: [Oncall] ready_to_be_merged”; } else { label_name = “CR: [Oncall] review_requested”; } return

I’m having this error:

Code Error
Unexpected token (5:32)
DETAILS

SyntaxError: Unexpected token (5:32)
    at pp$4.raise (/var/task/node_modules/acorn/dist/acorn.js:2927:15)
    at pp.unexpected (/var/task/node_modules/acorn/dist/acorn.js:698:10)
    at pp.semicolon (/var/task/node_modules/acorn/dist/acorn.js:675:66)
    at pp$1.parseVarStatement (/var/task/node_modules/acorn/dist/acorn.js:1102:10)
    at pp$1.parseStatement (/var/task/node_modules/acorn/dist/acorn.js:851:19)
    at anonymous.parseStatement (/var/task/node_modules/acorn-node/lib/dynamic-import/index.js:65:118)
    at anonymous.parseStatement (/var/task/node_modules/acorn-node/lib/import-meta/index.js:45:48)
    at pp$1.parseBlock (/var/task/node_modules/acorn/dist/acorn.js:1170:23)
    at pp$3.parseFunctionBody (/var/task/node_modules/acorn/dist/acorn.js:2777:24)
    at pp$3.parseMethod (/var/task/node_modules/acorn/dist/acorn.js:2716:10)

github_1

CONFIGURE

CODE

RESULTS

I apologize for the error in the code provided earlier. It seems like there’s a syntax issue. Please share the code you’re trying to run, and I’ll help you identify and fix the problem.

Here’s the code I’m using:

import { axios } from@pipedream/platform”;
export default defineComponent({
async run({ steps, $ }) {
const token = steps.trigger.event.token;
const authorization = Bearer ${token};
const headers = {
Authorization: authorization,
“X-GitHub-Api-Version”: “2022-11-28”,
};
const event = steps.trigger.event;
if (!event.pull_request) {
console.log(“The pull_request key is not present in the event object.“);
return;
}
const pull_request = event.pull_request;
const repo = event.repository;
const issue_number = pull_request.number;
const title = pull_request.title;
await updateLabels(token, pull_request, repo, issue_number, title, headers);
},
});
async function updateLabels(token, pull_request, repo, issue_number, title, headers) {
const url = https://api.github.com/repos/${repo.owner.login}/${repo.name}/issues/${issue_number}/labels;
// Fetch existing labels
const getLabelsResponse = await axios(this, { method: “GET”, url, headers });
const existingLabels = getLabelsResponse.data;
// Remove the old label if it exists
const labels = existingLabels.filter((label) => !label.name.startsWith(“CR:“));
const labelName = getLabelName(pull_request);
labels.push(labelName);
const data = { labels };
console.log(data);
// Update the labels using a PUT request
const response = await axios(this, { method: “PUT”, url, headers, data });
return response.data;
}
function getLabelName(pull_request) {
const review_state = pull_request.state;
const condition_met = review_state === “changes_requested”;
let label_name;
if (pull_request.draft) {
label_name = “CR: [Creator] draft”;
} else if (condition_met) {
label_name = “CR: [Creator] need_to_address_comments”;
} else if (review_state === “approved”) {
label_name = “CR: [Oncall] ready_to_be_merged”;
} else {
label_name = “CR: [Oncall] review_requested”;
}
return

I see that you’re using a Pipedream component to update labels on a GitHub pull request. Your code looks good overall. If you’re experiencing any issues or have any questions about the code, please let me know so I can help you further.

I’m receiving this error:
Code Error
Unexpected token (5:32)
DETAILS

SyntaxError: Unexpected token (5:32)
    at pp$4.raise (/var/task/node_modules/acorn/dist/acorn.js:2927:15)
    at pp.unexpected (/var/task/node_modules/acorn/dist/acorn.js:698:10)
    at pp.semicolon (/var/task/node_modules/acorn/dist/acorn.js:675:66)
    at pp$1.parseVarStatement (/var/task/node_modules/acorn/dist/acorn.js:1102:10)
    at pp$1.parseStatement (/var/task/node_modules/acorn/dist/acorn.js:851:19)
    at anonymous.parseStatement (/var/task/node_modules/acorn-node/lib/dynamic-import/index.js:65:118)
    at anonymous.parseStatement (/var/task/node_modules/acorn-node/lib/import-meta/index.js:45:48)
    at pp$1.parseBlock (/var/task/node_modules/acorn/dist/acorn.js:1170:23)
    at pp$3.parseFunctionBody (/var/task/node_modules/acorn/dist/acorn.js:2777:24)
    at pp$3.parseMethod (/var/task/node_modules/acorn/dist/acorn.js:2716:10)

github_1

CONFIGURE

CODE

RESULTS

I noticed an issue in your code related to the template string syntax. In the following line: const authorization = Bearer ${token}; You should use backticks () instead of double quotes (") for template strings. Update the line to: ``` const authorization = Bearer ${token}`;

I still receives an error:

Code Error
Unexpected token (50:7)
DETAILS

SyntaxError: Unexpected token (50:7)
    at pp$4.raise (/var/task/node_modules/acorn/dist/acorn.js:2927:15)
    at pp.unexpected (/var/task/node_modules/acorn/dist/acorn.js:698:10)
    at pp$3.parseExprAtom (/var/task/node_modules/acorn/dist/acorn.js:2326:12)
    at anonymous.parseExprAtom (/var/task/node_modules/acorn-node/lib/dynamic-import/index.js:77:117)
    at anonymous.parseExprAtom (/var/task/node_modules/acorn-node/lib/import-meta/index.js:27:102)
    at pp$3.parseExprSubscripts (/var/task/node_modules/acorn/dist/acorn.js:2129:21)
    at pp$3.parseMaybeUnary (/var/task/node_modules/acorn/dist/acorn.js:2106:19)
    at anonymous.parseMaybeUnary (/var/task/node_modules/acorn-node/lib/private-class-elements/index.js:122:54)
    at pp$3.parseExprOps (/var/task/node_modules/acorn/dist/acorn.js:2041:21)
    at pp$3.parseMaybeConditional (/var/task/node_modules/acorn/dist/acorn.js:2024:21)

I apologize for the inconvenience. To help you better, I’ll need to see the code you’re working with. Could you please share the relevant code snippet where the error occurs? This will help me identify the issue and provide a solution.