AWS API Gateway and Python Lambda returning HTML

15,555

Solution 1

The <pre> tag you are seeing is the browser trying to show you the text returned from server. It is not part of the returned from the Lambda function.

To get it working you need to get the lambda function set the response HTTP header with Content-Type: 'text/html'

for example:

response = {
    "statusCode": 200,
    "body": content,
    "headers": {
        'Content-Type': 'text/html',
    }
}

Solution 2

You have to configure the API Gateway to return the proper Content-Type.

  1. From the API Gateway click on the API you created
  2. Click on "Method Response"
  3. Expand the row for Method response status 200. Click "Add Header" and add a "Content-Type" entry.
  4. Go back to the API you created by clicking "<- Method Execution"
  5. Click on "Integration Response"
  6. Expand the row for Method response status 200
  7. Click "Add mapping template"
  8. Type "text/html" without quotes for the Content-Type and click the checkbox button
  9. In the template area type the JsonPath that maps the part of the json returned from you lambda function to what is returned to the client. For example type $input.path('body') if your json is:

.

{
    "statusCode": 200,
    "body": "<html><body><h1>Test</h1></body></html>"
}
  1. Be sure to deploy the API before testing.

Here's a more detailed article on how to return html from AWS Lambda

Solution 3

try: response_body = "<HTML><Title>Title</Title></HTML>"

finally:

return {
    "statusCode": 200,
    "body": response_body,
    "headers": {
        'Content-Type': 'text/html',
    }
}

This just code illustration of David Lin answer

Share:
15,555
user2615236
Author by

user2615236

Updated on June 12, 2022

Comments

  • user2615236
    user2615236 almost 2 years

    I'm trying to return a webpage from my python lambda ftn, using API GW. Instead, I'm getting my page embeded in a tag within the body, instead of the return value being the full page ( header, body, etc... without the pre>

    Any suggestions what I might be doing wrong

    Thanks

  • Sanjiv
    Sanjiv over 4 years
    Windsch: the above link in node.js. Is there any way to render HTML page using AWS Lambda function in PYTHON