lapyme
v0.3.1
Published
Official TypeScript SDK for La Pyme's public API.
Downloads
1,324
Readme
lapyme
Official TypeScript SDK for La Pyme's public API.
Use La Pyme as the business operations layer for custom backends, scripts, workers, and automations. Manage customers, products, sales, purchases, inventory, payments, and reports with typed requests and responses.
To learn more, check the API reference
and the copy-pasteable workflows in examples/.
pnpm add lapymeimport { Lapyme } from "lapyme";
const lapyme = new Lapyme({
bearerAuth: process.env["LAPYME_API_KEY"] ?? "",
});
const externalOrderId = "shopify-1001";
const customerId = "cus_...";
const pointOfSaleId = "pos_...";
const productId = "prod_...";
const sale = await lapyme.sales.create({
idempotencyKey: `sale:shopify:${externalOrderId}`,
body: {
customerId,
pointOfSaleId,
voucherType: 6,
invoiceDate: new Date("2026-05-24"),
currency: "PES",
items: [
{
productId,
quantity: 1,
unitPrice: 125000,
},
],
},
});
console.log(sale.result.data.sale.id);Set API keys as LAPYME_API_KEY in your server environment and pass that value
to the SDK constructor as bearerAuth. Do not expose API keys in browser code.
See examples/ for copy-pasteable workflows, including
credential checks, sales, purchase orders, reports, and error handling.
Summary
La Pyme API: Resources and workflows for purchases, sales, inventory, contacts, products, reports, and settings.
Table of Contents
SDK Installation
The SDK can be installed with either npm, pnpm, bun or yarn package managers.
NPM
npm add lapymePNPM
pnpm add lapymeBun
bun add lapymeYarn
yarn add lapyme[!NOTE] This package is published as an ES Module (ESM) only. For applications using CommonJS, use
await import("lapyme")to import and use this package.
Requirements
For supported JavaScript runtimes, please consult RUNTIMES.md.
SDK Example Usage
Example
import { Lapyme } from "lapyme";
const lapyme = new Lapyme({
bearerAuth: process.env["LAPYME_BEARER_AUTH"] ?? "",
});
async function run() {
const result = await lapyme.suppliers.list({});
console.log(result);
}
run();
Authentication
Per-Client Security Schemes
This SDK supports the following security scheme globally:
| Name | Type | Scheme | Environment Variable |
| ------------ | ---- | ----------- | -------------------- |
| bearerAuth | http | HTTP Bearer | LAPYME_BEARER_AUTH |
To authenticate with the API the bearerAuth parameter must be set when initializing the SDK client instance. For example:
import { Lapyme } from "lapyme";
const lapyme = new Lapyme({
bearerAuth: process.env["LAPYME_BEARER_AUTH"] ?? "",
});
async function run() {
const result = await lapyme.suppliers.list({});
console.log(result);
}
run();
Available Resources and Operations
Api
- archiveApiOrder - Archivar pedido
- updateApiOrderPreparation - Actualizar preparación pendiente
- createApiOrderPreparation - Marcar líneas como preparadas
- cancelApiOrderPreparation - Cancelar preparación
- createApiOrderInvoice - Facturar pedido
- listApiAccountingAccounts - Listar cuentas contables
- getApiAccountingAccount - Obtener cuenta contable
- listApiCostCenterDimensions - Listar dimensiones de centros de costo
- listApiCostCenters - Listar centros de costo
- getApiTrialBalance - Obtener sumas y saldos
- getApiIncomeStatement - Obtener estado de resultados
- getApiComparativeIncomeStatement - Obtener estado de resultados comparativo
- getApiIncomeStatementByCostCenter - Obtener estado de resultados por centro de costo
- listApiSummarizedJournal - Listar libro diario resumido
- previewApiInflationAdjustment - Previsualizar ajuste por inflación
- createApiInflationAdjustment - Crear ajuste por inflación
- listApiAccountingJournalEntries - Listar asientos contables
- createApiManualJournalEntry - Crear asiento manual
- getApiAccountingJournalEntry - Obtener asiento contable
- updateApiManualJournalEntry - Reemplazar asiento manual
- deleteApiManualJournalEntry - Eliminar asiento manual
- getApiAccountLedger - Obtener mayor de cuenta
Categories
- get - Listar categorías
- create - Crear categoría
- getById - Obtener categoría
- updateCategory - Actualizar categoría
CustomerPayments
- listCustomerPayments - Listar cobranzas de clientes
- createCustomerPayment - Crear cobranza de cliente
- getCustomerPayment - Obtener cobranza de cliente
- void - Anular cobranza de cliente
Customers
- get - Listar clientes
- create - Crear cliente
- getCustomerById - Obtener cliente por ID
- updateCustomer - Actualizar cliente
- applyTags - Aplicar etiquetas a clientes
Inventory
- listInventory - Consultar inventario por depósito
- listInventoryMovements - Listar movimientos de inventario
Orders
- listOrders - Listar pedidos
- createOrder - Crear pedido
- getOrderById - Obtener pedido
- updateOrderNotes - Actualizar notas del pedido
- deleteArchived - Eliminar pedido archivado
- cancel - Cancelar pedido
- unarchive - Desarchivar pedido
PaymentMethods
- list - Listar métodos de pago
- create - Crear método de pago
- get - Obtener método de pago
- updatePaymentMethod - Actualizar método de pago
PointsOfSale
- listPointsOfSale - Listar puntos de venta
PriceLists
- get - Listar listas de precios
- createPriceList - Crear lista de precios
- getPriceListById - Obtener lista de precios por ID
- updatePriceList - Actualizar lista de precios
ProductBulkAdjustments
- create - Actualizar productos masivamente
Products
- list - Listar productos
- create - Crear producto
- getProductById - Obtener producto por ID
- update - Actualizar producto
- applyProductTags - Aplicar etiquetas a productos
PurchaseOrders
- listPurchaseOrders - Listar órdenes de compra
- createPurchaseOrder - Crear orden de compra
- getPurchaseOrderById - Obtener orden de compra por ID
- confirm - Confirmar orden de compra
- close - Cerrar orden de compra
- reopen - Reabrir orden de compra
PurchaseOrders.Receipts
- receive - Recibir orden de compra
Purchases
- listPurchases - Listar compras
- createPurchase - Crear compra
- getPurchaseById - Obtener compra por ID
- applyPurchaseTags - Aplicar etiquetas a compras
Reports
- query - Consultar reporte
Sales
- list - Listar ventas
- create - Crear venta
- getSaleById - Obtener venta por ID
- patchMetadata - Actualizar metadatos de venta
SaleTags
- apply - Aplicar etiquetas a ventas
StockMovements
- createStockMovement - Crear movimiento de stock
StockTransfers
- listStockTransfers - Listar transferencias de stock
- createStockTransfer - Crear transferencia de stock
- getStockTransferById - Obtener transferencia por ID
SupplierPayments
- listSupplierPayments - Listar pagos a proveedores
- createSupplierPayment - Crear pago a proveedor
- getSupplierPayment - Obtener pago a proveedor
- voidSupplierPayment - Anular pago a proveedor
Suppliers
- list - Listar proveedores
- createSupplier - Crear proveedor
- getSupplier - Obtener proveedor
- updateSupplier - Actualizar proveedor
- applySupplierTags - Aplicar etiquetas a proveedores
Tags
Warehouses
- list - Listar depósitos
- create - Crear depósito
- getWarehouseById - Obtener depósito por ID
- updateWarehouse - Actualizar depósito
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.
apiArchiveAPIOrder- Archivar pedidoapiCancelAPIOrderPreparation- Cancelar preparaciónapiCreateAPIInflationAdjustment- Crear ajuste por inflaciónapiCreateAPIManualJournalEntry- Crear asiento manualapiCreateAPIOrderInvoice- Facturar pedidoapiCreateAPIOrderPreparation- Marcar líneas como preparadasapiDeleteAPIManualJournalEntry- Eliminar asiento manualapiGetAPIAccountingAccount- Obtener cuenta contableapiGetAPIAccountingJournalEntry- Obtener asiento contableapiGetAPIAccountLedger- Obtener mayor de cuentaapiGetAPIComparativeIncomeStatement- Obtener estado de resultados comparativoapiGetAPIIncomeStatement- Obtener estado de resultadosapiGetAPIIncomeStatementByCostCenter- Obtener estado de resultados por centro de costoapiGetAPITrialBalance- Obtener sumas y saldosapiListAPIAccountingAccounts- Listar cuentas contablesapiListAPIAccountingJournalEntries- Listar asientos contablesapiListAPICostCenterDimensions- Listar dimensiones de centros de costoapiListAPICostCenters- Listar centros de costoapiListAPISummarizedJournal- Listar libro diario resumidoapiPreviewAPIInflationAdjustment- Previsualizar ajuste por inflaciónapiUpdateAPIManualJournalEntry- Reemplazar asiento manualapiUpdateAPIOrderPreparation- Actualizar preparación pendientecategoriesCreate- Crear categoríacategoriesGet- Listar categoríascategoriesGetById- Obtener categoríacategoriesUpdateCategory- Actualizar categoríacustomerPaymentsCreateCustomerPayment- Crear cobranza de clientecustomerPaymentsGetCustomerPayment- Obtener cobranza de clientecustomerPaymentsListCustomerPayments- Listar cobranzas de clientescustomerPaymentsVoid- Anular cobranza de clientecustomersApplyTags- Aplicar etiquetas a clientescustomersCreate- Crear clientecustomersGet- Listar clientescustomersGetCustomerById- Obtener cliente por IDcustomersUpdateCustomer- Actualizar clienteinventoryListInventory- Consultar inventario por depósitoinventoryListInventoryMovements- Listar movimientos de inventarioordersCancel- Cancelar pedidoordersCreateOrder- Crear pedidoordersDeleteArchived- Eliminar pedido archivadoordersGetOrderById- Obtener pedidoordersListOrders- Listar pedidosordersUnarchive- Desarchivar pedidoordersUpdateOrderNotes- Actualizar notas del pedidopaymentMethodsCreate- Crear método de pagopaymentMethodsGet- Obtener método de pagopaymentMethodsList- Listar métodos de pagopaymentMethodsUpdatePaymentMethod- Actualizar método de pagopointsOfSaleListPointsOfSale- Listar puntos de ventapriceListsCreatePriceList- Crear lista de preciospriceListsGet- Listar listas de preciospriceListsGetPriceListById- Obtener lista de precios por IDpriceListsUpdatePriceList- Actualizar lista de preciosproductBulkAdjustmentsCreate- Actualizar productos masivamenteproductsApplyProductTags- Aplicar etiquetas a productosproductsCreate- Crear productoproductsGetProductById- Obtener producto por IDproductsList- Listar productosproductsUpdate- Actualizar productopurchaseOrdersClose- Cerrar orden de comprapurchaseOrdersConfirm- Confirmar orden de comprapurchaseOrdersCreatePurchaseOrder- Crear orden de comprapurchaseOrdersGetPurchaseOrderById- Obtener orden de compra por IDpurchaseOrdersListPurchaseOrders- Listar órdenes de comprapurchaseOrdersReceiptsReceive- Recibir orden de comprapurchaseOrdersReopen- Reabrir orden de comprapurchasesApplyPurchaseTags- Aplicar etiquetas a compraspurchasesCreatePurchase- Crear comprapurchasesGetPurchaseById- Obtener compra por IDpurchasesListPurchases- Listar comprasreportsQuery- Consultar reportesalesCreate- Crear ventasalesGetSaleById- Obtener venta por IDsalesList- Listar ventassalesPatchMetadata- Actualizar metadatos de ventasaleTagsApply- Aplicar etiquetas a ventasstockMovementsCreateStockMovement- Crear movimiento de stockstockTransfersCreateStockTransfer- Crear transferencia de stockstockTransfersGetStockTransferById- Obtener transferencia por IDstockTransfersListStockTransfers- Listar transferencias de stocksupplierPaymentsCreateSupplierPayment- Crear pago a proveedorsupplierPaymentsGetSupplierPayment- Obtener pago a proveedorsupplierPaymentsListSupplierPayments- Listar pagos a proveedoressupplierPaymentsVoidSupplierPayment- Anular pago a proveedorsuppliersApplySupplierTags- Aplicar etiquetas a proveedoressuppliersCreateSupplier- Crear proveedorsuppliersGetSupplier- Obtener proveedorsuppliersList- Listar proveedoressuppliersUpdateSupplier- Actualizar proveedortagsCreateTag- Crear etiquetatagsListTags- Listar etiquetastagsUpdateTag- Actualizar etiquetawarehousesCreate- Crear depósitowarehousesGetWarehouseById- Obtener depósito por IDwarehousesList- Listar depósitoswarehousesUpdateWarehouse- Actualizar depósito
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 { Lapyme } from "lapyme";
const lapyme = new Lapyme({
bearerAuth: process.env["LAPYME_BEARER_AUTH"] ?? "",
});
async function run() {
const result = await lapyme.suppliers.list({}, {
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 { Lapyme } from "lapyme";
const lapyme = new Lapyme({
retryConfig: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
bearerAuth: process.env["LAPYME_BEARER_AUTH"] ?? "",
});
async function run() {
const result = await lapyme.suppliers.list({});
console.log(result);
}
run();
Error Handling
LapymeError 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 { Lapyme } from "lapyme";
import * as errors from "lapyme/models/errors";
const lapyme = new Lapyme({
bearerAuth: process.env["LAPYME_BEARER_AUTH"] ?? "",
});
async function run() {
try {
const result = await lapyme.suppliers.list({});
console.log(result);
} catch (error) {
// The base class for HTTP error responses
if (error instanceof errors.LapymeError) {
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.ApiErrorEnvelope) {
console.log(error.data$.requestId); // string
console.log(error.data$.error); // models.ErrorT
}
}
}
}
run();
Error Classes
Primary errors:
LapymeError: The base class for HTTP error responses.ApiErrorEnvelope: Generic error.
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 LapymeError:
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.
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 { Lapyme } from "lapyme";
const lapyme = new Lapyme({
serverURL: "https://api.lapyme.com.ar",
bearerAuth: process.env["LAPYME_BEARER_AUTH"] ?? "",
});
async function run() {
const result = await lapyme.suppliers.list({});
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:
- route requests through a proxy server using undici's ProxyAgent
- use the
"beforeRequest"hook to add a custom header and a timeout to requests - use the
"requestError"hook to log errors
import { Lapyme } from "lapyme";
import { ProxyAgent } from "undici";
import { HTTPClient } from "lapyme/lib/http";
const dispatcher = new ProxyAgent("http://proxy.example.com:8080");
const httpClient = new HTTPClient({
// 'fetcher' takes a function that has the same signature as native 'fetch'.
fetcher: (input, init) =>
// 'dispatcher' is specific to undici and not part of the standard Fetch API.
fetch(input, { ...init, dispatcher } as RequestInit),
});
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 Lapyme({ 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 { Lapyme } from "lapyme";
const sdk = new Lapyme({ debugLogger: console });You can also enable a default debug logger by setting an environment variable LAPYME_DEBUG to true.
Development
Versioning
Pin the SDK to a specific package version in production applications. This keeps installs reproducible and lets you adopt SDK updates intentionally.
Contributions
Open an issue or PR with the integration you are building, a minimal repro, and the expected SDK behavior. We prioritize changes that make common La Pyme API workflows easier to build and safer to operate.
