Introduction to Serverless and Azure Functions with Java and IntelliJ IDEA.

Rashmin Mudunkotuwa
7 min readAug 1, 2023
Photo by Intricate Explorer on Unsplash

Serverless

Serverless programming/deployment style has been up and coming in the recent years and all the major cloud providers have implemented their own version of Serverless computing.

Serverless is a cloud computing/ code deployment technology which provides backend services to a client on an-used basis. Meaning that unlike the the typical PaaS services which are charged depending on the up-time of the service, this will be charged depending on the usage of the service making it much more cost-effective in certain scenarios.

Here, the term “Serverless” could be misleading because it does not mean that there are no servers, obviously if we need to deploy our code to the internet, we must do so in a server which has a network connection. The difference here is that, us as developers will have to do little to no configuration/infrastructure management when deploying our service/code. All the infrastructure and application run-times are managed by the cloud provider. The developer just has to feed the finalized code into the cloud portal and the cloud provider will manage the runtime/infrastructure/resource allocation all by itself and would expose our service to the internet and scale/manage the service depending on the load received.

Azure Functions

Azure functions is the serverless computing offering provided by Microsoft’s Azure Cloud. It supports many of the modern programming languages and have a rich feature set.

The main feature of an Azure Function is the “Trigger”, which causes a certain Azure function to run and defines how a function is invoked. There are multiple triggers which are supported by default but the most common are,

  1. HTTP Trigger — Triggers a given function on a HTTP Request. Could be used to make quick and easy cloud managed APIs.
  2. Time Trigger — Triggers a given function based on a timer. Could be useful for timed jobs/tasks in the cloud.
  3. Database/SQL Trigger — Triggers a given function based on a SQL/Database change (etc — Adding/Deleting a Row of Data)

An Azure function mainly consists of two parts. The code itself and the configuration (function.json).

Azure Function Structure

The code consists of the developed code which we require to be executed as a serverless service. The function.json file is the configuration of the Azure function which contains the details of Triggers/Bindings and extra configuration.

An Azure function is deployed within a “Function App”, which is a unit of deployment. A function app can contain multiple functions deployed within itself. So for you to deploy a developed Azure function, you will first need to create an Function App using the Azure Portal.

Functions and Java

Azure supports Java as a language to develop Azure functions. The development SDK/Libraries are provide by the com.microsoft.azure.functions.azure-functions-java-library maven dependency which includes all the tools we need to develop Azure functions in Java.

<dependency>
<groupId>com.microsoft.azure.functions</groupId>
<artifactId>azure-functions-java-library</artifactId>
<version>2.2.0</version>
</dependency>

After developed, Java code can be deployed to a function app via the IDE (IntelliJ IDEA/ VSCode) itself by the Azure plugin, or via packaging the build files as a ZIP and uploading it to the Azure portal.

Creating a Simple Greeting Function

Lets look at how to create a simple service using Java and IntelliJ. (Please make sure to install the azure cli on your PC )

First you’ll have to generate the project, which could be achieved using a maven archetype.

mvn archetype:generate -DarchetypeGroupId=com.microsoft.azure -DarchetypeArtifactId=azure-functions-archetype -DjavaVersion=<java-version>

After entering this command in the terminal, provide a group-id, artifact-id, version and a package name for your project. This will create a folder with the auto generated project files which you need to open using your preferred IDE. I will be using IntelliJ IDEA in this article.

project file structure

After opening the generated folder, the file structure would look something like the above.

The files to take notice are Function.java, host.json and local.settings.json.

  • Function.java — Contains the auto-generated dummy azure function code.
  • host.json — Contains metadata/configurations affecting all the functions in the function app.
  • local.settings.json — Settings used when locally running the Azure function

Function.Java

The Function.java file would contain the Function class which is auto-generated via the Maven Archetype.

It defines a HttpTrigger type of Azure Function in the run method, which is annotated using@FunctionName .

public class Function {
@FunctionName("HttpExample")
public HttpResponseMessage run(
@HttpTrigger(
name = "req",
methods = {HttpMethod.GET, HttpMethod.POST},
authLevel = AuthorizationLevel.ANONYMOUS)
HttpRequestMessage<Optional<String>> request,
final ExecutionContext context) {
context.getLogger().info("Java HTTP trigger processed a request.");

final String query = request.getQueryParameters().get("name");
final String name = request.getBody().orElse(query);

if (name == null) {
return request
.createResponseBuilder(HttpStatus.BAD_REQUEST)
.body("Please pass a name")
.build();
} else {
return request
.createResponseBuilder(HttpStatus.OK)
.body("Hello, " + name)
.build();
}
}
}

