com.microsoft.azure.functions.annotation

Annotations and support classes for use as part of the Java API for Azure Functions.

Interfaces

BindingName

Place this on a parameter whose value would come from Azure Functions runtime. Use this annotation when you want to get the value of trigger metadata, or when you defined your own bindings in function.json manually.

BlobInput

Place this on a parameter whose value would come from a blob. The parameter type can be one of the following:

  • Any native Java types such as int, String, byte[]
  • Nullable values using Optional
  • Any POJO type

The following example is a Java function that uses a queue trigger and an input blob binding. The queue message contains the name of the blob, and the function logs the size of the blob.

@FunctionName("getBlobSize")
@StorageAccount("AzureWebJobsStorage")
 public void blobSize(
    @QueueTrigger(name = "filename",
                   queueName = "myqueue-items") String filename,
    @BlobInput(name = "file",
                dataType = "binary",
                path = "samples-workitems/{queueTrigger}") byte[] content,
     final ExecutionContext context
 ) {
     context.getLogger().info("The size of \"" + filename + "\" is: " + content.length + " bytes");
 }
BlobOutput

Place this on a parameter whose value would be written to a blob. The parameter type should be OutputBinding, where T could be one of:

  • Any native Java types such as int, String, byte[]
  • Any POJO type

The following example shows blob input and output bindings in a Java function. The function makes a copy of a text blob. The function is triggered by a queue message that contains the name of the blob to copy. The new blob is named {originalblobname}-Copy.

@FunctionName("copyTextBlob")
@StorageAccount("AzureWebJobsStorage")
@BlobOutput(name = "target", path = "samples-workitems/{queueTrigger}-Copy")
 public String blobCopy(
    @QueueTrigger(name = "filename",
                   queueName = "myqueue-items") String filename,
    @BlobInput(name = "source",
                path = "samples-workitems/{queueTrigger}") String content
 ) {
     return content;
 }
BlobTrigger

Place this on a parameter whose value would come from a blob, and causing the method to run when a blob is uploaded. The parameter type can be one of the following:

  • Any native Java types such as int, String, byte[]
  • Nullable values using Optional
  • Any POJO type

The following example shows a Java function that logs the filename and size when a blob is added or updated in the "samples-workitems" container:

@FunctionName("blobMonitor")
 public void blobMonitor(
    @BlobTrigger(name = "file",
                  dataType = "binary",
                  path = "samples-workitems/{name}",
                  connection = "AzureWebJobsStorage") byte[] content,
    @BindingName("name") String filename,
     final ExecutionContext context
 ) {
     context.getLogger().info("Name: " + filename + ", Size: " + content.length + " bytes");
 }
CosmosDBInput

Place this on a parameter whose value would come from CosmosDB. The parameter type can be one of the following:

  • Some native Java types such as String
  • Nullable values using Optional
  • Any POJO type

The following example shows a Java function that retrieves a single document. The function is triggered by an HTTP request that uses a query string to specify the ID to look up. That ID is used to retrieve a ToDoItem document from the specified database and collection. A sample URL would be like: http://localhost:7071/api/getItem?id=myid.

@FunctionName("getItem")
 public String cosmosDbQueryById(
    @HttpTrigger(name = "req",
                  methods = {HttpMethod.GET},
                  authLevel = AuthorizationLevel.ANONYMOUS) Optional<String> dummy,
    @CosmosDBInput(name = "database",
                      databaseName = "ToDoList",
                      collectionName = "Items",
                      id = "{Query.id}",
                      connectionStringSetting = "AzureCosmosDBConnection") Optional<String> item
 ) {
     return item.orElse("Not found");
 }
CosmosDBOutput

Place this on a parameter whose value would be written to CosmosDB. The parameter type should be OutputBinding, where T could be one of:

  • Some native Java types such as String
  • Any POJO type

The following example shows a Java function that adds a document to a database, using data provided in the body of an HTTP Post request.

