Search⌘ K
AI Features

Using HTTP Triggers

Explore how HTTP triggers enable Azure Functions execution via HTTP requests. Learn to configure triggers with authentication levels, supported HTTP methods, and custom routes. Understand integrating OpenAPI to test POST endpoints through Swagger UI, and how to enforce HTTPS to secure your development environment.

In a function, an HTTP trigger allows the user to execute the function logic via an HTTP request. In this lesson, we will examine how this type of trigger works. We will do so with the help of the interactive playground below:

using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Attributes;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json;

namespace AzureFunctionApp
{
    public class Functions
    {
        private readonly ILogger<Functions> _logger;

        public Functions(ILogger<Functions> log)
        {
            _logger = log;
        }

        [FunctionName("Chatbot")]
        [OpenApiOperation(operationId: "Run", tags: new[] { "name" })]
        [OpenApiParameter(name: "name", In = ParameterLocation.Query, Required = true, Type = typeof(string), Description = "The name of the user")]
        [OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: "text/plain", bodyType: typeof(string), Description = "Chat reply")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "introduction")] HttpRequest req)
        {
            string name = req.Query["name"];

            var requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;

            var responseMessage = string.IsNullOrEmpty(name)
                ? "Hello. What is your name?"
                : $"Hello, {name}. What can I help you with?";

            return new OkObjectResult(responseMessage);
        }
    }
}

Function app with a HTTP trigger and OpenAPI

HTTP trigger basics

An HTTP trigger is added to a function method via a request parameter marked by the HttpTrigger attribute. We have an example of it in line 30 inside the Functions.cs file. Here are some properties that we configure inside the attribute:

  • AuthLevel: This represents the authentication level for the function. In the above example, we set it as AuthorizationLevel.Anonymous, which allows the user to execute the function without specifying any secrets in the request.

  • Methods: This represents a list of HTTP verbs that the function can be executed with. In the above example, we only allow it to be executed via the POST method.

  • Route: This represents the URL path that maps to the method. In the above example, the path is introduction, which makes our function accessible by specifying /api/introduction after the base URL.

In the above example, this attribute is placed on the input parameter of the HttpRequest type, which represents a request object. This object is dynamic enough to represent both the payload from a POST request and the query string parameters of a GET request. For example, in line 32, we attempt to extract a query string parameter from the request:

string name = req.Query["name"];

In line 34, we attempt to extract the request body:

var requestBody = await new StreamReader(req.Body).ReadToEndAsync();

If we set GET as one of the allowed HTTP methods, we will be able to trigger the method from the browser. For any other HTTP method, however, we would typically need to use a CLI command, a third-party tool such as Postman, or build our own client. However, there is also an OpenAPI library that we can use to enable our POST endpoints to be accessible from the browser.

Using OpenAPI with HTTP triggers

Before we can use OpenAPI (also commonly referred to as Swagger), we need to add the Microsoft.Azure.WebJobs.Extensions.OpenApi NuGet package to our project. We do so in line 7 of the AzureFunctionApp.csproj file.

Once we add the required dependencies, we can apply the appropriate attributes on an HTTP trigger method to register it with OpenAPI.

  • First, we need to make sure we reference the appropriate namespaces via the using statements. In the Functions.cs file, these can be seen in lines 9 and 11, which are references to the Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Attributes and Microsoft.OpenApi.Models namespaces, respectively.

  • Then, we add the appropriate attributes, as we do in lines 26–28, which look as follows:

[OpenApiOperation(operationId: "Run", tags: new[] { "name" })]
[OpenApiParameter(name: "name", In = ParameterLocation.Query, Required = true, Type = typeof(string), Description = "The name of the user")]
[OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: "text/plain", bodyType: typeof(string), Description = "Chat reply")]

The OpenApiOperation attribute allows us to give the name to the operation. The OpenApiParameter attribute allows us to assign a human-readable description of a parameter that we can inject into the method. The OpenApiResponseWithBody attribute describes the HTTP response that we expect to get by calling this endpoint.

Accessing the Swagger page

To access the Swagger page of the function app, we can go through the following steps:

  1. Build the function app by clicking the “Run” button.

  2. Click the URL provided next to the “Your app can be found at” label.

  3. Navigate to the Swagger web page by clicking the application URL and adding the /api/swagger/ui path to the address.

We should expect to see the following web page, where we can test out any HTTP trigger endpoint by clicking the “Try it out” button:

Swagger page example
Swagger page example

Forcing HTTPS on a development environment

In some circumstances, we would want to enforce HTTPS in our development environment. Depending on our hosting model, this might sometimes create a mismatch between the address used by the main application and the address used by the Swagger page to retrieve the OpenAPI configuration. If the application is only accessible via HTTPS but the OpenAPI document is being accessed via HTTP, the Swagger page will not work.

To prevent this and force the entire application to use HTTPS, we can add the OpenApi__ForceHttps setting to our settings and set it to true. In the above setup, we do so in line 6 of the local.settings.json file.