3

I currently have a Python lambda function that is returning a JSON object. However rather then getting a white screen with JSON data I was wondering if there is a way to return a html webpage that returns instead of JSON? Currently the return data looks like

 return {
'statusCode': 200,
'headers': {},
'body': json.dumps({ 

                    'HOW-TO: ': prompt,    
                    'instanceId': instanceId,
                    'PUBLIC_IP_ADDRESS': publicIp,
                       'instanceRegion':Instance_region
})

But was curious if there is a way to return an HTML page instead?

jelidens
  • 221
  • 1
  • 4
  • 14

2 Answers2

6

Yes you can, just define with AWS Python the right headers

"headers": {'Content-Type': 'text/html'}

as in the following example (please adjust the right Python identations)

def lambda_handler(event, context):

import json

longinformation = '''
<h1 style="color: #5e9ca0;">You can edit <span style="color: #2b2301;">this demo</span> text!</h1>
<h2 style="color: #2e6c80;">How to send HTML with AWS lambda in Python:</h2>
<p>Paste your documents in the visual editor on the left or your HTML code in the source editor in the right. <br />Edit any of the two areas and see the other changing in real time.&nbsp;</p>
'''

return {
    "statusCode": 200,
    "headers": {'Content-Type': 'text/html'},   #it really works by Hector Duran!
    "body": longinformation
}
2

Of course you can. The default content returned from a Lambda function is an arbitrary string. You can return a JSON object, or HTML, or pretty much any text you'd like. There is also a way, using the CLI to set the content type to be binary instead of text but that is not of consequence to your question.

To return HTML, simply change your return statement to return the HTML markup.

You do have to generate the HTML markup which is quite a different question altogether. If you are looking for an HTML markup generator for Python, as opposed to generating by hand, you might consider a library such as: Yattag, or Karrigell or even better a templating system such as Jinja or Mako

Mike Dinescu
  • 54,171
  • 16
  • 118
  • 151
  • The asker is not talking about returning HTML code alone but returning it so the browser will actually render it as HTML. See @HECTOR's answer. – Adam Grant Oct 11 '21 at 18:14