Skip to main content

React Client SDK for Bookla

The Bookla React Client SDK provides a TypeScript/JavaScript interface for interacting with the Bookla Platform API. This SDK simplifies the integration of Bookla's booking system into your React applications by providing type-safe methods and intuitive abstractions.

Getting Started

Installation

First, install the SDK using npm:

npm install @bookla/react-client-sdk

Basic Setup

Initialize the SDK by creating an instance with your configuration. The SDK offers both US and EU endpoints to ensure optimal performance based on your location:

import { BooklaSDK } from '@bookla/react-client-sdk';

const sdk = new BooklaSDK({
// Choose the appropriate regional endpoint
apiUrl: 'https://us.bookla.com', // or 'https://eu.bookla.com'
apiKey: 'your-api-key',

// Optional configurations for fine-tuning behavior
timeout: 30000, // Request timeout in milliseconds
debug: false, // Enable debug logging for development

// Configure automatic retry behavior for transient failures
retry: {
maxAttempts: 3,
delayMs: 1000,
statusCodesToRetry: [408, 429, 500, 502, 503, 504]
}
});

Authentication

The SDK supports a token-based authentication system. You need to implement backend-to-backend authentication for your clients to obtain the necessary tokens. Here's how to manage authentication states:

// After successful client authentication, store the tokens
sdk.setAuthTokens({
accessToken: 'access-token',
refreshToken: 'refresh-token',
expiresAt: '2024-01-02T12:00:00Z'
});

// Check authentication status before operations
const authState = sdk.isAuthenticated();
if (authState.isAuthenticated) {
console.log('Session expires:', new Date(authState.expiresAt));
} else {
console.log('Need to authenticate');
}

// Clear authentication when logging out
sdk.clearAuth();

Core Features

Managing Bookings

The booking system is the heart of the SDK. Here's how to handle common booking operations:

// Create a new booking
const booking = await sdk.bookings.request({
companyID: 'company-id',
serviceID: 'service-id',
resourceID: 'resource-id',
startTime: '2024-01-02T10:00:00Z',
spots: 1,

// Pass guest client data if you don't need client authentication
// In this case, each booking will be associated with a new guest client
client: {
email: 'client@example.com',
firstName: 'John',
lastName: 'Doe'
}
});

// Retrieve a list of bookings
const bookings = await sdk.bookings.list();

// Get details of a specific booking
const bookingDetails = await sdk.bookings.get('booking-id');

// Cancel a booking with a reason
await sdk.bookings.cancel('booking-id', 'Schedule conflict');

Working with Services

Services represent the different offerings available for booking:

// Get all available services for a company
const services = await sdk.services.list('company-id');

// Get detailed information about a specific service
const service = await sdk.services.get('company-id', 'service-id');

// Check available time slots for a service
const availableTimes = await sdk.services.getTimes('company-id', 'service-id', {
from: '2024-01-02T00:00:00Z',
to: '2024-01-02T23:59:59Z',
duration: 'PT1H',
spots: 1
});

Managing Resources

Resources represent the bookable entities in your system:

// List all resources for a company
const resources = await sdk.resources.list('company-id');

// Get detailed information about a specific resource
const resource = await sdk.resources.get('company-id', 'resource-id');

Subscription Management

For businesses offering subscription-based services:

// View available subscription plans
const subscriptions = await sdk.subscriptions.getAvailableSubscriptions('company-id');

// Add subscriptions to shopping cart
await sdk.subscriptions.addToCart('company-id', {
items: [{ subscriptionID: 'subscription-id' }]
});

// View current cart contents
const cart = await sdk.subscriptions.getCart('company-id');

// Complete purchase
const purchase = await sdk.subscriptions.checkout('company-id');

// View purchase history
const purchases = await sdk.subscriptions.getPurchases('company-id');

Advanced Features

Request Cancellation

The SDK supports cancellation of in-flight requests, which is crucial for maintaining a responsive user interface:

// Create a cancellation token
const cancelToken = sdk.createCancelToken();

try {
// Use the token in a request
const bookings = await sdk.bookings.list({ cancelToken });

// Cancel the request if needed
cancelToken.cancel();
} catch (error) {
if (sdk.isCancelledError(error)) {
console.log('Request was cancelled');
}
}

Request/Response Interceptors

Interceptors allow you to modify requests and responses globally:

// Add custom headers to all requests
const removeRequestInterceptor = sdk.interceptors.request.use(async (config) => {
config.headers['Custom-Header'] = 'value';
return config;
});

// Process all responses
const removeResponseInterceptor = sdk.interceptors.response.use(async (response) => {
// Add custom processing here
return response;
});

// Clean up interceptors when no longer needed
removeRequestInterceptor();
removeResponseInterceptor();

Error Handling

The SDK provides structured error handling with specific error types:

try {
await sdk.bookings.request({
// Invalid booking parameters
});
} catch (error) {
if (error instanceof BooklaValidationError) {
// Handle validation errors
console.error('Invalid input:', error.details);
} else if (error instanceof BooklaError) {
// Handle API errors
console.error('API error:', {
message: error.message,
code: error.code,
status: error.status
});
} else {
// Handle unexpected errors
console.error('Unexpected error:', error);
}
}

TypeScript Integration

The SDK provides comprehensive TypeScript definitions for all its functionality:

import {
RequestBookingRequest,
BookingResponse,
ServiceType,
BookingStatus
} from '@bookla/react-client-sdk';

// All methods and properties are fully typed
const booking: BookingResponse = await sdk.bookings.get('booking-id');

License

This SDK is available under the MIT license, allowing for both personal and commercial use with appropriate attribution.