In this post I’m going to answer a question someone asked me recently when I presented an Introduction to Azure Functions – can we return JSON from the HttpTrigger function? The answer is yes and it’s not limited to the Http trigger function and I’ll walk you through one of many ways to do this.
First let’s start off by taking a look at the output that shows up by default from the HttpTrigger Function I had created in the Azure portal. As you can see the default output is XML as shown here:
The same goes for the response when the require “name” parameter is missing in the query string or the body of the request:
You might think that there is a simple property in the Azure Function properties to configure the output, but there isn’t, at least at this point in time with version 1 runtime.
Creating a C# Http Trigger Function
Let’s quickly create an Azure Function in the portal and I can show you one of many ways to return JSON from your Azure Function.
1. Create a new Serverless Function App:
2. Once your Azure Function app is running, create a new C# Http trigger function and then provide it a name and authentication model:
3. Now that your function is created you will see the following code in the run.csx file. If you run it you will get XML as your response, so let’s go ahead and update this function to return JSON.
Changing the return type to JSON
For this example I’ll import Newtonsoft.Json package and then serialize a simple object to return back when the function is called.
1. Add Newtonsoft.Json package and other using references:
2. Update function code to use Newtonsoft.Json. Looking at the following code you will see that I’ve created a simple POCO object which is what I’ll be returning from the function. I then changed the response to return a serialized string in UTF8 encoding and application/response:
3. Now when we run the function through either the browser or Postman we’ll see the response in JSON format. Here is what we would see in Postman:
and then in a browser we would see this:
Azure Functions is a powerful component in Azure serverless offering and as you can see your not limited to XML as the only response format.
Let me know if you have any questions and I’d be happy to investigate and follow up.