# Reference Application Tutorial
source: https://developer.mastercard.com/consumer-clarity/documentation/tutorials-and-guides/reference-app-tutorial/index.md

## Overview {#overview}

This tutorial shows you how to generate an API client for the Consumer Clarity API. You will build an application that makes an API call to the Consumer Clarity service to retrieve details about a specific merchant and transaction.

### What you need {#what-you-need}

* [Mastercard Developers Account](https://developer.mastercard.com/dashboard) with access to Ethoca Consumer Clarity
* A text editor or IDE
* [Spring Boot 2.2+](https://spring.io/projects/spring-boot)
* [Apache Maven 3.3+](https://maven.apache.org/download.cgi)
* Set up the `JAVA_HOME` environment variable to match the location of your Java installation

### Generate API keys {#generate-api-keys}

If you haven't yet done so, first generate the Sandbox credentials that your server uses to communicate with Mastercard and the Consumer Clarity API client. See our [Quick Start Guide](https://developer.mastercard.com/consumer-clarity/documentation/quick-start-guide/index.md) for the steps required to set up the Sandbox project and download the keys.

## Step-By-Step Guide {#step-by-step-guide}

To complete this tutorial, you can either start from scratch using the [Spring Getting Started](https://spring.io/guides) guides and complete each step, or you can bypass the basic setup steps that are already familiar to you. Either way, you end up with working code.

To skip the basics, do the following:

* Access the source code for this tutorial from this zip file: [consumer-clarity-reference-1.0.0-SNAPSHOT-dist.zip](https://static.developer.mastercard.com/content/consumer-clarity/uploads/consumer-clarity-reference-1.0.0-SNAPSHOT-dist.zip) (42KB)
* Go to [Configure Resources](https://developer.mastercard.com/consumer-clarity/documentation/tutorials-and-guides/reference-app-tutorial/index.md#step-2-configure-resources).

### Step 1: Create a Maven project {#step-1-create-a-maven-project}

1. In Maven, select **File** \> **New** \> **Project** to create a new Maven project. This sets up your directory structure automatically.
2. Select **Project SDK** , then select **Next** . ![Create new Maven project for Consumer Clarity API](https://static.developer.mastercard.com/content/consumer-clarity/documentation/img/maven-create-project.png)
3. Enter a GroupId, ArtifactId and Version. These are required to configure a Maven project. Select **Next** . ![Enter Maven project details](https://static.developer.mastercard.com/content/consumer-clarity/documentation/img/maven-enter-project-details.png)
4. Enter a Project name, such as consumer-clarity-reference", and a Project location.
5. Select **Finish**.

### Step 2: Configure resources {#step-2-configure-resources}

1. Download and add the Consumer Clarity `OpenAPI Specification YAML` file into your Maven project's `local/` folder: [consumer-clarity-api-spec.yaml](https://static.developer.mastercard.com/content/consumer-clarity/swagger/consumer-clarity-api-spec.yaml) (89KB). (If necessary, right-click and save the file to your `local/` folder.)
2. Download and add the Consumer Clarity Subscription Cancellation `OpenAPI Specification YAML` file into your Maven project's `local/` folder: [clarity-subscription-actions.yaml](https://static.developer.mastercard.com/content/consumer-clarity/swagger/clarity-subscription-actions.yaml) (62KB). (If necessary, right-click and save the file to your `local/` folder.)
3. Place the .p12 file in the `resources` folder. The .p12 file was generated when you created the [Sandbox Signing Keys](https://developer.mastercard.com/consumer-clarity/documentation/tutorials-and-guides/quick-start-guide/index.md#sandbox-oauth-credentials) within your project in Mastercard Developers.
4. Specify the `src/main/resources/application.properties` file as `classpath:<p.12 file name>`.

Your Maven project directory now looks similar to this (the .idea and .iml items are generated and used by IntelliJ IDEA):

![Maven project directory](https://static.developer.mastercard.com/content/consumer-clarity/documentation/img/maven-project-directory.png)

### Step 3: Generate an API client project {#step-3-generate-an-api-client-project}

Add the following plugin to your project's *pom.xml* file to generate an API client library.

```Maven
<!-- https://mvnrepository.com/artifact/org.openapitools/openapi-generator-maven-plugin -->
<plugin>
    <groupId>org.openapitools</groupId>
    <artifactId>openapi-generator-maven-plugin</artifactId>
    <version>${openapi-generator.version}</version>
    <executions>
        <execution>
            <id>clarity-search</id>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <inputSpec>${project.basedir}/local/consumer-clarity-api-spec.yaml</inputSpec>
                <generatorName>java</generatorName>
                <library>okhttp-gson</library>
                <generateApiTests>false</generateApiTests>
                <generateModelTests>false</generateModelTests>
                <configOptions>
                    <sourceFolder>src/gen/main/java</sourceFolder>
                    <dateLibrary>java8</dateLibrary>
                </configOptions>
            </configuration>
        </execution>
        <execution>
            <id>clarity-subscription</id>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <inputSpec>${project.basedir}/local/clarity-subscription-actions.yaml</inputSpec>
                <generatorName>java</generatorName>
                <library>okhttp-gson</library>
                <generateApiTests>false</generateApiTests>
                <generateModelTests>false</generateModelTests>
                <configOptions>
                    <sourceFolder>src/gen/main/java</sourceFolder>
                    <dateLibrary>java8</dateLibrary>
                </configOptions>
            </configuration>
        </execution>
    </executions>
</plugin>
```

Note: If you created your project from scratch, also add the following libraries to the dependencies section of your *pom.xml* file.

```Maven
<dependency>
   <groupId>com.squareup.okhttp3</groupId>
   <artifactId>okhttp</artifactId>
   <version>4.8.1</version>
</dependency>
<dependency>
   <groupId>com.squareup.okhttp3</groupId>
   <artifactId>logging-interceptor</artifactId>
   <version>4.8.1</version>
</dependency>
<dependency>
   <groupId>io.gsonfire</groupId>
   <artifactId>gson-fire</artifactId>
   <version>1.8.4</version>
</dependency>
<dependency>
   <groupId>com.google.code.gson</groupId>
   <artifactId>gson</artifactId>
   <version>2.8.6</version>
</dependency>
<dependency>
   <groupId>io.swagger</groupId>
   <artifactId>swagger-annotations</artifactId>
   <version>1.6.1</version>
</dependency>
<dependency>
   <groupId>com.google.code.findbugs</groupId>
   <artifactId>jsr305</artifactId>
   <version>3.0.2</version>
</dependency>
```

### Step 4: Generate the API client sources {#step-4-generate-the-api-client-sources}

You now have all the dependencies you need to generate sources. To do this, use one of these methods:

#### Method 1 {#method-1}

1. In IntelliJ IDEA, open the Maven window by selecting **View** \> **Tool Windows** \> **Maven**.
2. Select **Reimport All Maven Projects** and **Generate Sources and Update Folders for All Projects**.

![Updated Maven folders for all projects](https://static.developer.mastercard.com/content/consumer-clarity/documentation/img/maven-reimport-projects.png)

#### Method 2 {#method-2}

1. In the same menu, navigate to the commands by selecting **{Project name}** \> **Lifecycle**.
2. Select **clean and compile** then select **Run Maven Build**.

![Run Maven build](https://static.developer.mastercard.com/content/consumer-clarity/documentation/img/maven-run-build.png)

Alternatively, you can navigate to the root directory of the project within a terminal window and run the `mvn clean compile` command.

After you finish, there's a new folder named *target* within your root directory. This folder contains classes generated for the schemas and API calls defined within the OpenAPI Specification.

![Maven target folder](https://static.developer.mastercard.com/content/consumer-clarity/documentation/img/maven-target-folder.png)

### Step 5: Create an API client instance {#step-5-create-an-api-client-instance}

To create an API client instance, you need to make your consumer key and OAuth signing key credentials available to the program.

1. Edit your Maven project's `src/main/resources/application.properties` file to include the `entrans.api.key-file` and `entrans.api.consumer-key` information you received when you generated your sandbox keys.
2. Create an instance of the generated `ApiClient` class and configure it as shown:

```ApiClient
ApiClient client = new ApiClient();
Builder httpClientBuilder = client.getHttpClient().newBuilder();
client.setBasePath("https://sandbox.api.ethocaweb.com/ethoca/consumer-clarity/searches);
// Add the interceptor code responsible for signing HTTP requests
PrivateKey signingKey = AuthenticationUtils.loadSigningKey("./path/to/your/signing-key.p12", "your key alias", "your keystore password");
httpClientBuilder.addInterceptor(new OkHttpOAuth1Interceptor("your consumer key string", signingKey));
```

Note: OpenAPI Generator supports several HTTP clients and frameworks for Java (such as Jersey, OkHttp, RestTemplate, Retrofit). In this tutorial, we chose to use okhttp-gson. Refer to our [Java library on GitHub](https://github.com/Mastercard/oauth1-signer-java#integrating-with-openapi-generator-api-client-libraries) for a list of supported options.

### Step 6: Call the service {#step-6-call-the-service}

You can now send requests to the Consumer Clarity service through the [**/searches**](https://developer.mastercard.com/consumer-clarity/documentation/api-reference/index.md#apis) endpoint. Use the generated **EnrichedTransactionApi** class, as shown in this code:

```UserApi
EnrichedTransactionApi enrichedTransactionApi = new EnrichedTransactionApi(apiClient);
EnrichedTransactionRequest enrichedTransactionRequest = getFirstUseCaseEnrichedTransactionSearch();
EnrichedTransactionResponse enrichedTransactionResponse = enrichedTransactionApi.search(enrichedTransactionRequest);
```

The API client serializes and signs the `EnrichedTransactionRequest` request and de-serializes the response into an `EnrichedTransactionResponse` instance.

To make it easy to understand, only the snippets needed to make the API call are shown above. You can download the full reference content here:
[EnrichedTransactionServiceImpl.java](https://static.developer.mastercard.com/content/consumer-clarity/uploads/EnrichedTransactionServiceImpl.java) (2KB). (If necessary, right-click and save the file to download it.)

Here is an example of a request and response from our provided [test case data](https://developer.mastercard.com/consumer-clarity/documentation/testing/index.md).

#### Request {#request}

```JSON
{
  "locale": "en-US",
  "searchCriteria": [
    {
      "merchantCriteria": {
        "cardAcceptorName": "SHOE STORE 1234",
        "cardAcceptorLocation": "AUSTIN",
        "cardAcceptorRegionCode": "TX",
        "cardAcceptorCountryCode": null,
        "merchantCategoryCode": "5661"
      }
    }
  ]
}
```

#### Expected response {#expected-response}

```JSON
{
  "searchResults": [
    {
      "recordId": "0.cef8da17.1672866204.72030a8a-01",
      "resultStatus": {
        "code": "OK",
        "message": "OK."
      },
      "merchantResult": {
        "merchantName": "The Shoe Store",
        "address": {
          "line1": "100 Main St",
          "city": "Austin",
          "postalCode": "78701",
          "countryCode": "USA",
          "countryName": "United States",
          "countrySubdivisionCode": "TX"
        },
        "merchantCategory": {
          "code": "5661",
          "description": "SHOE STORES"
        },
        "logos": [
          {
            "height": 400,
            "width": 400,
            "url": "https://sandbox.content.ethoca.com/b/industry/61d0cd49-f86b-4c55-afbc-ccdc30abf990.png?size=400",
            "type": "INDUSTRY",
            "altTextTag": "Shoe Stores Logo"
          },
          {
            "height": 200,
            "width": 200,
            "url": "https://sandbox.content.ethoca.com/b/industry/61d0cd49-f86b-4c55-afbc-ccdc30abf990.png?size=200",
            "type": "INDUSTRY",
            "altTextTag": "Shoe Stores Logo"
          }
        ],
        "merchantLocation": {
          "latitude": "30.309558",
          "longitude": "-97.759881"
        },
        "resultStatus": {
          "code": "MERCHANT_FOUND",
          "message": "Merchant results provided."
        }
      },
      "purchaseReceipt": {
        "resultStatus": {
          "code": "RECEIPT_NOT_ACCESSIBLE",
          "message": "Purchase receipt service not configured for this account."
        }
      }
    }
  ]
}
```

You can also check out our guidance for [How to Use the Response Data](https://developer.mastercard.com/consumer-clarity/documentation/tutorials-and-guides/how-to-use-response-data/index.md) for tips on how you can use the returned response in your banking app.

### Step 7: Build and execute {#step-7-build-and-execute}

Now that you've added the correct properties, you can build the application.

1. Navigate to the project's base directory from the terminal and run the following command.

   `mvn clean install`
2. After the project builds successfully, run the following command to start the project.

   `java -jar target/consumer-clarity-reference-1.0.0-SNAPSHOT.jar`

You are now running an application that uses the Consumer Clarity API Service.

## Next Steps {#next-steps}

When ready, you can convert your sandbox keys to production.

* Log into your [Mastercard Developers Account](https://developer.mastercard.com/account/log-in) and navigate to **My Projects**.
* Request Production access for your project, which requires approval from Mastercard and assistance from the [Ethoca Customer Delivery Team](mailto:customerdelivery@ethoca.com).   

You can also check out these other articles for guidance on interacting with the Consumer Clarity API:

* [Tips for Sending Requests](https://developer.mastercard.com/consumer-clarity/documentation/tutorials-and-guides/tips-for-sending-requests/index.md)
* [How to Use the Response Data](https://developer.mastercard.com/consumer-clarity/documentation/tutorials-and-guides/how-to-use-response-data/index.md)
