0

I am trying to have an external api (servicenow attachment api) that you send a file to that attaches to a record in servicenow be through AWS API Gateway and AWS Lambda. I have set the binary media in the gateway to /. I have set up the post endpoint. And I pasted snippet of lambda below.

But I am getting a UnicodeDecodeError: 'utf-8' codec can't decode byte...

I was looking for what might be causing this and possible solutions, I'm thinking it's something with how I'm parsing the event body. I'm trying to test the endpoint through postman, have tried binary and form-data body content-types with no luck

Have a function for the b64 encoding

def _parse_event_body(event):
    """Decode event body from either base64 or json string
    """
    body_str = event["body"]
    if not isinstance(body_str, str):
        return None, Exception("Body not a string")

    try:
        body = base64.urlsafe_b64decode(body_str).decode()

    except (TypeError, binascii.Error) as _:
        body = None

    if not body:
        # try to parse json string (happens when body isn't encoded)
        body = body_str

    try:
        body = json.loads(body)
    except (JSONDecodeError, TypeError) as err:
        return None, err

    return body, None

Then just a regular post

body, err = _parse_event_body(event)
# Set the headers from the lambda proxy event
dest_headers = event['headers']

response = s.post(
                url=parsed_url,
                headers=dest_headers,
                data=body,
                timeout=REQUEST_TIMEOUT,
                verify=False
gxtra
  • 11
  • 2

0 Answers0