Emporix Java SDK
A comprehensive Java SDK for integrating with Emporix Commerce APIs.
Built for Spring Boot applications with powerful authentication management, type-safe API clients, and convenient token handling.
The Emporix Java SDK is available under emporix-sdk maven repository and provides:
Type-safe API clients for all Emporix services
Automatic Spring Boot configuration with
@EnableEmporixAutoConfigurationComprehensive token management with
EmporixTokenServiceAutomatic token caching and refresh for service tokens
Exception handling with Emporix error response parsing
Multi-credential support for multi-tenant scenarios
Prerequisites
Before you begin, ensure you have the following installed and configured:
Java 21 or higher
Spring Boot 3.x
Gradle 8.5+ or Maven 3.9+
Quick start
This quick start shows how to add the Emporix Java SDK to your Spring Boot project, enable auto-configuration, set up credentials, and run a first API call.
Enable the SDK by adding the annotation to your Spring Boot application
import io.emporix.config.EnableEmporixAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableEmporixAutoConfiguration // ← Add this
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}Configure your credentials
Recommended: Use environment variables
export EMPORIX_TENANT=your-tenant-id
export EMPORIX_API_CREDENTIALS_BACKEND_CLIENT_ID=your-backend-client-id
export EMPORIX_API_CREDENTIALS_BACKEND_SECRET=your-backend-secret
export EMPORIX_API_CREDENTIALS_STOREFRONT_CLIENT_ID=your-storefront-client-id
export EMPORIX_API_CREDENTIALS_STOREFRONT_SECRET=your-storefront-secretAlternatively, use the application.yml:
emporix:
tenant: your-tenant-id
api:
credentials:
backend:
client-id: your-backend-client-id
secret: your-backend-secret
storefront:
client-id: your-storefront-client-id
secret: your-storefront-secretUse the SDK in your code
import io.emporix.auth.service.EmporixTokenService;
import io.emporix.auth.dto.ServiceTokenResponse;
import io.emporix.product.ProductClient;
import io.emporix.product.dto.response.ProductResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ProductService {
@Autowired
private ProductClient productClient;
@Autowired
private EmporixTokenService tokenService;
public List<ProductResponse> getAllProducts() {
// 1. Get service token (with all available scopes)
ServiceTokenResponse token = tokenService.getServiceToken();
// 2. Get Bearer token (null-safe and idempotent)
String authorization = token.bearerAccessToken();
// 3. Call client with authorization
return productClient.getProducts(
null, null, null, 1, 20, "name:asc", true, "en", authorization
).getBody();
}
}Result: Setup is complete — the Emporix SDK is configured and working in your application.
Configuration
The SDK is configured through application.yml, application.properties, or environment variables.
Complete configuration example:
Property details
emporix.tenant
Yes
-
Your Emporix tenant name. All API requests are scoped to this tenant.
emporix.api.host
No
https://api.emporix.io
Base URL for Emporix API.
emporix.api.credentials.backend.client-id
Yes
-
OAuth2 client ID for backend operations (service tokens).
emporix.api.credentials.backend.secret
Yes
-
OAuth2 client secret for backend operations.
emporix.api.credentials.storefront.client-id
Yes
-
OAuth2 client ID for storefront operations (customer/anonymous tokens).
emporix.api.credentials.storefront.secret
Yes
-
OAuth2 client secret for storefront operations.
emporix.api.credentials.custom.*
No
-
Additional custom credential sets for integration scenarios.
emporix.api.timeouts.connect-timeout-ms
No
10000
Connection timeout in milliseconds (time to establish connection).
emporix.api.timeouts.read-timeout-ms
No
60000
Read timeout in milliseconds (time to wait for response data).
emporix.api.timeouts.connection-request-timeout-ms
No
5000
Connection request timeout in milliseconds (time to wait for connection from pool).
emporix.cache.enabled
No
true
Enable/disable token caching using Caffeine.
emporix.cache.max-size
No
1000
Maximum number of tokens to cache.
emporix.cache.expiration-buffer-seconds
No
60
Seconds before expiration to consider token expired (safety buffer).
emporix.cache.service-token-max-age-seconds
No
60
Maximum age for cached service tokens in seconds.
emporix.cache.max-lifetime-seconds
No
3600
Maximum lifetime for any cached token in seconds (Caffeine expireAfterWrite).
emporix.exception-handler.enabled
No
false
Enable automatic exception handling for Emporix API errors.
Environment variables
All properties can be set via environment variables (recommended for production):
Enabling the SDK
The SDK provides two usage modesL DTOs only and full SDK.
DTOs only - with no configuration
Simply add the SDK as a dependency to use the data transfer objects (DTOs). No additional configuration needed.
Full SDK - with auto-configuration
To enable API clients and authentication services, add the annotation:
This automatically configures:
All API clients (ProductClient, CategoryClient, PriceClient, etc.)
Token management (EmporixTokenService)
Token caching with automatic refresh
Exception handling (EmporixErrorHandler)
All required Spring beans
Available services
The SDK provides type-safe clients for the following Emporix services:
Product & catalog
Product
ProductClient
Product management
CRUD, bulk operations, search, filtering
Product Template
ProductTemplateClient
Product templates
Manage product templates
Product Recalculation Jobs
RecalculationJobClient
Dynamic variant recalculation jobs
Trigger recalculation, list jobs, get job
Brand
BrandClient
Brand management
CRUD for brands
Catalog
CatalogClient
Catalog management
Manage catalogs
Category
Category
CategoryClient
Category hierarchy
Create, update, manage hierarchy
Category Assignment
CategoryAssignmentClient
Product-category links
Assign products to categories
Category Tree
CategoryTreeClient
Tree navigation
Retrieve category trees
Price
Price
PriceClient
Price management
Create, update prices
Price List
PriceListClient
Price lists
Manage price lists
Price List Price
PriceListPriceClient
Price list entries
Manage prices in lists
Price Model
PriceModelClient
Pricing strategies
Configure pricing models
Price Match
PriceMatchClient
Price calculation
Calculate best prices
Cart & checkout
Cart
CartClient
Shopping cart management
Create, update, retrieve carts
Cart Items
CartItemsClient
Cart item operations
Add, update, remove cart items
Cart Discount
CartDiscountClient
Cart-level discounts
Apply and manage cart discounts
Checkout
CheckoutClient
Checkout process
Process checkouts, create orders
Order
Order
OrderClient
Order operations
Retrieve, update orders
Order Management
OrderManagementClient
Order administration
Full order lifecycle management
Availability
Availability
AvailabilityClient
Product availability
Create, upsert, delete, get, and search entries
Customer
Customer
CustomerClient
Customer operations
Retrieve customer data
Customer Management
CustomerManagementClient
Customer administration
Create, update, delete customers
Customer Address
CustomerAddressClient
Customer addresses
Retrieve customer addresses
Customer Address Mgmt
CustomerAddressManagementClient
Address administration
Create, update, delete addresses
Customer Credentials
CustomerCredentialsClient
Password & email management
Password reset, email change
Customer Double Opt-In
CustomerDoubleOptInClient
Email verification
Manage double opt-in flow
Company (B2B)
Legal Entity
LegalEntityClient
B2B company management
Create, update legal entities
Location
LocationClient
Company locations
Manage business locations
Contact Assignment
ContactAssignmentClient
Contact relationships
Assign contacts to entities
Shipping
Shipping Methods
ShippingMethodsClient
Shipping methods
Manage shipping methods
Shipping Zones
ShippingZonesClient
Shipping zones
Define shipping zones
Shipping Groups
ShippingGroupsClient
Shipping groups
Manage shipping groups
Shipping Cost
ShippingCostClient
Shipping cost calculation
Calculate shipping costs
Customer Group Relations
CustomerGroupRelationsClient
Customer group mappings
Manage customer group relations
Delivery Windows
DeliveryWindowsClient
Delivery time windows
Define delivery windows
Delivery Sites
DeliverySitesClient
Delivery locations
Manage delivery sites
Delivery Cycles
DeliveryCyclesClient
Delivery cycles
Manage delivery cycles
Delivery Times Management
DeliveryTimesManagementClient
Delivery times administration
Manage delivery times
Delivery Times Slots Mgmt
DeliveryTimesSlotsManagementClient
Delivery time slots
Manage delivery time slots
Coupon
Coupon Management
CouponManagementClient
Coupon administration
Create, update, delete coupons
Coupon Redemption
CouponRedemptionClient
Coupon usage
Redeem and manage coupon usage
Coupon Validation
CouponValidationClient
Coupon validation
Validate coupon eligibility
Referral Coupon Management
ReferralCouponManagementClient
Referral coupons
Manage referral coupon programs
Tax
Tax
TaxClient
Tax configuration
Manage tax settings, calculate taxes
Configuration
Configuration
ConfigurationClient
Tenant configuration
Tenant settings
Client Configuration
ClientConfigurationClient
Client-scoped config
Client-specific settings
Session context
Session Context
SessionContextClient
Session management
Manage session context
Own Session Context
OwnSessionContextClient
Own session operations
Manage own session context
Authentication
The SDK provides comprehensive token management through EmporixTokenService and direct client invocation patterns.
Scope constants
All API clients provide scope constants through a nested Scopes interface.
Example:
Benefits:
Type safety - compile-time errors for typos
IDE autocomplete - discover available scopes
Refactoring support - rename scopes safely
Documentation - JavaDoc for each scope
Authentication overview
Emporix supports several token types:
Service Token
Backend operations, admin tasks
backend credentials
tokenService.getServiceToken()
Scoped Service Token
Backend with specific permissions
backend credentials
tokenService.getServiceToken(Set.of(SCOPES))
Custom Service Token
Integration/partner with full access
custom credentials
tokenService.getServiceToken("integration")
Custom Scoped Token
Integration/partner with limited scopes
custom credentials
tokenService.getServiceToken(Set.of(SCOPES), "integration")
Customer Token
Authenticated user operations
storefront credentials
tokenService.getCustomerToken(email, password, anonymousToken)
Anonymous Token
Guest browsing, public access
storefront credentials
tokenService.getAnonymousToken()
B2B Token
Business customer operations
storefront credentials
tokenService.getB2bToken(customerToken, legalEntityId)
Token caching
The SDK automatically caches service and custom credential tokens for optimal performance:
Service tokens - Cached by scope set AND credential name, auto-refreshed on expiration
Custom credential tokens - Each credential set has its own cache
Customer tokens - NOT cached (managed by your application)
Anonymous tokens - NOT cached (each user needs unique token)
Token management
The SDK uses a direct token management approach. All API clients accept an authorization header parameter (typically the last parameter in each method). You obtain tokens using EmporixTokenService and pass them to client methods.
Basic token flow
Example:
Using service tokens - backend operations
Service tokens are used for backend/administrative operations and are automatically cached by the SDK.
Available Methods:
getServiceToken()- Get token with all available scopes (simplest, recommended for most cases)getServiceToken(Set<String> scopes)- Get token with specific scopes (least privilege principle)getServiceToken(String credentialName)- Get token with custom credentials and all scopesgetServiceToken(Set<String> scopes, String credentialName)- Get token with custom credentials and specific scopes
Example: Service token usage
Using custom credentials
Custom credentials are additional OAuth2 clients configured in Emporix with specific scopes. Use them for:
External integrations with limited permissions
Partner access with read-only or specific operations
Third-party systems that need controlled access
Configuration for custom credentials:
Using anonymous tokens - guest browsing
Anonymous tokens are used for public/guest browsing sessions.
Using customer tokens - authenticated users
Customer tokens are for authenticated user operations. The SDK automatically preserves shopping sessions when logging in.
Available Methods:
getCustomerToken(email, password, AnonymousTokenResponse)- Login with anonymous token object RecommendedgetCustomerToken(email, password, String)- Login with anonymous bearer string RecommendedgetCustomerToken(email, password)- Works but creates new session Loses cart/session context
Typical Flow:
Token cache management
The SDK automatically caches service tokens for performance. You can clear the cache when needed:
Usage examples
Example 1: Product management
Example 2: Category management
Example 3: Multi-client operations with custom credentials
This example shows how to use multiple OAuth2 clients (configured in Emporix) with different permission levels.
Configuration:
Each custom credential corresponds to an OAuth2 client configured in your Emporix tenant with specific scopes.
Example 4: REST controller
Advanced configuration
Custom client beans
Override default client configuration by providing your own beans:
ClientConfig options
Custom REST client with timeout
Modern Apache HttpClient 5.6+ approach with custom timeouts:
Key points:
Uses Apache HttpClient 5.6+ (no deprecated APIs)
ConnectionConfigfor connection-level timeouts (connect, socket)RequestConfigfor request-level timeouts (connection request, response)PoolingHttpClientConnectionManagerfor better connection pooling control
Multi-tenant support
The SDK supports running multiple Emporix tenants within a single JVM. This is useful when your application needs to communicate with different Emporix environments (e.g., QA, staging, production) or different tenant accounts simultaneously.
When additional tenants are configured, the SDK automatically creates a full bean stack for each tenant — including EmporixProperties, EmporixClientFactory, EmporixTokenService, and all API clients. These beans are injected using Spring's @Qualifier annotation with the tenant key as the qualifier value.
The default tenant (configured under emporix.*) remains the unqualified default and does not require @Qualifier for injection.
Configuration
Define additional tenants under emporix.tenants.<key> in your application.yml. Each <key> becomes the @Qualifier value used to inject that tenant's beans:
Or via environment variables:
Injecting tenant-specific beans
Use @Qualifier("<key>") to inject the bean stack for a specific tenant. Without @Qualifier, the default tenant beans are injected:
All SDK clients are available per tenant — ProductClient, CategoryClient, CartClient, OrderClient, CustomerClient, and every other registered client. Simply use @Qualifier("<key>") on any of them.
Property inheritance and overrides
Each tenant configuration inherits from the default configuration. You only need to specify properties that differ from the defaults:
tenant
No (must be specified)
Required per tenant
api.host
Yes
Yes
api.credentials.backend
No (must be specified)
Required per tenant
api.credentials.storefront
No (must be specified)
Required per tenant
api.credentials.custom.*
Yes
Yes
api.timeouts.*
Yes
Yes
cache.*
Yes
Yes
If all tenants share the same timeout and cache settings, you only need to define them once in the default section.
Custom credentials per tenant
Custom credentials can be defined per tenant. If a tenant does not define its own custom credentials, it falls back to the default custom credentials:
Usage in code:
Validation rules
The SDK validates multi-tenant configuration at startup and will fail fast with descriptive error messages if any rule is violated:
Default tenant is always required —
emporix.tenantmust be specified even when additional tenants are configured.No duplicate tenant IDs — the default tenant ID must not appear as a key or
tenantvalue inemporix.tenants.All tenant IDs must be unique — no two entries in
emporix.tenantscan resolve to the same tenant ID.Backend and storefront credentials are required per tenant entry.
Overriding default beans
Multi-tenant support is designed to be non-intrusive. SDK users can still override default beans using @Primary as before:
Exception handling
Global exception handler
Enable automatic exception handling:
This provides automatic handling of:
EmporixApiException- Emporix API errorsStandard HTTP errors (400, 401, 403, 404, 500, etc.)
Validation errors
Structured error responses
Manual exception handling
Best practices
Use appropriate scopes
Choose the right method based on your security requirements:
Recommended: For specific operations (least privilege):
For full backend access (simpler, when you need multiple operations):
Avoid: requesting all scopes when you only need one:
When to use each:
Use
getServiceToken()for internal backend services that perform multiple operationsUse
getServiceToken(Set.of(SCOPES))for external integrations or when following strict least-privilege security
Preserve anonymous tokens on login
Always pass the anonymous token when logging in customers to preserve shopping cart and session.
Recommended:
Avoid: (loses session context):
Reuse service tokens
Service tokens are automatically cached by the SDK. Reuse the same EmporixTokenService instance.
Recommended:
Handle errors gracefully
Always handle API exceptions appropriately.
Recommended:
Use custom credentials for integrations and partners
Leverage custom credentials (separate OAuth2 clients configured in Emporix) for integrations, partners, or systems with limited permissions.
Recommended:
Each custom credential corresponds to an OAuth2 client created in your Emporix tenant with specific scopes.
Manage customer tokens in your application
The SDK does NOT cache customer tokens. Store them securely in your application.
Recommended:
Recommended:
Enable token caching
Keep token caching enabled in production for better performance.
Troubleshooting
Check the solutions for the most common issues.
Issue: "Bean of type ProductClient could not be found"
Cause: SDK auto-configuration is not enabled.
Solution: Add @EnableEmporixAutoConfiguration to your main application class:
Issue: "401 Unauthorized"
Possible Causes:
Invalid credentials
Missing or malformed authorization header
Expired token
Token with insufficient scopes
Solutions:
Verify credentials in Emporix Portal
Check environment variables are set correctly:
Ensure you're passing the authorization header:
Issue: "Tenant must be configured"
Cause: Missing tenant configuration.
Solution: Set tenant via environment variable or application.yml:
Or:
Issue: "Custom credentials 'xxx' not found"
Cause: Requesting a token with custom credential name that doesn't exist in configuration.
Example Error:
Solution: Configure custom credentials in application.yml:
Important: The OAuth2 client must also be created in your Emporix tenant with appropriate scopes assigned.
Issue: "403 Forbidden" or "Insufficient Scopes"
Cause: Token doesn't have required OAuth2 scopes for the operation.
Solutions:
Request token with appropriate scopes:
Verify credentials in Emporix Portal have the required scopes.
Check if you need to use custom credentials with different scope permissions.
Token caching not working
Symptom: Every request creates a new token.
Solution: Service tokens are automatically cached. If you're seeing new tokens:
Check if you're requesting different scopes (each scope set gets its own cache entry).
Check if you're using different credential names.
Customer and anonymous tokens are NOT cached by design.
Debugging tips
Enable debug logging:
Clear token cache:
Inspect token details:
Last updated
Was this helpful?

