How to Add an API Key to a Webhook and Verify it with Python?

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

I wanted to add an API Key to my webhook. I configured the webhook for a custom response. Then I used a Python code block to do a check for the key and the method, as I only use POST in my case. Note the API key is unique to this posted example and not from actual code. The Python then configures the response to the webhook. Processing of any action based on this webhook could occur within this Python code block or steps after it.

ALLOWED_API_KEYS = {
    "1111-1111-1111-1111-111111111111": "Dev"
}

def handler(pd: "pipedream"):
    response = {
        'status': 401,
        'body': 'API key missing'
    }

    user = ''
    api_key = pd.steps["trigger"]["event"]["headers"].get("x-api-key")

    if api_key is None:
        pd.respond(response)
        pd.flow.exit('API key missing')
        return

    if api_key in ALLOWED_API_KEYS:
        if pd.steps["trigger"]["event"]["method"] != 'POST':
            response['status'] = 405
            response['body'] = 'Only POST method is allowed'
            pd.respond(response)
            pd.flow.exit('Method Not Allowed')

        if "application/json" not in pd.steps["trigger"]["event"]["headers"].get("content-type", ""):
            response['status'] = 400
            response['body'] = 'Missing or invalid request body'
            pd.respond(response)
            pd.flow.exit('Bad Request')

        response['status'] = 200
        response['body'] = ''
        user = ALLOWED_API_KEYS[api_key]
        pd.respond(response)
    else:
        response['status'] = 403
        response['body'] = 'Unauthorized'
        pd.respond(response)
        pd.flow.exit('Unauthorized')

    return {'user': user}

this is a great pattern, thanks for sharing. Hoping we can make this easier in the product, e.g. these could be settings on the HTTP trigger you could enforce

true, true.