# Com / Github / Blaxk3 / Api

## Overview

The `com.github.blaxk3.api` package contains a small API client wrapper for working with currency exchange rates. It appears to centralize three concerns: loading an API key from application resources, building requests to the ExchangeRate API, and extracting currency data or conversion results from the returned JSON.

In practice, this module acts as a thin integration layer between the application and the external currency-rate service. It keeps the HTTP and JSON parsing logic in one place so callers only need to ask for supported currency codes or perform a conversion.

## Key Classes and Interfaces

### [`CurrencyRateAPI`](src/main/java/com/github/blaxk3/api/CurrencyRateAPI.java:19)

This is the only class in the package and the core of the module. It encapsulates all access to the external exchange-rate service and exposes a few convenience methods for common operations.

The class is intentionally lightweight: it does not define a separate service interface, DTO layer, or repository abstraction. Instead, it directly handles resource loading, HTTP requests, and JSON parsing in one place. That makes the module easy to use, but also means callers rely on this class for both transport concerns and data extraction.

#### Responsibilities

- Load an `API_KEY` value from `config.properties` on the classpath.
- Build base and endpoint URLs for the ExchangeRate API.
- Make GET requests and parse JSON responses.
- Extract supported currency codes from the `conversion_rates` object.
- Extract a currency conversion result for a requested currency pair and amount.

#### Key methods

##### [`getApiKeyService()`](src/main/java/com/github/blaxk3/api/CurrencyRateAPI.java:23)

Loads `config.properties` from the classpath and returns the `API_KEY` property.

- **Parameters:** none
- **Returns:** the API key as a `String`, or `null` if the file cannot be found or loaded
- **Behavior and side effects:**
  - Uses the class loader to open `config.properties`
  - Logs an error if the file is missing or if an `IOException` occurs
  - Closes the resource automatically with try-with-resources

This method is the module's credential source. If the property file is absent or malformed, downstream URL construction will still proceed, but requests will likely fail because the base URL will contain a missing key.

##### [`getURL()`](src/main/java/com/github/blaxk3/api/CurrencyRateAPI.java:38)

Builds the base ExchangeRate API URL using the loaded API key.

- **Parameters:** none
- **Returns:** a `String` such as `https://v6.exchangerate-api.com/v6/<API_KEY>`
- **Behavior and side effects:** none beyond calling `getApiKeyService()`

This is a convenience method used by the request-building methods. It does not validate whether the key was actually found.

##### [`getJsonObject(URL url)`](src/main/java/com/github/blaxk3/api/CurrencyRateAPI.java:42)

Performs an HTTP GET request and parses the response body into a `JsonObject`.

- **Parameters:**
  - `URL url` — the fully qualified endpoint to request
- **Returns:** a `JsonObject` on HTTP 200 OK, or `null` on failure
- **Behavior and side effects:**
  - Opens a `HttpURLConnection`
  - Sets the method to `GET`
  - Checks the response code before parsing
  - Uses `JsonParser.parseReader(...)` on the response content stream
  - Logs an error for non-200 responses and for unexpected exceptions

This is the module's main transport helper. It is shared by the higher-level operations and is responsible for converting raw HTTP responses into JSON.

##### [`getCurrencyCode()`](src/main/java/com/github/blaxk3/api/CurrencyRateAPI.java:61)

Fetches the latest USD-based rates and returns the available currency codes.

- **Parameters:** none
- **Returns:** a `String[]` of currency codes, or `null` if the response does not contain `conversion_rates` or if the request fails
- **Throws:**
  - `MalformedURLException`
  - `URISyntaxException`
- **Behavior and side effects:**
  - Builds a URL for `/latest/USD`
  - Calls `getJsonObject(...)`
  - Looks for a `conversion_rates` object in the response
  - Returns the key set of that object as an array

This method appears to be used as a discovery endpoint for UI or workflow code that needs a list of supported currencies. It assumes that USD is a suitable base currency for enumerating the available codes.

##### [`convert(String foreignCurrency1, String foreignCurrency2, BigDecimal amount)`](src/main/java/com/github/blaxk3/api/CurrencyRateAPI.java:72)

Requests a conversion result for a specific currency pair and amount.

- **Parameters:**
  - `foreignCurrency1` — source currency code
  - `foreignCurrency2` — target currency code
  - `amount` — amount to convert
