# Java API Client
source: https://developer.mastercard.com/payment-currency-conversion/documentation/tutorials-and-guides/api-tutorial/index.md

This tutorial generates a Java API client library using the OpenAPI Generator and Currency Conversion Calculator API specification and builds a simple Java program that makes API calls to the Sandbox environment. You can also adapt this tutorial to [make API Calls to Production](https://developer.mastercard.com/payment-currency-conversion/documentation/tutorials-and-guides/api-tutorial/index.md#make-api-calls-to-production).

## Prerequisites {#prerequisites}

To complete this tutorial, you need:

* [Java 11+](https://www.java.com/en/download/manual.jsp). Ensure that your `JAVA_HOME` environment variable is pointing to your JDK installation or have the java executable on your `PATH` environment variable.
* [Maven 3.6.0+](https://maven.apache.org/download.cgi)
* Integrated Development Environment (IDE) of your choice. This tutorial uses the IntelliJ IDEA IDE.
* A Mastercard Developers [project](https://developer.mastercard.com/dashboard) created with the **Currency Conversion for Originating Institution** API service. This generated the Sandbox signing key (.p12 file) and credentials you will use to access the Sandbox environment. For guidance on creating a project, see the [quick start guide](https://developer.mastercard.com/platform/documentation/getting-started-with-mastercard-apis/quick-start-guide/).

## Generate a Client Application {#generate-a-client-application}

Note: This tutorial was developed using a Windows machine. You can follow the same steps in other Operating Systems (OS) as well.

In the File Explorer, create a folder in your desired location. In the same folder:

1. Download and save the
[currency-conversion-oi.yaml](https://static.developer.mastercard.com/content/payment-currency-conversion/swagger/currency-conversion-oi.yaml) (22KB) file.

2. Download and save the latest [OpenAPI Generator CLI](https://openapi-generator.tech/docs/installation/#jar) jar directly from Maven.org.

3. Create a `config.json` file and add the following configurations to the file:

```json
{
   "groupId":"com.acme.app",
   "artifactId":"mastercard-api-client",
   "artifactVersion":"1.0.0",
   "invokerPackage":"com.acme.app.mastercard",
   "apiPackage":"com.acme.app.mastercard.api",
   "modelPackage":"com.acme.app.mastercard.model"
}  
```

Your current folder should look as follows:

![](https://static.developer.mastercard.com/content/payment-currency-conversion/documentation/images/ccc-oi-api-tutorial-1.png)

4. Open the Command Prompt and navigate to that folder.

5. Run the following command to generate the client application.

    openapi-generator-cli-7.8.0.jar generate -g java --library okhttp-gson -i currency-conversion-oi.yaml -c config.json -o CurrConvOIClient

In the above command, alter these parts as necessary:

* Jar version number, for example, "7.8.0"
* Name of the swagger file, for example, "currency-conversion-oi.yaml"
* Name of the desired client application, for example, "CurrConvOIClient"

After you run the command, the CurrConvOIClient application is generated within that folder as follows:

![](https://static.developer.mastercard.com/content/payment-currency-conversion/documentation/images/ccc-oi-api-tutorial-2.png)

## Set up a Maven Project {#set-up-a-maven-project}

After generating the client application, complete the below Maven project setup to download the dependencies and generate the Java client library.

1. In the IntelliJ IDE, open the client application as a **Maven** project. Your IntelliJ IDE should look as follows:

![](https://static.developer.mastercard.com/content/payment-currency-conversion/documentation/images/ccc-oi-api-tutorial-3.png)

2. Edit the **pom.xml** file to add the below OAuth Client Authentication Library as one of the dependencies.

```xml
    <dependency>
                <groupId>com.mastercard.developer</groupId>
                <artifactId>oauth1-signer</artifactId>
                <version>1.5.2</version>
    </dependency>
```

3. In the IntelliJ IDE, navigate to the Terminal window and run the below command:

    mvn clean install

After you have successfully run the command, a new folder named **target** is generated within your root directory, which contains classes generated for the schemas and API calls defined within the API specification. The generated classes can be found in the location `target/classes/com/acme/app/mastercard` as shown below.

![](https://static.developer.mastercard.com/content/payment-currency-conversion/documentation/images/ccc-oi-api-tutorial-4.png)

4. Create a **resources** folder in the `./src/main/` location and copy the Sandbox signing key (.p12) file to that folder as shown below:

![](https://static.developer.mastercard.com/content/payment-currency-conversion/documentation/images/ccc-oi-api-tutorial-5.png)

## Make API Calls to Sandbox {#make-api-calls-to-sandbox}

The below steps and sample code demonstrate how to make an API call. You can either:

* Download and add the [CurrConvOI.java](https://static.developer.mastercard.com/content/payment-currency-conversion/uploads/CurrConvOI.java) (5KB) file, then alter the code snippets as indicated below.
* Create a new Java class file, then add and alter the code snippets as indicated below.

Add or create the Java class file in the `./src/main/java` location as shown below:

![](https://static.developer.mastercard.com/content/payment-currency-conversion/documentation/images/ccc-oi-api-tutorial-6.png)

Open the `CurrConvOI.java` file and modify or add the following parts accordingly:

1. Add or adjust the code to import the required classes:

```java
import com.acme.app.mastercard.ApiClient;
import com.acme.app.mastercard.ApiException;
import com.acme.app.mastercard.api.*;
import com.acme.app.mastercard.model.*;
import com.mastercard.developer.interceptors.OkHttpOAuth1Interceptor;
import com.mastercard.developer.utils.AuthenticationUtils;
import java.security.PrivateKey;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.concurrent.TimeUnit;
```

2. Update the consumer key and signing key values to match your .p12 file and the Sandbox Credentials from your Mastercard Developers project. These will be used by the `AuthenticationUtils.loadSigningKey()` method to generate a private signing key object.

```java
        // Update these values to match your OAuth credentials
        String consumerKey = "your_consumer_key_WdnUc_-2345tF245A-_DE7f71c_-75!b10-_23451b440ab_-e210b12-_58f650000000000000000";
        String signingKeyAlias = "your_key_alias";
        String signingKeyFilePath = "./src/main/resources/CCC-project-sandbox-signing.p12";
        String signingKeyPassword = "your_key_password";

        // This method generates the signing key which can be used to sign your API requests
        PrivateKey signingKey = AuthenticationUtils.loadSigningKey(signingKeyFilePath, signingKeyAlias, signingKeyPassword);
```

3. The base path is set to the Sandbox environment by default. You instantiate a client that can sign requests with your authentication credentials.

```java
        ApiClient apiClient = new ApiClient();

        apiClient.setBasePath("https://sandbox.api.mastercard.com/originator/payment-transaction");
        apiClient.setHttpClient(
                apiClient.getHttpClient()
                        .newBuilder()
                        .addInterceptor(new OkHttpOAuth1Interceptor(consumerKey, signingKey))
                        .build()
        );
```

### Currencies endpoint {#currencies-endpoint}

4. You create a new `currenciesApi` request object for the `/currencies` endpoint. The `currenciesResponse` object will be used to store the response.

```java
        // This function makes a GET call to the Currencies endpoint
        CurrenciesApi currenciesApi = new CurrenciesApi(apiClient);
        MastercardCurrency currenciesResponse = null;
```

5. You call the `getOIMCCurrencyData` function to make the API call to the `/currencies` endpoint. For successful calls, you can access the individual response values using the `currenciesResponse.get()` method.

```java
        System.out.println();
        System.out.println("GET call to the Currencies endpoint...");
        System.out.println();
        try {
            currenciesResponse = currenciesApi.getOIMCCurrencyData();
            System.out.println("Response:");
            System.out.println(currenciesResponse);
        } catch (ApiException e) {
            System.err.println("Exception when calling CurrenciesApi#getOIMCCurrencyData");
            System.err.println("Status code: " + e.getCode());
            System.err.println("Reason: " + e.getResponseBody());
            System.err.println("Response headers: " + e.getResponseHeaders());
            e.printStackTrace();
        }
```

##### Result {#result}

When you build and run `CurrConvOI.java` in the IntelliJ IDE, the successful API request produces the following response in the Run window.

    class MastercardCurrency {
        requestInformation: class RequestInformation {
            name: payment transaction currencies
            description: A list of mastercard active currencies
            requestDate: 2024-10-24 11:07:01 GMT
        }
        data: class MastercardCurrencies {
            currencyCount: 151
            mastercardCurrencies: [class Currency {
                alphaCd: AFN
                currNam: AFGHANISTAN AFGHANI
            }, class Currency {
                alphaCd: ALL
                currNam: ALBANIAN LEK
            }, class Currency {
                alphaCd: DZD
                currNam: ALGERIAN DINAR
            }, class Currency {
    ...

### Conversion Rates Status endpoint {#conversion-rates-status-endpoint}

6. Optional: Add a 5-second wait before adding the next endpoint call.

```java
        // Wait five seconds before next call
        System.out.println();
        System.out.println("Wait five seconds");
        TimeUnit.SECONDS.sleep(5);
```

7. You create a new `conversionRatesStatusApi` request object for the `/status-rates` endpoint and set the query value (`rateDate`). The `conversionRatesStatusResponse` object will be used to store the response.

```java
        // Set request query values for the Conversion Rates Status call
        LocalDate rateDate = LocalDate.now();

        // This function makes a GET call to the Conversion Rates Status endpoint
        ConversionRatesStatusApi conversionRatesStatusApi = new ConversionRatesStatusApi(apiClient);
        StatusRates conversionRatesStatusResponse = null;
```

8. You call the `getOIMCRateStatus` function to make the API call to the `/status-rates` endpoint. For successful calls, you can access the individual response values using the `conversionRatesStatusResponse.get()` method.

```java
        System.out.println();
        System.out.println("GET call to the Conversion Rates Status endpoint...");
        System.out.println();
        try {
            conversionRatesStatusResponse = conversionRatesStatusApi.getOIMCRateStatus(rateDate);
            System.out.println("Response:");
            System.out.println(conversionRatesStatusResponse);
        } catch (ApiException e) {
            System.err.println("Exception when calling ConversionRatesStatusApi#getOIMCRateStatus");
            System.err.println("Status code: " + e.getCode());
            System.err.println("Reason: " + e.getResponseBody());
            System.err.println("Response headers: " + e.getResponseHeaders());
            e.printStackTrace();
        }
```

##### Result {#result-1}

When you build and run `CurrConvOI.java` in the IntelliJ IDE, the successful API request produces the following response in the Run window. You may get a different response if the rates have been published today.

    class StatusRates {
        requestInformation: class RequestInformation {
            name: payment-transaction-rate-issued
            description: Determine if mastercard conversion rates are issued for the given date
            requestDate: 2024-10-24 11:07:06 GMT
        }
        data: class RateStatusResponseData {
            rateDate: 2024-10-24
            mastercardRateIssued: class RateStatus {
                status: No
                reasonCode: TO_BE_PUBLISHED
                message: Mastercard Rate is not yet published for the selected date. Resubmit later
            }
        }
    }

### Conversion Rate Details endpoint {#conversion-rate-details-endpoint}

9. Optional: Add a 5-second wait before adding the next endpoint call.

```java
        // Wait five seconds before next call
        System.out.println();
        System.out.println("Wait five seconds");
        TimeUnit.SECONDS.sleep(5);
```

10. You create a new `conversionRateDetailsApi` request object for the `/transaction-settlement-rate-details` endpoint and set the query values (`transactionDate` and so on). The `conversionRateDetailsResponse` object will be used to store the response.

```java
        // Set request query values for the Conversion Rate Details call
        String transactionDate = "0000-00-00";
        String transactionCurrency = "GBP";
        BigDecimal transactionAmount = BigDecimal.valueOf(134.86);
        String oiSettlementCurrency = "USD";
        String clearingSystem = null;
        String transactionTypeIdentifier = null;

        // This function makes a GET call to the Conversion Rate Details endpoint
        ConversionRateDetailsApi conversionRateDetailsApi = new ConversionRateDetailsApi(apiClient);
        OriginatorSettlementCurrencyConversion conversionRateDetailsResponse = null;
```

11. You call the `getOriginatorConversionRate` function to make the API call to the `/transaction-settlement-rate-details` endpoint. For successful calls, you can access the individual response values using the `conversionRateDetailsResponse.get()` method.

```java
        System.out.println();
        System.out.println("GET call to the Conversion Rate Details endpoint...");
        System.out.println();
        try {
            conversionRateDetailsResponse = conversionRateDetailsApi.getOriginatorConversionRate(transactionDate, transactionCurrency, transactionAmount, oiSettlementCurrency, clearingSystem, transactionTypeIdentifier);
            System.out.println("Response:");
            System.out.println(conversionRateDetailsResponse);
        } catch (ApiException e) {
            System.err.println("Exception when calling conversionRateDetailsApi#getOriginatorConversionRate");
            System.err.println("Status code: " + e.getCode());
            System.err.println("Reason: " + e.getResponseBody());
            System.err.println("Response headers: " + e.getResponseHeaders());
            e.printStackTrace();
        }
```

##### Result {#result-2}

When you build and run `CurrConvOI.java` in the IntelliJ IDE, the successful API request produces the following response in the Run window.

    class OriginatorSettlementCurrencyConversion {
        requestInformation: class RequestInformation {
            name: oi-settlement-currency-conversion-rate
            description: Provides Originating Institution payment transaction currency conversion rates and Originating Institution's settlement amount
            requestDate: 2024-10-24 11:07:11 GMT
        }
        data: class OriginatorSettlementCurrencyConversionData {
            transactionDate: 2024-10-24
            clearingSystem: null
            transactionTypeIdentifier: null
            transactionCurrency: GBP
            transactionAmount: 134.86
            oiSettlementCurrency: USD
            oiSettlementAmount: 174.4744102
            conversionRate: 1.2937447
            conversionRateDate: 2024-10-23
        }
    }

## Make API Calls to Production {#make-api-calls-to-production}

You can make calls to the Production environment when you have registered for this service and Mastercard has configured that environment for your Production keys. You can adapt this tutorial code easily to call Production:

* Copy your Production signing key (.p12) file to the `./src/main/resources` folder.
* Update the consumer key and signing key values to match your .p12 file and the Production Credentials from your Mastercard Developers project.
* Adjust the base path to "https://api.mastercard.com/originator/payment-transaction".

You may need to adjust the code to pass request query values appropriate to the environment and your configuration.