@FunctionName("addItem")

 public String cosmosDbAddItem(
    @HttpTrigger(name = "request", methods = {HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS)
     final String message,
    @CosmosDBOutput(name = "database", databaseName = "ToDoList", collectionName = "Items", 
    connectionStringSetting = "AzureCosmosDBConnection")
 ) {
     return "{ \"id\": \"" + System.currentTimeMillis() + "\", \"description\": \"" + message + "\" }";
 }
CosmosDBTrigger

Place this on a parameter whose value would come from CosmosDB, and causing the method to run when CosmosDB data is changed. The parameter type can be one of the following:

  • Some native Java types such as String
  • Nullable values using Optional
  • Any POJO type

The following example shows a Java function that is invoked when there are inserts or updates in the specified database and collection.

@FunctionName("cosmosDBMonitor")
 public void cosmosDbLog(
    @CosmosDBTrigger(name = "database",
                      databaseName = "ToDoList",
                      collectionName = "Items",
                      leaseCollectionName = "leases",
                      createLeaseCollectionIfNotExists = true,
                      connectionStringSetting = "AzureCosmosDBConnection") 
                      List<Map<String, String>> items,
     final ExecutionContext context
 ) {
     context.getLogger().info(items.size() + " item(s) is/are inserted.");
     if (!items.isEmpty()) {
         context.getLogger().info("The ID of the first item is: " + items.get(0).get("id"));
     }
 }
CustomBinding

Place this on a parameter to define a custom binding

  • Any native Java types such as int, String, byte[]
  • Nullable values using Optional
  • Any POJO type

The following example shows a Java function that uses a customBinding:

@FunctionName("CustomBindingTriggerSample")
 public void logCustomTriggerInput(
    @CustomBinding(direction = "in", name = "inputParameterName", type = "customBindingTrigger") String customTriggerInput
    final ExecutionContext context
 ) {
     context.getLogger().info(customTriggerInput);
 }
EventGridTrigger

Place this on a parameter whose value would come from EventGrid, and causing the method to run when an event is arrived. The parameter type can be one of the following:

  • Any native Java types such as int, String, byte[]
  • Nullable values using Optional
  • Any POJO type

The following example shows a Java function that prints out an event:

@FunctionName("eventGridMonitor")
 public void logEvent(
    @EventGridTrigger(name = "event") String content,
     final ExecutionContext context
 ) {
     context.getLogger().info(content);
 }
EventHubOutput

Place this on a parameter whose value would be published to the event hub. The parameter type should be OutputBinding, where T could be one of:

  • Any native Java types such as int, String, byte[]
  • Any POJO type

The following example shows a Java function that writes a message to an event hub:

@FunctionName("sendTime")
@EventHubOutput(name = "event", eventHubName = "samples-workitems", connection = "AzureEventHubConnection")
 public String sendTime(
    @TimerTrigger(name = "sendTimeTrigger", schedule = "0 */5 * * * *") String timerInfo
 ) {
     return LocalDateTime.now().toString();
 }
EventHubTrigger

Place this on a parameter whose value would come from event hub, and causing the method to run when a new event is arrived. The parameter type can be one of the following:

  • Any native Java types such as int, String, byte[]
  • Nullable values using Optional
  • Any POJO type

The following example shows a Java function that logs the message body of the event hub trigger:

@FunctionName("eventHubMonitor")
 public void logEventHubMessage(
    @EventHubTrigger(name = "event", 
    eventHubName = "samples-workitems", 
    connection = "AzureEventHubConnection") String message,
     final ExecutionContext context
 ) {
     context.getLogger().info("Event hub message received: " + message);
 }
FunctionName

The FunctionName annotation is used to specify to the Azure Functions tooling what name is to be applied to the associated function when the function is deployed onto Azure. This becomes the endpoint (in the case of an http triggered function, for example, but more generally it is what is shown to users in the Azure Portal, so a succinct and understandable function name is useful.

An example of how the FunctionName annotation is shown in the code snippet below. Note that it is applied to the function that will be called by Azure, based on the specified trigger (in the code below it is a HttpTrigger).

@FunctionName("redirect")
  public HttpResponseMessage<String> redirectFunction(
    @HttpTrigger(name = "req",
    methods = {"get"}, authLevel = AuthorizationLevel.ANONYMOUS) 
    HttpRequestMessage<Optional<String>> request) {
     ....
  }
HttpOutput

Place this on a parameter whose value would be send back to the user as an HTTP response. The parameter type should be OutputBinding, where T could be one of:

HttpTrigger

The HttpTrigger annotation is applied to Azure functions that will be triggered by a call to the HTTP endpoint that the function is located at. The HttpTrigger annotation should be applied to a method parameter of one of the following types:

  • HttpRequestMessage < T >
  • Any native Java types such as int, String, byte[]
  • Nullable values using Optional
  • Any POJO type

For example:

@FunctionName("hello")
  public HttpResponseMessage<String> helloFunction(
    @HttpTrigger(name = "req",
                  methods = {HttpMethod.GET},
                  authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request
  ) {
     ....
  }

In this code snippet you will observe that we have a function annotated with @FunctionName("hello"), which indicates that this function will be available at the endpoint /api/hello. The name of the method itself, in this case helloFunction is irrelevant for all intents and purposes related to Azure Functions. Note however that the method return type is com.microsoft.azure.functions.HttpResponseMessage, and that the first argument into the function is an com.microsoft.azure.functions.HttpRequestMessage with generic type Optional. This indicates that the body of the request will potentially contain a String value.

Most important of all however is the @HttpTrigger annotation that has been applied to this argument. In this annotation you'll note that it has been given a name, as well as told what type of requests it supports (in this case, only HTTP GET requests), and that the AuthorizationLevel is anonymous, allowing access to anyone who can call the endpoint.

The HttpTrigger can be further customised by providing a custom #route(), which allows for custom endpoints to be specified, and for these endpoints to be parameterized with arguments being bound to arguments provided to the function at runtime.

The following example shows a Java function that looks for a name parameter either in the query string (HTTP GET) or the body (HTTP POST) of the HTTP request. Notice that the return value is used for the output binding, but a return value attribute isn't required.

@FunctionName("readHttpName")
  public String readName(
    @HttpTrigger(name = "req", 
          methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS)
          final HttpRequestMessage<Optional<String>> request) {
       String name = request.getBody().orElseGet(() -> request.getQueryParameters().get("name"));
       return name == null ?
              "Please pass a name on the query string or in the request body" :
              "Hello " + name;
  }
QueueOutput

Place this on a parameter whose value would be written to a storage queue. The parameter type should be OutputBinding, where T could be one of:

  • Any native Java types such as int, String, byte[]
  • Any POJO type

The following example shows a Java function that creates a queue message for each HTTP request received.

@FunctionName("httpToQueue")
@QueueOutput(name = "item", queueName = "myqueue-items", connection = "AzureWebJobsStorage")
 public String pushToQueue(
    @HttpTrigger(name = "request", methods = {HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS)
     final String message,
    @HttpOutput(name = "response") final OutputBinding<String> result
 ) {
     result.setValue(message + " has been added.");
     return message;
 }
QueueTrigger

Place this on a parameter whose value would come from a storage queue, and causing the method to run when a new item is pushed. The parameter type can be one of the following:

  • Any native Java types such as int, String, byte[]
  • Nullable values using Optional
  • Any POJO type

The following example shows a Java function that polls the "myqueue-items" queue and writes a log each time a queue item is processed.

@FunctionName("queueMonitor")
 public void logQueueItem(
    @QueueTrigger(name = "msg", queueName = "myqueue-items", connection = "AzureWebJobsStorage") 
     String message,
     final ExecutionContext context
 ) {
     context.getLogger().info("Queue message processed: " + message);
 }
SendGridOutput

Place this on a parameter whose value would be written to SendGrid. The parameter type should be OutputBinding, where T could be one of:

  • Any native Java types such as int, String, byte[]
  • Any POJO type
ServiceBusQueueOutput

Place this on a parameter whose value would be written to a service bus queue. The parameter type should be OutputBinding, where T could be one of:

  • Any native Java types such as int, String, byte[]
  • Any POJO type

The following example shows a Java function that sends a Service Bus queue message:

@FunctionName("httpToServiceBusQueue")
@ServiceBusQueueOutput(name = "message", queueName = "myqueue", connection = "AzureServiceBusConnection")
 public String pushToQueue(
    @HttpTrigger(name = "request", methods = {HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS)
     final String message,
    @HttpOutput(name = "response") final OutputBinding<String> result
 ) {
     result.setValue(message + " has been sent.");
     return message;
 }
ServiceBusQueueTrigger

Place this on a parameter whose value would come from a Service Bus queue, and causing the method to run when a new item is pushed. The parameter type can be one of the following:

  • Any native Java types such as int, String, byte[]
  • Nullable values using Optional
  • Any POJO type

The following example shows a Java function that logs a Service Bus queue message:

@FunctionName("serviceBusMonitor")
 public void logServiceBusMessage(
    @ServiceBusQueueTrigger(name = "msg", queueName = "myqueue", connection = "AzureServiceBusConnection") 
     final String message,
     final ExecutionContext context
 ) {
     context.getLogger().info("Message is received: " + message);
 }
ServiceBusTopicOutput

Place this on a parameter whose value would be written to a service bus topic. The parameter type should be OutputBinding, where T could be one of:

  • Any native Java types such as int, String, byte[]
  • Any POJO type
ServiceBusTopicTrigger

Place this on a parameter whose value would come from Service Bus topic, and causing the method to run when a new item is published. The parameter type can be one of the following:

  • Any native Java types such as int, String, byte[]
  • Nullable values using Optional
  • Any POJO type

The following example shows a service bus topic trigger which logs the message:

@FunctionName("sbprocessor")
 public void serviceBusProcess(
    @ServiceBusTopicTrigger(name = "msg",
                             topicName = "mytopicname",
                             subscriptionName = "mysubname",
                             connection = "myconnvarname") String message,
     final ExecutionContext context
 ) {
     context.getLogger().info(message);
 }
StorageAccount

Apply this annotation to a method if you have multiple Azure Storage triggers/input/output in that method which share the same app setting name of Azure Storage connection string.

TableInput

Place this on a parameter whose value would come from storage table. The parameter type can be one of the following:

  • Any native Java types such as int, String, byte[]
  • Nullable values using Optional
  • Any POJO type

The following example shows an HTTP trigger which returned the total count of the items in a table storage:

@FunctionName("getallcount")
 public int run(
    @HttpTrigger(name = "req",
                  methods = {"get"},
                  authLevel = AuthorizationLevel.ANONYMOUS) Object dummyShouldNotBeUsed,
    @TableInput(name = "items",
                 tableName = "mytablename",
                 partitionKey = "myparkey",
                 connection = "myconnvarname") MyItem[] items
 ) {
     return items.length;
 }
TableOutput

Place this on a parameter whose value would be written to a storage table. The parameter type should be OutputBinding, where T could be one of:

  • Any native Java types such as int, String, byte[]
  • Any POJO type
TimerTrigger

The timer trigger lets you run a function on a schedule by specifying a CRON expression for when the function should run. For more details and examples on how to specify a CRON expression, refer to the #schedule() attribute of this annotation.

An example of using the timer trigger is shown below, where the keepAlive function is set to trigger and execute every five minutes:

@FunctionName("keepAlive")
 public void keepAlive(
    @TimerTrigger(name = "keepAliveTrigger", schedule = "0 */5 * * * *") String timerInfo,
     ExecutionContext context
 ) {
     // timeInfo is a JSON string, you can deserialize it to an object using your favorite JSON library
     context.getLogger().info("Timer is triggered: " + timerInfo);
 }
TwilioSmsOutput

Place this on a parameter whose value would be sent through twilio SMS. The parameter type should be OutputBinding, where T could be one of:

  • Any native Java types such as int, String, byte[]
  • Any POJO type

Enums

AccessRights

Azure Service Bus permission.

AuthorizationLevel

Azure HTTP authorization level, Determines what keys, if any, need to be present on the request in order to invoke the function.

Cardinality

Cardinality of the EventHubTrigger input. Choose 'ONE' if the input is a single message or 'Many' if the input is an array of messages. 'Many' is the default if unspecified