- **Returns:** the `conversion_result` value as a `String`
- **Throws:**
  - `MalformedURLException`
  - `URISyntaxException`
- **Behavior and side effects:**
  - Builds a `/pair/{from}/{to}/{amount}` URL
  - Calls `getJsonObject(...)`
  - Reads the `conversion_result` field directly from the parsed JSON

This method is the primary conversion API for callers. It does not validate the response before dereferencing `conversion_result`, so callers should be prepared for runtime failures if the service returns an unexpected payload or if the request fails.

## How It Works

The module follows a simple request flow:

1. A caller asks for the API base URL or a higher-level operation such as currency code lookup or conversion.
2. `CurrencyRateAPI` loads the API key from `config.properties` through `getApiKeyService()`.
3. It combines the key with the ExchangeRate API base host in `getURL()`.
4. Higher-level methods append a specific endpoint path such as `/latest/USD` or `/pair/...`.
5. `getJsonObject(URL)` opens the HTTP connection, sends a GET request, and parses the JSON response.
6. The caller receives either extracted values from the JSON or `null` if the response could not be processed.

A simplified view of the relationships is shown below.

```mermaid
flowchart LR
Caller["Caller"] --> API["CurrencyRateAPI"]
API --> Config["config.properties"]
API --> Exchange["ExchangeRate API v6"]
API --> Result["JSON response data"]
```

### Request sequence

```mermaid
sequenceDiagram
participant C as Caller
participant API as CurrencyRateAPI
participant CFG as config.properties
participant EXT as ExchangeRate API v6
C->>API: getApiKeyService
API->>CFG: load API_KEY
C->>API: getCurrencyCode
API->>EXT: request latest USD rates
EXT->>API: JSON response
API->>C: currency codes
```

## Data Model

This module does not define its own domain objects, DTOs, or entities. Instead, it works with:

- `Properties` for configuration data
- `JsonObject` and `JsonElement` for parsed API responses
- `String[]` for currency code lists
- `String` for conversion output values
- `BigDecimal` for the conversion amount input

The implicit data contract comes from the remote ExchangeRate API response shape. The code expects at least these JSON fields:

- `conversion_rates` for the supported currency lookup path
- `conversion_result` for conversion output

Because the JSON structure is assumed rather than modeled locally, the module is sensitive to changes in the external API response format.

## Dependencies and Integration

### External libraries

The class imports and uses:

- **Gson** (`JsonElement`, `JsonObject`, `JsonParser`) for JSON parsing
- **SLF4J** (`Logger`, `LoggerFactory`) for logging
- **Java standard library** networking and I/O classes such as `URL`, `HttpURLConnection`, `InputStream`, and `Properties`
- **`BigDecimal`** for precise conversion amounts

### External service

The module integrates with the **ExchangeRate API v6** at `https://v6.exchangerate-api.com/v6/`.

The service is used in two patterns:

- `/latest/USD` to retrieve the available currency codes
- `/pair/{from}/{to}/{amount}` to retrieve a conversion result

### Configuration

The API key is read from a classpath resource named `config.properties` with the property name `API_KEY`.

This means the module depends on runtime packaging or test setup to provide that file. If the file is missing, `getApiKeyService()` returns `null` and logs an error.

## Notes for Developers

- **Handle null results defensively.** Several methods return `null` on failure, and `convert(...)` does not guard against a null JSON response before accessing `conversion_result`.
- **Treat the API key as required configuration.** Without `config.properties` and `API_KEY`, requests are unlikely to succeed.
- **The module mixes transport and parsing concerns.** If you need richer error handling or testability, this class would be a natural candidate for refactoring into smaller pieces.
- **`getCurrencyCode()` assumes USD as the base currency.** If the service contract or product requirements change, this base currency may need to become configurable.
- **The conversion result is returned as a string.** Callers that need numeric behavior may need to parse or normalize that value themselves.
- **Exceptions are only partially handled internally.** The helper method catches broad exceptions, but the public methods still declare URL/URI-related exceptions and may fail at runtime if the response shape is unexpected.

## Summary

`com.github.blaxk3.api` is a focused integration package that wraps a third-party exchange-rate service behind a small set of helper methods. It is useful as a centralized point for API key handling, request construction, JSON parsing, and currency conversion lookups.