Azure Functions: Return content as HTML
Even though Azure Functions is mainly used to serve APIs and return JSON objects, it can also be used to help HTML content.
In this article, we will see how we can achieve that. But just before we dive into the technical details, let's discuss why we would like to do that:
Sometimes, you want your API to return a "visually attractive" data version.
Let's say you're building a tool for handling your bookmarks across devices (think of "Pocket"). You can add a page to your bookmark list through an API call.
But what if you would like to list all your saved bookmarks? You'd prefer a pretty UI for that, don't you? Of course, you could create a web application-specific for that matter and host it in some other service (e.g., an App Service Web App or a Static Web App), or you could add a function to your Functions App that returns that list in HTML (and, why not, add some CSS to it).
Now that we understand the use case, let's see how we can return HTML content from Azure Functions.
Let's first create a Functions App targeting .NET Core 3.1 as a stack and create a new function using the "HTTP trigger" template:
Then, let's replace the demo code with this:
Now, let's run the application, and voilà!
The HTML content presented here is essential, but it illustrates the point. Our code could have dynamically constructed the HTML to be returned to serve our application's purpose better.