> ## Documentation Index
> Fetch the complete documentation index at: https://upstash.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Serverless API with Java and Redis

In this tutorial, we will build a stateful serverless API using Java and Redis
on AWS Lambda. The API will simply count the page views and return it as HTTP
response.

### Prerequisites

1. Install the Serverless Framework installed with an AWS account set up.

```shell theme={"system"}
npm i serverless@3.39.0 -g
```

2. Install JDK and not Java JRE. Set your JAVA\_HOME.
3. Install Apache Maven.
4. Create a free Serverless Redis database from
   [Upstash](https://console.upstash.com) as described
   [here](/redis/overall/getstarted).

### Project Setup

Create the project:

```shell theme={"system"}
serverless create --template aws-java-maven --name counter-api -p aws-java-counter-api
```

```shell theme={"system"}
cd aws-java-counter-api
```

Add `jedis` as dependency to the `pom.xml`:

```xml pom.xml theme={"system"}
...
    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>3.6.0</version>
    </dependency>
...
```

Update `serverless.yml` as below:

```yaml serverless.yml theme={"system"}
service: counter-api

frameworkVersion: '3'

provider:
  name: aws
  runtime: java17

package:
  artifact: target/hello-dev.jar

functions:
 hello:
   handler: com.serverless.Handler
   events:
     - httpApi:
         path: /hello
         method: get
```

### Counter Function Setup

Update `src/main/java/com/serverless/Handler.java` as below:

```java src/main/java/com/serverless/Handler.java theme={"system"}
package com.serverless;

import java.util.Map;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import redis.clients.jedis.Jedis;

public class Handler implements RequestHandler<Map<String, Object>, ApiGatewayResponse> {
	@Override
	public ApiGatewayResponse handleRequest(Map<String, Object> input, Context context) {
		Jedis jedis = new Jedis("lasting-roughy-29092.upstash.io", 6379, true);
		jedis.auth("********");
		Long value = jedis.incr("counter");
		jedis.close();
		String message = "Hello World, Count:" + value;
		return ApiGatewayResponse.builder()
				.setStatusCode(200)
				.setObjectBody(message)
				.build();
	}
}
```

In the above code, you need to replace your Redis endpoint and password. You can copy Jedis connection code from the [Upstash Redis Console](https://console.upstash.com/redis) -> Your Database -> Connect to your database -> Java.

### Build and Deploy

Build your project:

```shell theme={"system"}
mvn clean install
```

Deploy to AWS:

```shell theme={"system"}
serverless deploy
```

Visit the output URL to see the counter in action.