The run method returns an object of the type HttpResponseMessage and takes in two parameters.

  1. HttpRequestMessage — consists of the details of the received in the HTTP request. Annotated with @HttpTrigger , which specifies supported HTTP methods, name and authorization level.
  2. ExecutionContext — To interact with the Azure Function execution environment/context.

The HttpRequestMessage request object is utilized to obtain the query/body parameters and, in the end to build the HttpResponse using request.createResponseBuilder() method.

Let’s modify the code a little bit.

public class Function {
@FunctionName("greeting")
public HttpResponseMessage run(
@HttpTrigger(
name = "req",
methods = HttpMethod.GET,
authLevel = AuthorizationLevel.ANONYMOUS)
HttpRequestMessage<Optional<String>> requestMessage,
final ExecutionContext context) {

String greeting = requestMessage.getQueryParameters().get("greeting");
String name = requestMessage.getQueryParameters().get("name");

if (greeting == null || name == null) {
return requestMessage.createResponseBuilder(HttpStatus.BAD_REQUEST).build();
} else {
return requestMessage.createResponseBuilder(HttpStatus.OK).body(greeting+"! "+name+".").build();
}
}
}

I have added a new set of query parameters and changed the function name and function methods.

Let’s compile and package the function with the below command.

mvn clean package -DskipTests

This will create a folder azure-functions inside the target folder.

azure-functions folder

In this folder we can see the packaged azure-function. The Java code is packaged into azure-function-xxx.jar file and the configuration is available in the function.json file inside the greeting folder.

Now that the function is compiled, you could run the function locally and test its functionality from the below command.

mvn azure-functions:run

This will use the azure functions core tools to execute and run the function locally.

running azure function locally

You can use the given URL in the browser to test the function as follows.

http://localhost:7071/api/greeting?greeting=Hola&name=rashm1n

Now that the function is tested locally we shall look into creating the Function App in Azure portal and deploying our function to the Function App.

Follow the below steps to create the Function App in Azure Portal.

Step 1 — Navigate to Azure Functions menu and click on Create Function App.

azure-functions menu

Step 2 — Fill in the naming details as you prefer.

I will use the version as Java 17 and Operating System as Windows.

Create Function App

Step 3 — Click Review + Create and create the app.

After creating the function app, open the IDE (IntelliJ IDEA) again and go to Settings -> Plugins and install the Azure Toolkit for IntelliJ plugin. You would have the restart the IDE to make it work.

After that you’ll notice a new option in the side-pane of your IDE as below.

Azure Explorer.

Click on the Azure Explorer and log-in to your Azure Account.

Logging in to Azure

After signing-in you will notice the list of Azure resources created in you account/subscription. From that list, select the Function App option and you will see the function app we created a minute ago.

Now all you have to do is, right click on our function app and click Deploy. This would open a new dialog box in which you can keep the default options and click Run.

Deploy Dialog Box

This will start the deployment procedure and eventually deploy you application to the created Azure function. You’ll see the following message in the terminal when the deployment is completed.

Deployment Completed Message

And the deployed URL would appear in the deployment success message as above.

Now you can access the deployed Azure Function code via the below URL.

<YOUR_AZURE_URL>/api/greeting?greeting=Hola&name=rashm1n

Executing the Function

In this article I briefly talked about the Serverless architecure, Azure functions and how to create/deploy an Azure function using Java and IntelliJ IDEA. I hope you found this article useful and feel free to ask any questions. Look into my other articles if you are interested in Java/Cloud and Databases. Cheers !

Want to Connect ?

- Medium
- LinkedIn
- Twitter(X)
- Threads

Find me everywhere @rashm1n.
Resources

- https://learn.microsoft.com/en-us/azure/azure-functions/functions-overview?pivots=programming-language-java
-

--

--

Rashmin Mudunkotuwa

Software Engineer | Interested in Cloud Computing, Microservices, API Development, and Software as a whole.