flexprice-sdk-test
v1.0.60
Published
Developer-friendly & type-safe Typescript SDK specifically catered to leverage *flexprice-sdk-test* API.
Readme
flexprice-sdk-test
Developer-friendly & type-safe Typescript SDK specifically catered to leverage flexprice-sdk-test API.
[!IMPORTANT] This SDK is not yet ready for production use. To complete setup please follow the steps outlined in your workspace. Delete this section before > publishing to a package manager.
Summary
FlexPrice API: FlexPrice API Service
Table of Contents
SDK Installation
[!TIP] To finish publishing your SDK to npm and others you must run your first generation action.
The SDK can be installed with either npm, pnpm, bun or yarn package managers.
NPM
npm add <UNSET>PNPM
pnpm add <UNSET>Bun
bun add <UNSET>Yarn
yarn add <UNSET>Requirements
For supported JavaScript runtimes, please consult RUNTIMES.md.
SDK Example Usage
Example
import { FlexPrice } from "flexprice-sdk-test";
const flexPrice = new FlexPrice({
serverURL: "https://api.example.com",
apiKeyAuth: "<YOUR_API_KEY_HERE>",
});
async function run() {
const result = await flexPrice.addons.getAddons({});
console.log(result);
}
run();
Authentication
Per-Client Security Schemes
This SDK supports the following security scheme globally:
| Name | Type | Scheme |
| ------------ | ------ | ------- |
| apiKeyAuth | apiKey | API key |
To authenticate with the API the apiKeyAuth parameter must be set when initializing the SDK client instance. For example:
import { FlexPrice } from "flexprice-sdk-test";
const flexPrice = new FlexPrice({
serverURL: "https://api.example.com",
apiKeyAuth: "<YOUR_API_KEY_HERE>",
});
async function run() {
const result = await flexPrice.addons.getAddons({});
console.log(result);
}
run();
Available Resources and Operations
Addons
- getAddons - List addons
- postAddons - Create addon
- getAddonsLookupLookupKey - Get addon by lookup key
- postAddonsSearch - List addons by filter
- getAddonsId - Get addon
- putAddonsId - Update addon
- deleteAddonsId - Delete addon
AlertLogs
- postAlertSearch - List alert logs by filter
Auth
- postAuthLogin - Login
- postAuthSignup - Sign up
Connections
- getConnections - Get connections
- postConnectionsSearch - List connections by filter
- getConnectionsId - Get a connection
- putConnectionsId - Update a connection
- deleteConnectionsId - Delete a connection
Costs
- postCosts - Create a new costsheet
- getCostsActive - Get active costsheet for tenant
- postCostsAnalytics - Get combined revenue and cost analytics
- postCostsAnalyticsV2 - Get combined revenue and cost analytics
- postCostsSearch - List costsheets by filter
- getCostsId - Get a costsheet by ID
- putCostsId - Update a costsheet
- deleteCostsId - Delete a costsheet
Coupons
- getCoupons - List coupons with filtering
- postCoupons - Create a new coupon
- getCouponsId - Get a coupon by ID
- putCouponsId - Update a coupon
- deleteCouponsId - Delete a coupon
CreditNotes
- getCreditnotes - List credit notes with filtering
- postCreditnotes - Create a new credit note
- getCreditnotesId - Get a credit note by ID
- postCreditnotesIdFinalize - Process a draft credit note
- postCreditnotesIdVoid - Void a credit note
CreditGrants
- getCreditgrants - Get credit grants
- postCreditgrants - Create a new credit grant
- getCreditgrantsId - Get a credit grant by ID
- putCreditgrantsId - Update a credit grant
- deleteCreditgrantsId - Delete a credit grant
- getPlansIdCreditgrants - Get plan credit grants
CustomerPortal
- getPortalExternalId - Create a customer portal session
Customers
- getCustomers - Get customers
- putCustomers - Update a customer
- postCustomers - Create a customer
- getCustomersExternalExternalId - Get a customer by external id
- postCustomersSearch - List customers by filter
- getCustomersUsage - Get customer usage summary
- getCustomersId - Get a customer
- deleteCustomersId - Delete a customer
- getCustomersIdEntitlements - Get customer entitlements
- getCustomersIdGrantsUpcoming - Get upcoming credit grant applications
Entitlements
- getAddonsIdEntitlements - Get addon entitlements
- getEntitlements - Get entitlements
- postEntitlements - Create a new entitlement
- postEntitlementsBulk - Create multiple entitlements in bulk
- postEntitlementsSearch - List entitlements by filter
- getEntitlementsId - Get an entitlement by ID
- putEntitlementsId - Update an entitlement
- deleteEntitlementsId - Delete an entitlement
- getPlansIdEntitlements - Get plan entitlements
EntityIntegrationMappings
- getEntityIntegrationMappings - List entity integration mappings
- postEntityIntegrationMappings - Create entity integration mapping
- getEntityIntegrationMappingsId - Get entity integration mapping
- deleteEntityIntegrationMappingsId - Delete entity integration mapping
Environments
- getEnvironments - Get environments
- postEnvironments - Create an environment
- getEnvironmentsId - Get an environment
- putEnvironmentsId - Update an environment
Events
- postEvents - Ingest event
- postEventsAnalytics - Get usage analytics
- postEventsBulk - Bulk Ingest events
- postEventsHuggingfaceInference - Get hugging face inference data
- getEventsMonitoring - Get monitoring data
- postEventsQuery - List raw events
- postEventsUsage - Get usage statistics
- postEventsUsageMeter - Get usage by meter
- getEventsId - Get event by ID
Features
- getFeatures - List features
- postFeatures - Create a new feature
- postFeaturesSearch - List features by filter
- getFeaturesId - Get a feature by ID
- putFeaturesId - Update a feature
- deleteFeaturesId - Delete a feature
Groups
- postGroups - Create a group
- postGroupsSearch - Get groups
- getGroupsId - Get a group
- deleteGroupsId - Delete a group
Integrations
- getSecretsIntegrationsByProviderProvider - Get integration details
- postSecretsIntegrationsCreateProvider - Create or update an integration
- getSecretsIntegrationsLinked - List linked integrations
- deleteSecretsIntegrationsId - Delete an integration
Invoices
- getCustomersIdInvoicesSummary - Get a customer invoice summary
- getInvoices - List invoices
- postInvoices - Create a new one off invoice
- postInvoicesPreview - Get a preview invoice
- postInvoicesSearch - List invoices by filter
- getInvoicesId - Get an invoice by ID
- putInvoicesId - Update an invoice
- postInvoicesIdCommsTrigger - Trigger communication webhook for an invoice
- postInvoicesIdFinalize - Finalize an invoice
- putInvoicesIdPayment - Update invoice payment status
- postInvoicesIdPaymentAttempt - Attempt payment for an invoice
- getInvoicesIdPdf - Get PDF for an invoice
- postInvoicesIdRecalculate - Recalculate invoice totals and line items
- postInvoicesIdVoid - Void an invoice
Payments
- getPayments - List payments
- postPayments - Create a new payment
- getPaymentsId - Get a payment by ID
- putPaymentsId - Update a payment
- deletePaymentsId - Delete a payment
- postPaymentsIdProcess - Process a payment
Plans
- getPlans - Get plans
- postPlans - Create a new plan
- postPlansSearch - List plans by filter
- getPlansId - Get a plan
- putPlansId - Update a plan
- deletePlansId - Delete a plan
- postPlansIdSyncSubscriptions - Synchronize plan prices
PriceUnits
- getPricesUnits - List price units
- postPricesUnits - Create a new price unit
- getPricesUnitsCodeCode - Get a price unit by code
- postPricesUnitsSearch - List price units by filter
- getPricesUnitsId - Get a price unit by ID
- putPricesUnitsId - Update a price unit
- deletePricesUnitsId - Delete a price unit
Prices
- getPrices - Get prices
- postPrices - Create a new price
- postPricesBulk - Create multiple prices in bulk
- getPricesLookupLookupKey - Get price by lookup key
- getPricesId - Get a price by ID
- putPricesId - Update a price
- deletePricesId - Delete a price
Rbac
- getRbacRoles - List all RBAC roles
- getRbacRolesId - Get a specific RBAC role
ScheduledTasks
- getTasksScheduled - List scheduled tasks
- postTasksScheduled - Create a scheduled task
- postTasksScheduledScheduleUpdateBillingPeriod - Schedule update billing period
- getTasksScheduledId - Get a scheduled task
- putTasksScheduledId - Update a scheduled task
- deleteTasksScheduledId - Delete a scheduled task
- postTasksScheduledIdRun - Trigger force run
Secrets
- getSecretsApiKeys - List API keys
- postSecretsApiKeys - Create a new API key
- deleteSecretsApiKeysId - Delete an API key
Subscriptions
- getSubscriptions - List subscriptions
- postSubscriptions - Create subscription
- postSubscriptionsAddon - Add addon to subscription
- deleteSubscriptionsAddon - Remove addon from subscription
- putSubscriptionsLineitemsId - Update subscription line item
- deleteSubscriptionsLineitemsId - Delete subscription line item
- postSubscriptionsSearch - List subscriptions by filter
- postSubscriptionsUsage - Get usage by subscription
- getSubscriptionsId - Get subscription
- postSubscriptionsIdActivate - Activate draft subscription
- getSubscriptionsIdAddonsAssociations - Get active addon associations
- postSubscriptionsIdCancel - Cancel subscription
- postSubscriptionsIdChangeExecute - Execute subscription plan change
- postSubscriptionsIdChangePreview - Preview subscription plan change
- getSubscriptionsIdEntitlements - Get subscription entitlements
- getSubscriptionsIdGrantsUpcoming - Get upcoming credit grant applications
- postSubscriptionsIdPause - Pause a subscription
- getSubscriptionsIdPauses - List all pauses for a subscription
- postSubscriptionsIdResume - Resume a paused subscription
- getSubscriptionsIdV2 - Get subscription V2
- getV1SubscriptionSchedules - List all subscription schedules
- getV1SubscriptionSchedulesId - Get subscription schedule
- postV1SubscriptionsSchedulesScheduleIdCancel - Cancel subscription schedule
- getV1SubscriptionsSubscriptionIdSchedules - List subscription schedules
Tasks
- getTasks - List tasks
- postTasks - Create a new task
- getTasksResult - Get task processing result
- getTasksId - Get a task
- getTasksIdDownload - Download task export file
- putTasksIdStatus - Update task status
TaxAssociations
- getTaxesAssociations - List tax associations
- postTaxesAssociations - Create Tax Association
- getTaxesAssociationsId - Get Tax Association
- putTaxesAssociationsId - Update tax association
- deleteTaxesAssociationsId - Delete tax association
TaxRates
- getTaxesRates - Get tax rates
- postTaxesRates - Create a tax rate
- getTaxesRatesId - Get a tax rate
- putTaxesRatesId - Update a tax rate
- deleteTaxesRatesId - Delete a tax rate
Tenants
- getTenantBilling - Get billing usage for the current tenant
- postTenants - Create a new tenant
- putTenantsUpdate - Update a tenant
- getTenantsId - Get tenant by ID
Users
- postUsers - Create service account
- getUsersMe - Get user info
- postUsersSearch - List users with filters
Wallets
- getCustomersWallets - Get Customer Wallets
- getCustomersIdWallets - Get wallets by customer ID
- getWallets - List wallets
- postWallets - Create a new wallet
- postWalletsSearch - List wallets by filter
- postWalletsTransactionsSearch - List wallet transactions by filter
- getWalletsId - Get wallet by ID
- putWalletsId - Update a wallet
- getWalletsIdBalanceRealTime - Get wallet balance
- postWalletsIdTerminate - Terminate a wallet
- postWalletsIdTopUp - Top up wallet
- getWalletsIdTransactions - Get wallet transactions
Webhooks
- postWebhooksChargebeeTenantIdEnvironmentId - Handle Chargebee webhook events
- postWebhooksHubspotTenantIdEnvironmentId - Handle HubSpot webhook events
- postWebhooksMoyasarTenantIdEnvironmentId - Handle Moyasar webhook events
- postWebhooksNomodTenantIdEnvironmentId - Handle Nomod webhook events
- postWebhooksQuickbooksTenantIdEnvironmentId - Handle QuickBooks webhook events
- postWebhooksRazorpayTenantIdEnvironmentId - Handle Razorpay webhook events
- postWebhooksStripeTenantIdEnvironmentId - Handle Stripe webhook events
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.
addonsDeleteAddonsId- Delete addonaddonsGetAddons- List addonsaddonsGetAddonsId- Get addonaddonsGetAddonsLookupLookupKey- Get addon by lookup keyaddonsPostAddons- Create addonaddonsPostAddonsSearch- List addons by filteraddonsPutAddonsId- Update addonalertLogsPostAlertSearch- List alert logs by filterauthPostAuthLogin- LoginauthPostAuthSignup- Sign upconnectionsDeleteConnectionsId- Delete a connectionconnectionsGetConnections- Get connectionsconnectionsGetConnectionsId- Get a connectionconnectionsPostConnectionsSearch- List connections by filterconnectionsPutConnectionsId- Update a connectioncostsDeleteCostsId- Delete a costsheetcostsGetCostsActive- Get active costsheet for tenantcostsGetCostsId- Get a costsheet by IDcostsPostCosts- Create a new costsheetcostsPostCostsAnalytics- Get combined revenue and cost analyticscostsPostCostsAnalyticsV2- Get combined revenue and cost analyticscostsPostCostsSearch- List costsheets by filtercostsPutCostsId- Update a costsheetcouponsDeleteCouponsId- Delete a couponcouponsGetCoupons- List coupons with filteringcouponsGetCouponsId- Get a coupon by IDcouponsPostCoupons- Create a new couponcouponsPutCouponsId- Update a couponcreditGrantsDeleteCreditgrantsId- Delete a credit grantcreditGrantsGetCreditgrants- Get credit grantscreditGrantsGetCreditgrantsId- Get a credit grant by IDcreditGrantsGetPlansIdCreditgrants- Get plan credit grantscreditGrantsPostCreditgrants- Create a new credit grantcreditGrantsPutCreditgrantsId- Update a credit grantcreditNotesGetCreditnotes- List credit notes with filteringcreditNotesGetCreditnotesId- Get a credit note by IDcreditNotesPostCreditnotes- Create a new credit notecreditNotesPostCreditnotesIdFinalize- Process a draft credit notecreditNotesPostCreditnotesIdVoid- Void a credit notecustomerPortalGetPortalExternalId- Create a customer portal sessioncustomersDeleteCustomersId- Delete a customercustomersGetCustomers- Get customerscustomersGetCustomersExternalExternalId- Get a customer by external idcustomersGetCustomersId- Get a customercustomersGetCustomersIdEntitlements- Get customer entitlementscustomersGetCustomersIdGrantsUpcoming- Get upcoming credit grant applicationscustomersGetCustomersUsage- Get customer usage summarycustomersPostCustomers- Create a customercustomersPostCustomersSearch- List customers by filtercustomersPutCustomers- Update a customerentitlementsDeleteEntitlementsId- Delete an entitlemententitlementsGetAddonsIdEntitlements- Get addon entitlementsentitlementsGetEntitlements- Get entitlementsentitlementsGetEntitlementsId- Get an entitlement by IDentitlementsGetPlansIdEntitlements- Get plan entitlementsentitlementsPostEntitlements- Create a new entitlemententitlementsPostEntitlementsBulk- Create multiple entitlements in bulkentitlementsPostEntitlementsSearch- List entitlements by filterentitlementsPutEntitlementsId- Update an entitlemententityIntegrationMappingsDeleteEntityIntegrationMappingsId- Delete entity integration mappingentityIntegrationMappingsGetEntityIntegrationMappings- List entity integration mappingsentityIntegrationMappingsGetEntityIntegrationMappingsId- Get entity integration mappingentityIntegrationMappingsPostEntityIntegrationMappings- Create entity integration mappingenvironmentsGetEnvironments- Get environmentsenvironmentsGetEnvironmentsId- Get an environmentenvironmentsPostEnvironments- Create an environmentenvironmentsPutEnvironmentsId- Update an environmenteventsGetEventsId- Get event by IDeventsGetEventsMonitoring- Get monitoring dataeventsPostEvents- Ingest eventeventsPostEventsAnalytics- Get usage analyticseventsPostEventsBulk- Bulk Ingest eventseventsPostEventsHuggingfaceInference- Get hugging face inference dataeventsPostEventsQuery- List raw eventseventsPostEventsUsage- Get usage statisticseventsPostEventsUsageMeter- Get usage by meterfeaturesDeleteFeaturesId- Delete a featurefeaturesGetFeatures- List featuresfeaturesGetFeaturesId- Get a feature by IDfeaturesPostFeatures- Create a new featurefeaturesPostFeaturesSearch- List features by filterfeaturesPutFeaturesId- Update a featuregroupsDeleteGroupsId- Delete a groupgroupsGetGroupsId- Get a groupgroupsPostGroups- Create a groupgroupsPostGroupsSearch- Get groupsintegrationsDeleteSecretsIntegrationsId- Delete an integrationintegrationsGetSecretsIntegrationsByProviderProvider- Get integration detailsintegrationsGetSecretsIntegrationsLinked- List linked integrationsintegrationsPostSecretsIntegrationsCreateProvider- Create or update an integrationinvoicesGetCustomersIdInvoicesSummary- Get a customer invoice summaryinvoicesGetInvoices- List invoicesinvoicesGetInvoicesId- Get an invoice by IDinvoicesGetInvoicesIdPdf- Get PDF for an invoiceinvoicesPostInvoices- Create a new one off invoiceinvoicesPostInvoicesIdCommsTrigger- Trigger communication webhook for an invoiceinvoicesPostInvoicesIdFinalize- Finalize an invoiceinvoicesPostInvoicesIdPaymentAttempt- Attempt payment for an invoiceinvoicesPostInvoicesIdRecalculate- Recalculate invoice totals and line itemsinvoicesPostInvoicesIdVoid- Void an invoiceinvoicesPostInvoicesPreview- Get a preview invoiceinvoicesPostInvoicesSearch- List invoices by filterinvoicesPutInvoicesId- Update an invoiceinvoicesPutInvoicesIdPayment- Update invoice payment statuspaymentsDeletePaymentsId- Delete a paymentpaymentsGetPayments- List paymentspaymentsGetPaymentsId- Get a payment by IDpaymentsPostPayments- Create a new paymentpaymentsPostPaymentsIdProcess- Process a paymentpaymentsPutPaymentsId- Update a paymentplansDeletePlansId- Delete a planplansGetPlans- Get plansplansGetPlansId- Get a planplansPostPlans- Create a new planplansPostPlansIdSyncSubscriptions- Synchronize plan pricesplansPostPlansSearch- List plans by filterplansPutPlansId- Update a planpricesDeletePricesId- Delete a pricepricesGetPrices- Get pricespricesGetPricesId- Get a price by IDpricesGetPricesLookupLookupKey- Get price by lookup keypricesPostPrices- Create a new pricepricesPostPricesBulk- Create multiple prices in bulkpricesPutPricesId- Update a pricepriceUnitsDeletePricesUnitsId- Delete a price unitpriceUnitsGetPricesUnits- List price unitspriceUnitsGetPricesUnitsCodeCode- Get a price unit by codepriceUnitsGetPricesUnitsId- Get a price unit by IDpriceUnitsPostPricesUnits- Create a new price unitpriceUnitsPostPricesUnitsSearch- List price units by filterpriceUnitsPutPricesUnitsId- Update a price unitrbacGetRBACRoles- List all RBAC rolesrbacGetRBACRolesId- Get a specific RBAC rolescheduledTasksDeleteTasksScheduledId- Delete a scheduled taskscheduledTasksGetTasksScheduled- List scheduled tasksscheduledTasksGetTasksScheduledId- Get a scheduled taskscheduledTasksPostTasksScheduled- Create a scheduled taskscheduledTasksPostTasksScheduledIdRun- Trigger force runscheduledTasksPostTasksScheduledScheduleUpdateBillingPeriod- Schedule update billing periodscheduledTasksPutTasksScheduledId- Update a scheduled tasksecretsDeleteSecretsApiKeysId- Delete an API keysecretsGetSecretsApiKeys- List API keyssecretsPostSecretsApiKeys- Create a new API keysubscriptionsDeleteSubscriptionsAddon- Remove addon from subscriptionsubscriptionsDeleteSubscriptionsLineitemsId- Delete subscription line itemsubscriptionsGetSubscriptions- List subscriptionssubscriptionsGetSubscriptionsId- Get subscriptionsubscriptionsGetSubscriptionsIdAddonsAssociations- Get active addon associationssubscriptionsGetSubscriptionsIdEntitlements- Get subscription entitlementssubscriptionsGetSubscriptionsIdGrantsUpcoming- Get upcoming credit grant applicationssubscriptionsGetSubscriptionsIdPauses- List all pauses for a subscriptionsubscriptionsGetSubscriptionsIdV2- Get subscription V2subscriptionsGetV1SubscriptionSchedules- List all subscription schedulessubscriptionsGetV1SubscriptionSchedulesId- Get subscription schedulesubscriptionsGetV1SubscriptionsSubscriptionIdSchedules- List subscription schedulessubscriptionsPostSubscriptions- Create subscriptionsubscriptionsPostSubscriptionsAddon- Add addon to subscriptionsubscriptionsPostSubscriptionsIdActivate- Activate draft subscriptionsubscriptionsPostSubscriptionsIdCancel- Cancel subscriptionsubscriptionsPostSubscriptionsIdChangeExecute- Execute subscription plan changesubscriptionsPostSubscriptionsIdChangePreview- Preview subscription plan changesubscriptionsPostSubscriptionsIdPause- Pause a subscriptionsubscriptionsPostSubscriptionsIdResume- Resume a paused subscriptionsubscriptionsPostSubscriptionsSearch- List subscriptions by filtersubscriptionsPostSubscriptionsUsage- Get usage by subscriptionsubscriptionsPostV1SubscriptionsSchedulesScheduleIdCancel- Cancel subscription schedulesubscriptionsPutSubscriptionsLineitemsId- Update subscription line itemtasksGetTasks- List taskstasksGetTasksId- Get a tasktasksGetTasksIdDownload- Download task export filetasksGetTasksResult- Get task processing resulttasksPostTasks- Create a new tasktasksPutTasksIdStatus- Update task statustaxAssociationsDeleteTaxesAssociationsId- Delete tax associationtaxAssociationsGetTaxesAssociations- List tax associationstaxAssociationsGetTaxesAssociationsId- Get Tax AssociationtaxAssociationsPostTaxesAssociations- Create Tax AssociationtaxAssociationsPutTaxesAssociationsId- Update tax associationtaxRatesDeleteTaxesRatesId- Delete a tax ratetaxRatesGetTaxesRates- Get tax ratestaxRatesGetTaxesRatesId- Get a tax ratetaxRatesPostTaxesRates- Create a tax ratetaxRatesPutTaxesRatesId- Update a tax ratetenantsGetTenantBilling- Get billing usage for the current tenanttenantsGetTenantsId- Get tenant by IDtenantsPostTenants- Create a new tenanttenantsPutTenantsUpdate- Update a tenantusersGetUsersMe- Get user infousersPostUsers- Create service accountusersPostUsersSearch- List users with filterswalletsGetCustomersIdWallets- Get wallets by customer IDwalletsGetCustomersWallets- Get Customer WalletswalletsGetWallets- List walletswalletsGetWalletsId- Get wallet by IDwalletsGetWalletsIdBalanceRealTime- Get wallet balancewalletsGetWalletsIdTransactions- Get wallet transactionswalletsPostWallets- Create a new walletwalletsPostWalletsIdTerminate- Terminate a walletwalletsPostWalletsIdTopUp- Top up walletwalletsPostWalletsSearch- List wallets by filterwalletsPostWalletsTransactionsSearch- List wallet transactions by filterwalletsPutWalletsId- Update a walletwebhooksPostWebhooksChargebeeTenantIdEnvironmentId- Handle Chargebee webhook eventswebhooksPostWebhooksHubspotTenantIdEnvironmentId- Handle HubSpot webhook eventswebhooksPostWebhooksMoyasarTenantIdEnvironmentId- Handle Moyasar webhook eventswebhooksPostWebhooksNomodTenantIdEnvironmentId- Handle Nomod webhook eventswebhooksPostWebhooksQuickbooksTenantIdEnvironmentId- Handle QuickBooks webhook eventswebhooksPostWebhooksRazorpayTenantIdEnvironmentId- Handle Razorpay webhook eventswebhooksPostWebhooksStripeTenantIdEnvironmentId- Handle Stripe webhook events
File uploads
Certain SDK methods accept files as part of a multi-part request. It is possible and typically recommended to upload files as a stream rather than reading the entire contents into memory. This avoids excessive memory consumption and potentially crashing with out-of-memory errors when working with very large files. The following example demonstrates how to attach a file stream to a request.
[!TIP]
Depending on your JavaScript runtime, there are convenient utilities that return a handle to a file without reading the entire contents into memory:
- Node.js v20+: Since v20, Node.js comes with a native
openAsBlobfunction innode:fs.- Bun: The native
Bun.filefunction produces a file handle that can be used for streaming file uploads.- Browsers: All supported browsers return an instance to a
Filewhen reading the value from an<input type="file">element.- Node.js v18: A file stream can be created using the
fileFromhelper fromfetch-blob/from.js.
import { FlexPrice } from "flexprice-sdk-test";
import { openAsBlob } from "node:fs";
const flexPrice = new FlexPrice({
serverURL: "https://api.example.com",
apiKeyAuth: "<YOUR_API_KEY_HERE>",
});
async function run() {
const result = await flexPrice.events.postEventsAnalytics(
await openAsBlob("example.file"),
);
console.log(result);
}
run();
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 { FlexPrice } from "flexprice-sdk-test";
const flexPrice = new FlexPrice({
serverURL: "https://api.example.com",
apiKeyAuth: "<YOUR_API_KEY_HERE>",
});
async function run() {
const result = await flexPrice.addons.getAddons({}, {
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 { FlexPrice } from "flexprice-sdk-test";
const flexPrice = new FlexPrice({
serverURL: "https://api.example.com",
retryConfig: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
apiKeyAuth: "<YOUR_API_KEY_HERE>",
});
async function run() {
const result = await flexPrice.addons.getAddons({});
console.log(result);
}
run();
Error Handling
FlexPriceError 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 { FlexPrice } from "flexprice-sdk-test";
import * as errors from "flexprice-sdk-test/models/errors";
const flexPrice = new FlexPrice({
serverURL: "https://api.example.com",
apiKeyAuth: "<YOUR_API_KEY_HERE>",
});
async function run() {
try {
const result = await flexPrice.addons.getAddons({});
console.log(result);
} catch (error) {
// The base class for HTTP error responses
if (error instanceof errors.FlexPriceError) {
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.ErrorsErrorResponse) {
console.log(error.data$.error); // components.ErrorsErrorDetail
console.log(error.data$.success); // boolean
}
}
}
}
run();
Error Classes
Primary errors:
FlexPriceError: The base class for HTTP error responses.
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 FlexPriceError:
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.
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 { FlexPrice } from "flexprice-sdk-test";
import { HTTPClient } from "flexprice-sdk-test/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 FlexPrice({ 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 { FlexPrice } from "flexprice-sdk-test";
const sdk = new FlexPrice({ debugLogger: console });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.
