Quadgnim
Quadgnim

Reputation: 551

AWS API Gateway and Python Lambda returning HTML

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

Upvotes: 18

Views: 27949

Answers (3)

C.J. Windisch
C.J. Windisch

Reputation: 309

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

Upvotes: 9

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

Upvotes: 8

David Lin
David Lin

Reputation: 13353

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',
    }
}

Upvotes: 36

Related Questions