servicem8
v0.9.54
Published
Developer-friendly & type-safe Typescript SDK specifically catered to leverage *servicem8* API.
Readme
servicem8
Developer-friendly & type-safe Typescript SDK specifically catered to leverage servicem8 API.
Summary
ServiceM8 API: Move your app forward with the ServiceM8 API
Limits and Throttling
To ensure continuous quality of service, API usage can be subject to throttling. The throttle will be applied once an API consumer reaches a certain threshold in terms of a maximum number of requests per minute. Most clients will never hit this threshold, but those that do, will get met by a HTTP 429 Too Many Requests response code.
There is a limit of 180 requests per minute, if you reach this you will receive a HTTP 429 with a text body of "Number of allowed API requests per minute exceeded". There is a limit of 20000 requests per day, if you reach this you will receive a HTTP 429 with a text body of "Number of allowed API requests per day exceeded".
We encourage all API developers to anticipate this error, and take appropriate measures like e.g. using a cached value from a previous call, or passing on a message to the end user that gets subjected to this behaviour (if any).
Limits are per Addon per account.
Table of Contents
SDK Installation
The SDK can be installed with either npm, pnpm, bun or yarn package managers.
NPM
npm add servicem8PNPM
pnpm add servicem8Bun
bun add servicem8Yarn
yarn add servicem8[!NOTE] This package is published with CommonJS and ES Modules (ESM) support.
Model Context Protocol (MCP) Server
This SDK is also an installable MCP server where the various SDK methods are exposed as tools that can be invoked by AI applications.
Node.js v20 or greater is required to run the MCP server from npm.
Add the following server definition to your claude_desktop_config.json file:
{
"mcpServers": {
"ServiceM8": {
"command": "npx",
"args": [
"-y", "--package", "servicem8",
"--",
"mcp", "start",
"--api-key", "...",
"--oauth2", "..."
]
}
}
}Create a .cursor/mcp.json file in your project root with the following content:
{
"mcpServers": {
"ServiceM8": {
"command": "npx",
"args": [
"-y", "--package", "servicem8",
"--",
"mcp", "start",
"--api-key", "...",
"--oauth2", "..."
]
}
}
}You can also run MCP servers as a standalone binary with no additional dependencies. You must pull these binaries from available Github releases:
curl -L -o mcp-server \
https://github.com/{org}/{repo}/releases/download/{tag}/mcp-server-bun-darwin-arm64 && \
chmod +x mcp-serverIf the repo is a private repo you must add your Github PAT to download a release -H "Authorization: Bearer {GITHUB_PAT}".
{
"mcpServers": {
"Todos": {
"command": "./DOWNLOAD/PATH/mcp-server",
"args": [
"start"
]
}
}
}For a full list of server arguments, run:
npx -y --package servicem8 -- mcp start --helpRequirements
For supported JavaScript runtimes, please consult RUNTIMES.md.
SDK Example Usage
Example
import { ServiceM8 } from "servicem8";
const serviceM8 = new ServiceM8({
security: {
apiKey: process.env["SERVICEM8_API_KEY"] ?? "",
},
});
async function run() {
const result = await serviceM8.allocationWindows.listAllocationWindows();
console.log(result);
}
run();
Authentication
Per-Client Security Schemes
This SDK supports the following security schemes globally:
| Name | Type | Scheme | Environment Variable |
| -------- | ------ | ------------ | -------------------- |
| apiKey | apiKey | API key | SERVICEM8_API_KEY |
| oauth2 | oauth2 | OAuth2 token | SERVICEM8_OAUTH2 |
You can set the security parameters through the security optional parameter when initializing the SDK client instance. The selected scheme will be used by default to authenticate with the API for all operations that support it. For example:
import { ServiceM8 } from "servicem8";
const serviceM8 = new ServiceM8({
security: {
apiKey: process.env["SERVICEM8_API_KEY"] ?? "",
},
});
async function run() {
const result = await serviceM8.allocationWindows.listAllocationWindows();
console.log(result);
}
run();
Available Resources and Operations
allocationWindows
- listAllocationWindows - List all Allocation Windows
- createAllocationWindows - Create a new Allocation Window
- getAllocationWindows - Retrieve an Allocation Window
- updateAllocationWindows - Update an Allocation Window
- deleteAllocationWindows - Delete an Allocation Window
assets
- listAssets - List all Assets
- getAssets - Retrieve an Asset
- updateAssets - Update an Asset
- deleteAssets - Delete an Asset
assetTypeFields
- listAssetTypeFields - List all Asset Type Fields
- createAssetTypeFields - Create a new Asset Type Field
- getAssetTypeFields - Retrieve an Asset Type Field
- updateAssetTypeFields - Update an Asset Type Field
- deleteAssetTypeFields - Delete an Asset Type Field
assetTypes
- listAssetTypes - List all Asset Types
- createAssetTypes - Create a new Asset Type
- getAssetTypes - Retrieve an Asset Type
- updateAssetTypes - Update an Asset Type
- deleteAssetTypes - Delete an Asset Type
attachments
- listAttachments - List all Attachments
- createAttachments - Create a new Attachment
- getAttachments - Retrieve an Attachment
- updateAttachments - Update an Attachment
- deleteAttachments - Delete an Attachment
badges
- listBadges - List all Badges
- createBadges - Create a new Badge
- getBadges - Retrieve a Badge
- updateBadges - Update a Badge
- deleteBadges - Delete a Badge
bundles
- listBundles - List all Bundles
- createBundles - Create a new Bundle
- getBundles - Retrieve a Bundle
- updateBundles - Update a Bundle
- deleteBundles - Delete a Bundle
categories
- listCategories - List all Categories
- createCategories - Create a new Category
- getCategories - Retrieve a Category
- updateCategories - Update a Category
- deleteCategories - Delete a Category
clients
- listClients - List all Clients
- createClients - Create a new Client
- getClients - Retrieve a Client
- updateClients - Update a Client
- deleteClients - Delete a Client
companyContacts
- listCompanyContacts - List all Company Contacts
- createCompanyContacts - Create a new Company Contact
- getCompanyContacts - Retrieve a Company Contact
- updateCompanyContacts - Update a Company Contact
- deleteCompanyContacts - Delete a Company Contact
documentTemplates
- listDocumentTemplates - List all Document Templates
- createDocumentTemplates - Create a new Document Template
- getDocumentTemplates - Retrieve a Document Template
- updateDocumentTemplates - Update a Document Template
- deleteDocumentTemplates - Delete a Document Template
emailTemplates
- listEmailTemplates - List all Email Templates
- createEmailTemplates - Create a new Email Template
- getEmailTemplates - Retrieve an Email Template
- updateEmailTemplates - Update an Email Template
- deleteEmailTemplates - Delete an Email Template
feedback
- listFeedback - List all Feedback
- createFeedback - Create a new Feedback
- getFeedback - Retrieve a Feedback
- updateFeedback - Update a Feedback
- deleteFeedback - Delete a Feedback
formFields
- listFormFields - List all Form Fields
- createFormFields - Create a new Form Field
- getFormFields - Retrieve a Form Field
- updateFormFields - Update a Form Field
- deleteFormFields - Delete a Form Field
formResponses
- listFormResponses - List all Form Responses
- createFormResponses - Create a new Form Response
- getFormResponses - Retrieve a Form Response
- updateFormResponses - Update a Form Response
- deleteFormResponses - Delete a Form Response
forms
- listForms - List all Forms
- createForms - Create a new Form
- getForms - Retrieve a Form
- updateForms - Update a Form
- deleteForms - Delete a Form
inbox
- listInboxMessages - List inbox messages
- createInboxMessage - Create a new inbox message
- getInboxMessage - Get inbox message details
- markInboxMessageAsRead - Mark message as read
- archiveInboxMessage - Archive or unarchive message
- snoozeInboxMessage - Snooze or unsnooze message
- convertInboxMessageToJob - Convert message to job
- attachInboxMessageToJob - Attach message to existing job
- addNoteToInboxMessage - Add note to message
jobActivities
- listJobActivities - List all Job Activities
- createJobActivities - Create a new Job Activity
- getJobActivities - Retrieve a Job Activity
- updateJobActivities - Update a Job Activity
- deleteJobActivities - Delete a Job Activity
jobAllocations
- listJobAllocations - List all Job Allocations
- createJobAllocations - Create a new Job Allocation
- getJobAllocations - Retrieve a Job Allocation
- updateJobAllocations - Update a Job Allocation
- deleteJobAllocations - Delete a Job Allocation
jobChecklists
- listJobChecklists - List all Job Checklists
- createJobChecklists - Create a new Job Checklist
- getJobChecklists - Retrieve a Job Checklist
- updateJobChecklists - Update a Job Checklist
- deleteJobChecklists - Delete a Job Checklist
jobContacts
- listJobContacts - List all Job Contacts
- createJobContacts - Create a new Job Contact
- getJobContacts - Retrieve a Job Contact
- updateJobContacts - Update a Job Contact
- deleteJobContacts - Delete a Job Contact
jobMaterialBundles
- listJobMaterialBundles - List all Job Material Bundles
- createJobMaterialBundles - Create a new Job Material Bundle
- getJobMaterialBundles - Retrieve a Job Material Bundle
- updateJobMaterialBundles - Update a Job Material Bundle
- deleteJobMaterialBundles - Delete a Job Material Bundle
jobMaterials
- listJobMaterials - List all Job Materials
- createJobMaterials - Create a new Job Material
- getJobMaterials - Retrieve a Job Material
- updateJobMaterials - Update a Job Material
- deleteJobMaterials - Delete a Job Material
jobPayments
- listJobPayments - List all Job Payments
- createJobPayments - Create a new Job Payment
- getJobPayments - Retrieve a Job Payment
- updateJobPayments - Update a Job Payment
- deleteJobPayments - Delete a Job Payment
jobQueues
- listJobQueues - List all Job Queues
- createJobQueues - Create a new Job Queue
- getJobQueues - Retrieve a Job Queue
- updateJobQueues - Update a Job Queue
- deleteJobQueues - Delete a Job Queue
jobs
- listJobs - List all Jobs
- createJobs - Create a new Job
- getJobs - Retrieve a Job
- updateJobs - Update a Job
- deleteJobs - Delete a Job
jobTemplates
- listJobTemplates - List all Job Templates
- getJobTemplates - Retrieve a Job Template
- createJobFromTemplate - Create a job from a template
knowledgeArticles
- listKnowledgeArticles - List all Knowledge Articles
- createKnowledgeArticles - Create a new Knowledge Article
- getKnowledgeArticles - Retrieve a Knowledge Article
- updateKnowledgeArticles - Update a Knowledge Article
- deleteKnowledgeArticles - Delete a Knowledge Article
locations
- listLocations - List all Locations
- createLocations - Create a new Location
- getLocations - Retrieve a Location
- updateLocations - Update a Location
- deleteLocations - Delete a Location
materials
- listMaterials - List all Materials
- createMaterials - Create a new Material
- getMaterials - Retrieve a Material
- updateMaterials - Update a Material
- deleteMaterials - Delete a Material
notes
- listNotes - List all Notes
- createNotes - Create a new Note
- getNotes - Retrieve a Note
- updateNotes - Update a Note
- deleteNotes - Delete a Note
search
- generalSearch - Search across multiple object types
- objectSearch - Search within a specific object type
- jobEmbeddingSearch - Semantic search for jobs
securityRoles
- listSecurityRoles - List all Security Roles
- getSecurityRoles - Retrieve a Security Role
smsTemplates
- listSMSTemplates - List all SMS Templates
- createSMSTemplates - Create a new SMS Template
- getSMSTemplates - Retrieve a SMS Template
- updateSMSTemplates - Update a SMS Template
- deleteSMSTemplates - Delete a SMS Template
staffMembers
- listStaffMembers - List all Staff Members
- createStaffMembers - Create a new Staff Member
- getStaffMembers - Retrieve a Staff Member
- updateStaffMembers - Update a Staff Member
- deleteStaffMembers - Delete a Staff Member
staffMessages
- listStaffMessages - List all Staff Messages
- createStaffMessages - Create a new Staff Message
- getStaffMessages - Retrieve a Staff Message
- updateStaffMessages - Update a Staff Message
- deleteStaffMessages - Delete a Staff Message
suppliers
- listSuppliers - List all Suppliers
- createSuppliers - Create a new Supplier
- getSuppliers - Retrieve a Supplier
- updateSuppliers - Update a Supplier
- deleteSuppliers - Delete a Supplier
tasks
- listTasks - List all Tasks
- createTasks - Create a new Task
- getTasks - Retrieve a Task
- updateTasks - Update a Task
- deleteTasks - Delete a Task
taxRates
- listTaxRates - List all Tax Rates
- createTaxRates - Create a new Tax Rate
- getTaxRates - Retrieve a Tax Rate
- updateTaxRates - Update a Tax Rate
- deleteTaxRates - Delete a Tax Rate
vendors
- listVendors - List all Vendors
- getVendors - Retrieve a Vendor
Standalone functions
All the methods listed above are available as standalone functions. These functions are ideal for use in applications running in the browser, serverless runtimes or other environments where application bundle size is a primary concern. When using a bundler to build your application, all unused functionality will be either excluded from the final bundle or tree-shaken away.
To read more about standalone functions, check FUNCTIONS.md.
allocationWindowsCreateAllocationWindows- Create a new Allocation WindowallocationWindowsDeleteAllocationWindows- Delete an Allocation WindowallocationWindowsGetAllocationWindows- Retrieve an Allocation WindowallocationWindowsListAllocationWindows- List all Allocation WindowsallocationWindowsUpdateAllocationWindows- Update an Allocation WindowassetsDeleteAssets- Delete an AssetassetsGetAssets- Retrieve an AssetassetsListAssets- List all AssetsassetsUpdateAssets- Update an AssetassetTypeFieldsCreateAssetTypeFields- Create a new Asset Type FieldassetTypeFieldsDeleteAssetTypeFields- Delete an Asset Type FieldassetTypeFieldsGetAssetTypeFields- Retrieve an Asset Type FieldassetTypeFieldsListAssetTypeFields- List all Asset Type FieldsassetTypeFieldsUpdateAssetTypeFields- Update an Asset Type FieldassetTypesCreateAssetTypes- Create a new Asset TypeassetTypesDeleteAssetTypes- Delete an Asset TypeassetTypesGetAssetTypes- Retrieve an Asset TypeassetTypesListAssetTypes- List all Asset TypesassetTypesUpdateAssetTypes- Update an Asset TypeattachmentsCreateAttachments- Create a new AttachmentattachmentsDeleteAttachments- Delete an AttachmentattachmentsGetAttachments- Retrieve an AttachmentattachmentsListAttachments- List all AttachmentsattachmentsUpdateAttachments- Update an AttachmentbadgesCreateBadges- Create a new BadgebadgesDeleteBadges- Delete a BadgebadgesGetBadges- Retrieve a BadgebadgesListBadges- List all BadgesbadgesUpdateBadges- Update a BadgebundlesCreateBundles- Create a new BundlebundlesDeleteBundles- Delete a BundlebundlesGetBundles- Retrieve a BundlebundlesListBundles- List all BundlesbundlesUpdateBundles- Update a BundlecategoriesCreateCategories- Create a new CategorycategoriesDeleteCategories- Delete a CategorycategoriesGetCategories- Retrieve a CategorycategoriesListCategories- List all CategoriescategoriesUpdateCategories- Update a CategoryclientsCreateClients- Create a new ClientclientsDeleteClients- Delete a ClientclientsGetClients- Retrieve a ClientclientsListClients- List all ClientsclientsUpdateClients- Update a ClientcompanyContactsCreateCompanyContacts- Create a new Company ContactcompanyContactsDeleteCompanyContacts- Delete a Company ContactcompanyContactsGetCompanyContacts- Retrieve a Company ContactcompanyContactsListCompanyContacts- List all Company ContactscompanyContactsUpdateCompanyContacts- Update a Company ContactdocumentTemplatesCreateDocumentTemplates- Create a new Document TemplatedocumentTemplatesDeleteDocumentTemplates- Delete a Document TemplatedocumentTemplatesGetDocumentTemplates- Retrieve a Document TemplatedocumentTemplatesListDocumentTemplates- List all Document TemplatesdocumentTemplatesUpdateDocumentTemplates- Update a Document TemplateemailTemplatesCreateEmailTemplates- Create a new Email TemplateemailTemplatesDeleteEmailTemplates- Delete an Email TemplateemailTemplatesGetEmailTemplates- Retrieve an Email TemplateemailTemplatesListEmailTemplates- List all Email TemplatesemailTemplatesUpdateEmailTemplates- Update an Email TemplatefeedbackCreateFeedback- Create a new FeedbackfeedbackDeleteFeedback- Delete a FeedbackfeedbackGetFeedback- Retrieve a FeedbackfeedbackListFeedback- List all FeedbackfeedbackUpdateFeedback- Update a FeedbackformFieldsCreateFormFields- Create a new Form FieldformFieldsDeleteFormFields- Delete a Form FieldformFieldsGetFormFields- Retrieve a Form FieldformFieldsListFormFields- List all Form FieldsformFieldsUpdateFormFields- Update a Form FieldformResponsesCreateFormResponses- Create a new Form ResponseformResponsesDeleteFormResponses- Delete a Form ResponseformResponsesGetFormResponses- Retrieve a Form ResponseformResponsesListFormResponses- List all Form ResponsesformResponsesUpdateFormResponses- Update a Form ResponseformsCreateForms- Create a new FormformsDeleteForms- Delete a FormformsGetForms- Retrieve a FormformsListForms- List all FormsformsUpdateForms- Update a ForminboxAddNoteToInboxMessage- Add note to messageinboxArchiveInboxMessage- Archive or unarchive messageinboxAttachInboxMessageToJob- Attach message to existing jobinboxConvertInboxMessageToJob- Convert message to jobinboxCreateInboxMessage- Create a new inbox messageinboxGetInboxMessage- Get inbox message detailsinboxListInboxMessages- List inbox messagesinboxMarkInboxMessageAsRead- Mark message as readinboxSnoozeInboxMessage- Snooze or unsnooze messagejobActivitiesCreateJobActivities- Create a new Job ActivityjobActivitiesDeleteJobActivities- Delete a Job ActivityjobActivitiesGetJobActivities- Retrieve a Job ActivityjobActivitiesListJobActivities- List all Job ActivitiesjobActivitiesUpdateJobActivities- Update a Job ActivityjobAllocationsCreateJobAllocations- Create a new Job AllocationjobAllocationsDeleteJobAllocations- Delete a Job AllocationjobAllocationsGetJobAllocations- Retrieve a Job AllocationjobAllocationsListJobAllocations- List all Job AllocationsjobAllocationsUpdateJobAllocations- Update a Job AllocationjobChecklistsCreateJobChecklists- Create a new Job ChecklistjobChecklistsDeleteJobChecklists- Delete a Job ChecklistjobChecklistsGetJobChecklists- Retrieve a Job ChecklistjobChecklistsListJobChecklists- List all Job ChecklistsjobChecklistsUpdateJobChecklists- Update a Job ChecklistjobContactsCreateJobContacts- Create a new Job ContactjobContactsDeleteJobContacts- Delete a Job ContactjobContactsGetJobContacts- Retrieve a Job ContactjobContactsListJobContacts- List all Job ContactsjobContactsUpdateJobContacts- Update a Job ContactjobMaterialBundlesCreateJobMaterialBundles- Create a new Job Material BundlejobMaterialBundlesDeleteJobMaterialBundles- Delete a Job Material BundlejobMaterialBundlesGetJobMaterialBundles- Retrieve a Job Material BundlejobMaterialBundlesListJobMaterialBundles- List all Job Material BundlesjobMaterialBundlesUpdateJobMaterialBundles- Update a Job Material BundlejobMaterialsCreateJobMaterials- Create a new Job MaterialjobMaterialsDeleteJobMaterials- Delete a Job MaterialjobMaterialsGetJobMaterials- Retrieve a Job MaterialjobMaterialsListJobMaterials- List all Job MaterialsjobMaterialsUpdateJobMaterials- Update a Job MaterialjobPaymentsCreateJobPayments- Create a new Job PaymentjobPaymentsDeleteJobPayments- Delete a Job PaymentjobPaymentsGetJobPayments- Retrieve a Job PaymentjobPaymentsListJobPayments- List all Job PaymentsjobPaymentsUpdateJobPayments- Update a Job PaymentjobQueuesCreateJobQueues- Create a new Job QueuejobQueuesDeleteJobQueues- Delete a Job QueuejobQueuesGetJobQueues- Retrieve a Job QueuejobQueuesListJobQueues- List all Job QueuesjobQueuesUpdateJobQueues- Update a Job QueuejobsCreateJobs- Create a new JobjobsDeleteJobs- Delete a JobjobsGetJobs- Retrieve a JobjobsListJobs- List all JobsjobsUpdateJobs- Update a JobjobTemplatesCreateJobFromTemplate- Create a job from a templatejobTemplatesGetJobTemplates- Retrieve a Job TemplatejobTemplatesListJobTemplates- List all Job TemplatesknowledgeArticlesCreateKnowledgeArticles- Create a new Knowledge ArticleknowledgeArticlesDeleteKnowledgeArticles- Delete a Knowledge ArticleknowledgeArticlesGetKnowledgeArticles- Retrieve a Knowledge ArticleknowledgeArticlesListKnowledgeArticles- List all Knowledge ArticlesknowledgeArticlesUpdateKnowledgeArticles- Update a Knowledge ArticlelocationsCreateLocations- Create a new LocationlocationsDeleteLocations- Delete a LocationlocationsGetLocations- Retrieve a LocationlocationsListLocations- List all LocationslocationsUpdateLocations- Update a LocationmaterialsCreateMaterials- Create a new MaterialmaterialsDeleteMaterials- Delete a MaterialmaterialsGetMaterials- Retrieve a MaterialmaterialsListMaterials- List all MaterialsmaterialsUpdateMaterials- Update a MaterialnotesCreateNotes- Create a new NotenotesDeleteNotes- Delete a NotenotesGetNotes- Retrieve a NotenotesListNotes- List all NotesnotesUpdateNotes- Update a NotesearchGeneralSearch- Search across multiple object typessearchJobEmbeddingSearch- Semantic search for jobssearchObjectSearch- Search within a specific object typesecurityRolesGetSecurityRoles- Retrieve a Security RolesecurityRolesListSecurityRoles- List all Security RolessmsTemplatesCreateSMSTemplates- Create a new SMS TemplatesmsTemplatesDeleteSMSTemplates- Delete a SMS TemplatesmsTemplatesGetSMSTemplates- Retrieve a SMS TemplatesmsTemplatesListSMSTemplates- List all SMS TemplatessmsTemplatesUpdateSMSTemplates- Update a SMS TemplatestaffMembersCreateStaffMembers- Create a new Staff MemberstaffMembersDeleteStaffMembers- Delete a Staff MemberstaffMembersGetStaffMembers- Retrieve a Staff MemberstaffMembersListStaffMembers- List all Staff MembersstaffMembersUpdateStaffMembers- Update a Staff MemberstaffMessagesCreateStaffMessages- Create a new Staff MessagestaffMessagesDeleteStaffMessages- Delete a Staff MessagestaffMessagesGetStaffMessages- Retrieve a Staff MessagestaffMessagesListStaffMessages- List all Staff MessagesstaffMessagesUpdateStaffMessages- Update a Staff MessagesuppliersCreateSuppliers- Create a new SuppliersuppliersDeleteSuppliers- Delete a SuppliersuppliersGetSuppliers- Retrieve a SuppliersuppliersListSuppliers- List all SupplierssuppliersUpdateSuppliers- Update a SuppliertasksCreateTasks- Create a new TasktasksDeleteTasks- Delete a TasktasksGetTasks- Retrieve a TasktasksListTasks- List all TaskstasksUpdateTasks- Update a TasktaxRatesCreateTaxRates- Create a new Tax RatetaxRatesDeleteTaxRates- Delete a Tax RatetaxRatesGetTaxRates- Retrieve a Tax RatetaxRatesListTaxRates- List all Tax RatestaxRatesUpdateTaxRates- Update a Tax RatevendorsGetVendors- Retrieve a VendorvendorsListVendors- List all Vendors
Retries
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide a retryConfig object to the call:
import { ServiceM8 } from "servicem8";
const serviceM8 = new ServiceM8({
security: {
apiKey: process.env["SERVICEM8_API_KEY"] ?? "",
},
});
async function run() {
const result = await serviceM8.allocationWindows.listAllocationWindows({
retries: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
});
console.log(result);
}
run();
If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:
import { ServiceM8 } from "servicem8";
const serviceM8 = new ServiceM8({
retryConfig: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
security: {
apiKey: process.env["SERVICEM8_API_KEY"] ?? "",
},
});
async function run() {
const result = await serviceM8.allocationWindows.listAllocationWindows();
console.log(result);
}
run();
Error Handling
ServiceM8Error is the base class for all HTTP error responses. It has the following properties:
| Property | Type | Description |
| ------------------- | ---------- | --------------------------------------------------------------------------------------- |
| error.message | string | Error message |
| error.statusCode | number | HTTP response status code eg 404 |
| error.headers | Headers | HTTP response headers |
| error.body | string | HTTP body. Can be empty string if no body is returned. |
| error.rawResponse | Response | Raw HTTP response |
| error.data$ | | Optional. Some errors may contain structured data. See Error Classes. |
Example
import { ServiceM8 } from "servicem8";
import * as errors from "servicem8/models/errors";
const serviceM8 = new ServiceM8({
security: {
apiKey: process.env["SERVICEM8_API_KEY"] ?? "",
},
});
async function run() {
try {
const result = await serviceM8.allocationWindows.listAllocationWindows();
console.log(result);
} catch (error) {
// The base class for HTTP error responses
if (error instanceof errors.ServiceM8Error) {
console.log(error.message);
console.log(error.statusCode);
console.log(error.body);
console.log(error.headers);
// Depending on the method different errors may be thrown
if (error instanceof errors.ErrorT) {
console.log(error.data$.errorCode); // number
console.log(error.data$.message); // string
}
}
}
}
run();
Error Classes
Primary errors:
ServiceM8Error: The base class for HTTP error responses.ErrorT: *AuthenticationError: Unauthorized - Authentication credentials are missing or invalid. Status code401. *ForbiddenError: Status code403. *RateLimitError: Too Many Requests - You have exceeded the rate limit. Status code429. *
Network errors:
ConnectionError: HTTP client was unable to make a request to a server.RequestTimeoutError: HTTP request timed out due to an AbortSignal signal.RequestAbortedError: HTTP request was aborted by the client.InvalidRequestError: Any input used to create a request is invalid.UnexpectedClientError: Unrecognised or unexpected error.
Inherit from ServiceM8Error:
NotFoundError: Status code404. Applicable to 108 of 193 methods.*ResponseValidationError: Type mismatch between the data returned from the server and the structure expected by the SDK. Seeerror.rawValuefor the raw value anderror.pretty()for a nicely formatted multi-line string.
* Check the method documentation to see if the error is applicable.
Server Selection
Override Server URL Per-Client
The default server can be overridden globally by passing a URL to the serverURL: string optional parameter when initializing the SDK client instance. For example:
import { ServiceM8 } from "servicem8";
const serviceM8 = new ServiceM8({
serverURL: "https://api.servicem8.com/api_1.0",
security: {
apiKey: process.env["SERVICEM8_API_KEY"] ?? "",
},
});
async function run() {
const result = await serviceM8.allocationWindows.listAllocationWindows();
console.log(result);
}
run();
Custom HTTP Client
The TypeScript SDK makes API calls using an HTTPClient that wraps the native
Fetch API. This
client is a thin wrapper around fetch and provides the ability to attach hooks
around the request lifecycle that can be used to modify the request or handle
errors and response.
The HTTPClient constructor takes an optional fetcher argument that can be
used to integrate a third-party HTTP client or when writing tests to mock out
the HTTP client and feed in fixtures.
The following example shows how to use the "beforeRequest" hook to to add a
custom header and a timeout to requests and how to use the "requestError" hook
to log errors:
import { ServiceM8 } from "servicem8";
import { HTTPClient } from "servicem8/lib/http";
const httpClient = new HTTPClient({
// fetcher takes a function that has the same signature as native `fetch`.
fetcher: (request) => {
return fetch(request);
}
});
httpClient.addHook("beforeRequest", (request) => {
const nextRequest = new Request(request, {
signal: request.signal || AbortSignal.timeout(5000)
});
nextRequest.headers.set("x-custom-header", "custom value");
return nextRequest;
});
httpClient.addHook("requestError", (error, request) => {
console.group("Request Error");
console.log("Reason:", `${error}`);
console.log("Endpoint:", `${request.method} ${request.url}`);
console.groupEnd();
});
const sdk = new ServiceM8({ httpClient: httpClient });Debugging
You can setup your SDK to emit debug logs for SDK requests and responses.
You can pass a logger that matches console's interface as an SDK option.
[!WARNING] Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.
import { ServiceM8 } from "servicem8";
const sdk = new ServiceM8({ debugLogger: console });You can also enable a default debug logger by setting an environment variable SERVICEM8_DEBUG to true.
Development
Maturity
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.
Contributions
While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.
