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:

image

The same goes for the response when the require “name” parameter is missing in the query string or the body of the request:

image

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:

image

image

2. Once your Azure Function app is running, create a new C# Http trigger function and then provide it a name and authentication model:

image

image

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.

image

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:

image

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:

image

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:

image

and then in a browser we would see this:

image

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.

Enjoy!

Posted by Callon Campbell

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s