17

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

Quadgnim
  • 531
  • 1
  • 6
  • 11
  • forgot to mention, running "TEST" works and returns 3DMUVE test but actually hitting the page with the url https:// {my api} .execute-api.us-east-1.amazonaws.com/prod/api/v1/mobs/test results in
    3DMUVE
    test
    
    – Quadgnim Dec 04 '16 at 20:31
  • I guess two things: 1. are you sending the right Accept header and/or Content-Type header to the API and back from the Lambda function? 2. Did you deploy the latest changes to the API? – jackko Dec 06 '16 at 00:11

3 Answers3

35

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',
    }
}
David Lin
  • 13,168
  • 5
  • 46
  • 46
9

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

Dante Falzone
  • 111
  • 1
  • 3
  • 16
C.J. Windisch
  • 191
  • 1
  • 4
  • Windsch: the above link in node.js. `Is there any way to render HTML page using AWS Lambda function in PYTHON` – Sanjiv Oct 21 '19 at 05:03
8

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

Prakash Pazhanisamy
  • 997
  • 1
  • 15
  • 25