In this Azure tutorial, we will discuss Azure Function HTTP Trigger.
Table of Contents
- Azure Function HTTP Trigger
- Create An HTTP Trigger Azure Function Using Visual Studio 2019
- Deploy An HTTP Trigger Azure Function from Visual Studio 2019
- Azure Function HTTP Trigger Route
- HTTP triggered Azure Functions Default Routing
- How to change the Azure Function Route Prefix With host.json
- Azure Function Remove API From Route
- Define the Route in the Azure Function Header
- Azure Functions HTTP Trigger Route Parameters
- How To Make Azure Function Route Parameters Optional
- Azure Function Route Wildcard
- Azure Function HTTP Trigger Query Parameters
Azure Function HTTP Trigger
Azure Function is an Azure Service from Microsoft that helps you to run some pieces of code smoothly without getting worried about the infrastructure for your application. Check out some more information on Azure Function before starting with the Azure Function HTTP Trigger.
- How Much Memory Available For Azure Functions
- Where To Instantiate Database Connection In Azure Functions
The main work of the Azure Function HTTP Trigger is to invoke the Azure Function with the HTTP Request. HTTP Trigger is the basic and simplest trigger of an Azure Function. Mostly, People use the HTTP Trigger while performing the operation with the Azure Function.
Basically, there are two response codes that HTTP Triggered functions to return
- It returns the response code as HTTP 204 if there is no content.
- It returns the response code as HTTP 200 OK in case everything is ok and the Successful execution of the Azure Function.
The HttpTrigger attribute is available in the case of C# language, Java, etc, to configure your Azure Function.
To execute the HTTP-triggered Azure function, you need to specify the authorization types. If you are running the Azure Function locally, in that case, the authorization attribute will be ignored. Once you publish your Azure Function into the Azure cloud then the authorization will work. There are a few authorization types available below
- Function: This is the default authorization type option available. This is the key-based authorization type. A function-specific API key is required for this authorization type.
- Anonymous: There is no restriction, anyone can access and No API key is needed for the Anonymous Authorization type.
- Admin: For the Admin authorization type, the master key is required to access the Azure function.
You can provide the HTTP-triggered Azure function parameter value along with the query string in the function URL or in the Body in a JSON format.
When you create an HTTP-triggered Azure function, by default, the URL of the function is in the below format
http://<APP_NAME>.azurewebsites.net/api/<FUNCTION_NAME>
One of the Examples for an HTTP triggered Azure function URL with the authorization type as Function is as below
https://mydemoazurefunction1220200810210756.azurewebsites.net/api/Function1?code=CNZkNlmz3xpQRhgu7DIKcRiMiTtLv7bTOvhcip82GdfCkormbvCqjw==
Below is the example of an HTTP-triggered Azure function function.json file
{
"bindings": [
{
"authLevel": "function",
"name": "req",
"type": "httpTrigger",
"direction": "in",
"methods": [
"get",
"post"
]
},
{
"name": "$return",
"type": "http",
"direction": "out"
}
]
}
If we discuss a little bit on the above function.json file,
type: The type property is required to mention, and the value will be httpTrigger.
direction: The property direction is also required, and the value must be set to in.
name: The property name is required and needs to mention the variable name in the code for the Azure function. authLevel: The property authLevel needs to specify the authorization level for the Azure function. You can provide the auth level property value as Function, Anonymous, or Admin. The default option is Function.
methods: You can specify the HTTP methods to which the Azure Function responds. If you do not mention any specific method, then your Azure function will respond to all the HTTP methods available. This is about the Azure function HTTP trigger authentication.
Let’s create an Azure Function HTTP Trigger using Visual Studio 2019
Create An HTTP Trigger Azure Function Using Visual Studio 2019
Well, let’s create an HTTP-triggered Azure Function using Visual Studio 2019. Follow the below steps to create the Azure function.
1. The first step is to open Visual Studio 2019.
2. Once the Visual Studio is loaded successfully, Now you need to click on the Create a new Project button from the Get Started window.
3. On the Create a new project window, Now search for the Azure Functions template, choose the Azure Functions and then click on the Next button to go to the next screen.
4. Enter your Project name, and choose a location where you want to save the Azure function project. On the Configure Your New Project window, click on the Create button.
5. We need to choose the trigger for our Azure Function, so choose the Http trigger as the trigger option. For the Storage Account (AzureWebJobsStorage) option, select the Storage Emulator option and Choose the Authorization level option as Anonymous On the Create a new Azure Functions Application window. Now click the Create button to create the HTTP-triggered Azure function, as shown below.
Now, you can see the project was created successfully.
Now, if you can see the local.settings.json file, it contains the below code with a key-value pair for the Azure Storage connection string to access the Azure storage account.
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet"
}
}
Now, you will open the Function1.cs file and see it contains our HTTP-triggered Azure Function. I am renaming the function from Function1 to HTTPAzureFunction
public static class Function1
{
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string name = req.Query["name"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
string responseMessage = string.IsNullOrEmpty(name)
? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
: $"Hello, {name}. This HTTP triggered function executed successfully.";
return new OkObjectResult(responseMessage);
}
}
Now our Azure function HTTP Trigger is ready. Let’s run the function to check if it is working as expected. Press F5 to run the project. You can see the project ran successfully without any issues and provided us with the Http Azure Function URL to access the function.
The URL is like below
http://localhost:7071/api/HTTPAzureFunction
Now, to check if the function is working fine, To check copy that URL, paste it into the Browser, and press enter
Now we can see the default message it is showing. It is expecting a value for the name parameter in the query string. Let’s provide that. So now append ?name=Azure and press enter. You can able to see it provides the output as expected.
Let’s check the function URL in the Postman app and see if it is working as expected. You can see below it executed the function URL successfully.
Deploy An HTTP Trigger Azure Function from Visual Studio 2019
You can deploy the HTTP trigger Azure function from Visual Studio 2019. You can check to Deploy an HTTP Trigger Azure Function from Visual Studio 2019 to Azure. You can check Deploying the Azure Function using Visual Studio 2019 section for the detailed steps.
Azure Function HTTP Trigger Route
Well, here we will discuss the HTTP-triggered Azure Functions Routing options. Before that, We should know What is routing?
Routing refers to how an application responds to the user request to an endpoint address with the particular HTTP request method like “GET” and “POST”, etc. In the case of Azure Functions, the route says, with the help of the Azure function URL, that which function will react as per your HTTP request. Finally, routing is all about the endpoint or the application URL.
HTTP triggered Azure Functions Default Routing
If we consider the above function, we have created a named HTTPAzureFunction.By running that function locally, you can see that the default URL generated to access the function is http://localhost:7071/api/HTTPAzureFunction. If you closely look at the function URL, you can see that the URL comprises a route prefix of /API/, then the actual name of your function, in my case is HTTPAzureFunction.
So, this is the default URL to access the HTTPAzureFunction. Now if we are accessing the URL with the value of a parameter as a query string with the function URL. You will get the expected output below
How to change the Azure Function Route Prefix With host.json
We can change the default routing of /API/ for the HTTP-triggered Azure Function with the help of a few modifications on the host.json file in your project. You can find the host.json file in your solution. Open that file, make the changes, and save it.
{
"version": "2.0",
"extensions": {
"http": {
"routePrefix": "Name"
}
}
}
Your host.json file should look exactly like the one below.
After the host.json file modification, if you run the Azure Function project again, you can see the URL is changed now. Earlier, before changing the host.json file, the function URL was http://localhost:7071/api/HTTPAzureFunction, and now, after the modification, the Function URL is http://localhost:7071/Name/HTTPAzureFunction. See below.
Now, let’s open the new URL in the Browser and see if it works fine. You can able to see it is working as expected.
Azure Function Remove API From Route
If you want to remove the route prefix altogether from the function URL, then you need to modify the host.json file like below
{
"version": "2.0",
"extensions": {
"http": {
"routePrefix": ""
}
}
}
Now your host.json file should be like the below
If you run the Project again after the above modification, you can see the URL changed now.
Now the URL is http://localhost:7071/HTTPAzureFunction
Now, let’s open the new URL in the Browser and see if it works fine. You can able to see it is working as expected.
Define the Route in the Azure Function Header
You can also define the Route in the Azure Function header like below. Now URL will be like http://localhost:7071/api/GetNameVal
[FunctionName("HTTPAzureFunction")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "GetNameVal")] HttpRequest req,
ILogger log)
Now we can test it like below
Azure Functions HTTP Trigger Route Parameters
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "GetNameVal/{name}")] HttpRequest req, string name, ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string name1 = req.Query["name"];
Now you can see the project and see the parameters below
http://localhost:7071/api/GetNameVal/{name}
Now, We can pass the name value directly using a route parameter
If you do not provide the URL’s route parameter, it will return HTTP Error 404 like below.
How To Make Azure Function Route Parameters Optional
You can Make Route Parameters Optional by adding the ? to the parameter name in the route definition and the type in the function header parameters. It looks exactly like below
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "GetNameVal/{name?}")] HttpRequest req, string name, ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string name1 = req.Query["name"];
Now, we can see the expected output by specifying the name as a URL parameter.
Now. if you do not provide the name, the parameter value defaults to null
and It will display the message to provide the name parameter.
Azure Function Route Wildcard
Sometimes, you might need to handle multiple routes with a single Azure function. The syntax will be like /api/{RemainingPath}. the value {RemainingPath} is a string representation of the remaining path.
The function will look like below
[FunctionName("NewWildCardFunction")]
public async Task NewWildCardFunction([HttpTrigger(AuthorizationLevel.Anonymous, "get",
Route = "{*RemainingPath}")]) string RemainingPath)
{
// Function body
}
Azure Function HTTP Trigger Query Parameters
I’m sorry to say that it’s not possible to put a query parameter in the Route, and it’s a restriction of ASP.NET routing used by the Azure function to build the route.
You may like following the below Articles
- Create Azure Function using Visual Studio Code and PowerShell
- CS1061 C# ‘HttpRequest’ does not contain a definition for ‘Content’ and no accessible extension method ‘Content’ accepting a first argument of type ‘HttpRequest’ could be found
- How To Monitor Azure Functions
- How To Find Azure Functions Run Time Version
- How To Call A Stored Procedure From Azure Functions
Conclusion
Well, in this article, we discussed Azure Function HTTP Trigger. I hope you have enjoyed this article !!!
.
.
I am Bijay, a Microsoft MVP (10 times) having more than 17 years of experience in the software industry. During my IT career, I got a chance to share my expertise in SharePoint and Microsoft Azure, like Azure VM, Azure Active Directory, Azure PowerShell, etc. I hope you will learn from these Azure tutorials. Read more