Web SDK API Reference
Introduction
The Web SDK provides a comprehensive interface for interacting with our platform directly from your web applications. It allows for seamless integration of our services, including user authentication, data management, and real-time event handling.
This document details all available methods, their parameters, return values, and usage examples.
Getting Started
To begin, include the SDK script in your HTML file:
<script src="https://cdn.example.com/web-sdk/v1.2.0/sdk.min.js"></script>
Then, initialize the SDK with your application's credentials.
Core API
initinit(config)
Initializes the Web SDK with the provided configuration object.
Parameters
config
(Object): An object containing SDK initialization options.apiKey
(String, required): Your unique API key.baseUrl
(String, optional): The base URL for API requests. Defaults to the official service URL.debug
(Boolean, optional): Enables or disables debug logging. Defaults tofalse
.
Returns
Promise<void>
: A promise that resolves when the SDK is successfully initialized.
import { init } from 'web-sdk'; // If using modules
// Or globally:
// const { init } = window.WebSDK;
init({
apiKey: 'YOUR_API_KEY',
debug: true
}).then(() => {
console.log('SDK initialized successfully!');
}).catch(error => {
console.error('SDK initialization failed:', error);
});
authenticateauthenticate(credentials)
Authenticates the user with the provided credentials.
Parameters
credentials
(Object): An object containing user credentials.username
(String, required): The user's username.password
(String, required): The user's password.
Returns
Promise<Object>
: A promise that resolves with user authentication details (e.g., token, user info) upon successful authentication.
import { authenticate } from 'web-sdk';
authenticate({ username: 'user@example.com', password: 'password123' })
.then(userInfo => {
console.log('Authentication successful:', userInfo);
})
.catch(error => {
console.error('Authentication failed:', error);
});
getUserDatagetUserData()
Retrieves the currently authenticated user's data.
Returns
Promise<Object>
: A promise that resolves with the user's profile data.
import { getUserData } from 'web-sdk';
getUserData()
.then(data => {
console.log('User data:', data);
})
.catch(error => {
console.error('Failed to fetch user data:', error);
});
logoutlogout()
Logs out the currently authenticated user and clears session data.
Returns
Promise<void>
: A promise that resolves when the user is successfully logged out.
import { logout } from 'web-sdk';
logout()
.then(() => {
console.log('User logged out successfully.');
})
.catch(error => {
console.error('Logout failed:', error);
});
Resource Management
Manage various resources within the platform.
createResourcecreateResource(type, data)
Creates a new resource of the specified type with the given data.
Parameters
type
(String, required): The type of resource to create (e.g., 'users', 'projects').data
(Object, required): The data for the new resource.
Returns
Promise<Object>
: A promise that resolves with the created resource's data, including its unique ID.
import { createResource } from 'web-sdk';
const newProject = {
name: 'My Awesome Project',
description: 'A project to showcase the SDK'
};
createResource('projects', newProject)
.then(project => {
console.log('Project created:', project);
})
.catch(error => {
console.error('Failed to create project:', error);
});
getResourcegetResource(type, id)
Retrieves a specific resource by its type and ID.
Parameters
type
(String, required): The type of resource.id
(String | Number, required): The unique identifier of the resource.
Returns
Promise<Object>
: A promise that resolves with the requested resource's data.
import { getResource } from 'web-sdk';
getResource('projects', 'proj_123abc')
.then(project => {
console.log('Project details:', project);
})
.catch(error => {
console.error('Failed to fetch project:', error);
});
updateResourceupdateResource(type, id, data)
Updates an existing resource with new data.
Parameters
type
(String, required): The type of resource.id
(String | Number, required): The unique identifier of the resource to update.data
(Object, required): The updated data for the resource.
Returns
Promise<Object>
: A promise that resolves with the updated resource's data.
import { updateResource } from 'web-sdk';
const updatedProjectData = {
description: 'Updated description for the awesome project'
};
updateResource('projects', 'proj_123abc', updatedProjectData)
.then(project => {
console.log('Project updated:', project);
})
.catch(error => {
console.error('Failed to update project:', error);
});
deleteResourcedeleteResource(type, id)
Deletes a resource by its type and ID.
Parameters
type
(String, required): The type of resource.id
(String | Number, required): The unique identifier of the resource to delete.
Returns
Promise<void>
: A promise that resolves when the resource is successfully deleted.
import { deleteResource } from 'web-sdk';
deleteResource('projects', 'proj_123abc')
.then(() => {
console.log('Project deleted successfully.');
})
.catch(error => {
console.error('Failed to delete project:', error);
});
listResourceslistResources(type, options)
Retrieves a list of resources of the specified type, with optional filtering and pagination.
Parameters
type
(String, required): The type of resource to list.options
(Object, optional): Options for filtering, sorting, and pagination.filter
(Object, optional): Criteria to filter resources.sort
(String, optional): Field to sort by. Prefix with '-' for descending order.limit
(Number, optional): Maximum number of resources to return.offset
(Number, optional): Number of resources to skip (for pagination).
Returns
Promise<Array<Object>>
: A promise that resolves with an array of resource objects.
import { listResources } from 'web-sdk';
// Get the first 10 projects, sorted by creation date
listResources('projects', { limit: 10, sort: 'createdAt' })
.then(projects => {
console.log('Projects:', projects);
})
.catch(error => {
console.error('Failed to list projects:', error);
});
// Get projects filtered by name
listResources('projects', { filter: { name: 'My Awesome Project' } })
.then(projects => {
console.log('Filtered projects:', projects);
})
.catch(error => {
console.error('Failed to list projects:', error);
});
Events
The SDK allows you to subscribe to real-time events emitted by the platform.
onon(eventName, handler)
Subscribes a handler function to a specific event.
Parameters
eventName
(String, required): The name of the event to subscribe to (e.g., 'resourceCreated', 'userLoggedIn').handler
(Function, required): The callback function to execute when the event is triggered. It receives event-specific data as an argument.
import { on } from 'web-sdk';
const handleProjectCreated = (projectData) => {
console.log('A new project was created:', projectData);
};
on('resourceCreated', handleProjectCreated);
// To unsubscribe later:
// off('resourceCreated', handleProjectCreated); // Assuming an 'off' method exists
Error Handling
All SDK methods return Promises. Errors during API calls or SDK operations will be rejected promises. It is recommended to use try...catch
blocks or .catch()
on your promises to handle potential errors gracefully.
Common error types include:
APIError
: Errors returned from the server (e.g., invalid credentials, resource not found).NetworkError
: Issues with the network connection.SDKError
: Errors related to the SDK's internal state or configuration.
async function fetchAndProcessResource(resourceId) {
try {
const resource = await getResource('items', resourceId);
console.log('Fetched:', resource);
// Process resource data
} catch (error) {
console.error('An error occurred:', error.message);
if (error.statusCode === 404) {
console.warn('Resource not found.');
}
}
}