How to return HTML file in HTTP Response (Azure-Functions)

Question:

I’m learning to use azure-functions and I want to know how can I return an HTML file on this piece of code. (the initial python code for azure-functions)

import logging

import azure.functions as func



def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    if name:
        return func.HttpResponse(f"Hello {name}!")
    else:
        return func.HttpResponse(
            "Please pass a name on the query string or in the request body",
            status_code=400
        )

What I want is something like:

return func.HttpResponse("index.html")

How can I do this?

Asked By: Am4teur

||

Answers:

Assumed that you are following the offical Quickstart tutorial Create an HTTP triggered function in Azure to learn Azure Function for Python, then you created a function named static-file to handle these static files in the path static-file or other path you want of MyFunctionProj like index.html, logo.jpg and so on.

Here is my sample code to do that as below.

import logging

import azure.functions as func
import mimetypes

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    if name:
        #return func.HttpResponse(f"Hello {name}!")
        path = 'static-file' # or other paths under `MyFunctionProj`
        filename = f"{path}/{name}"
        with open(filename, 'rb') as f:
            mimetype = mimetypes.guess_type(filename)
            return func.HttpResponse(f.read(), mimetype=mimetype[0])
    else:
        return func.HttpResponse(
             "Please pass a name on the query string or in the request body",
             status_code=400
        )

The result in browser as the figure below.

enter image description here

The file structure of my static-file api as below.

enter image description here

The content of the index.html file is as below.

<html>
<head></head>
<body>
<h3>Hello, world!</h3>
<img src="http://localhost:7071/api/static-file?name=logo.jpg"></img>
</body>
</html>

Note: for running on local, the index.html file will works fine to display logo.jpg. If deploy to Azure, you need to add the query parameter code to the end of property src of tag img, such as <img src="http://<your function name>.azurewebsites.net/api/static-file?name=logo.jpg&code=<your code for /api/static-file>"></img>.

Hope it helps.

Answered By: Peter Pan

The accepted answer no longer works. Now you need to use the context to find the correct folder. Something like the code below should work.

import logging
import azure.functions as func 
import mimetypes


def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
    logging.info('processed request for home funciton')
    # Returns /projectRoot/functionName/static/index.html
    filename = f"{context.function_directory}/static/index.html"
    
    with open(filename, 'rb') as f:
        mimetype = mimetypes.guess_type(filename)
        return func.HttpResponse(f.read(), mimetype=mimetype[0])
Answered By: jshen

I did simple, do not mind the content (uploading a file), it is not working that way 🙂

  if command:
        return func.HttpResponse(status_code=200,headers={'content-type':'text/html'}, 
        body=
"""<!DOCTYPE html>
<html>
<body>
   <form enctype = "multipart/form-data" action = "returnNameTrigger?save_file.py" method = "post">
   <p>File: <input type = "file" name = "filename" /></p>
   <p><input type = "submit" value = "Upload" /></p>
</form>
</body>
</html>
""")
Answered By: la_femme_it