Resources API
Manage business entities (nouns/objects) with full CRUD operations
Manage business entities (nouns/objects) with full CRUD operations. Resources represent the data entities in your business: customers, products, orders, invoices, etc.
Overview
Business resources are semantic entities that:
- Represent business nouns (Customer, Product, Order, Invoice, etc.)
- Use Schema.org types for semantic consistency
- Support full CRUD operations (Create, Read, Update, Delete)
- Include relationships via
$typeand$idproperties - Enable semantic querying and traversal
import { createBusinessApi } from 'business-as-code'
const api = createBusinessApi({
apiKey: process.env.APIS_DO_KEY,
})
// Create a customer
const customer = await api.resources.create({
$type: 'Customer',
$id: 'cust-123',
name: 'Acme Corporation',
email: '[email protected]',
phone: '+1-555-0100',
address: {
street: '123 Main St',
city: 'San Francisco',
state: 'CA',
zipCode: '94102',
},
})create()
Create a new business resource.
Signature
create(
resource: BusinessResource
): Promise<BusinessResource>Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| resource | BusinessResource | Yes | Resource data with $type and $id |
Returns
Promise that resolves to the created BusinessResource.
Example
// Create a product
const product = await api.resources.create({
$type: 'Product',
$id: 'prod-456',
name: 'Enterprise Plan',
description: 'Full-featured plan for large organizations',
price: 999.0,
currency: 'USD',
features: ['Unlimited users', 'Advanced analytics', 'Priority support', 'Custom integrations'],
category: 'Subscription',
})
console.log('Created product:', product.$id)Complex Example: Order with Line Items
// Create order resource
const order = await api.resources.create({
$type: 'Order',
$id: 'order-789',
// Customer reference
customer: {
$type: 'Customer',
$id: 'cust-123',
},
// Order details
orderNumber: 'ORD-2024-0789',
orderDate: '2024-10-27T10:30:00Z',
orderStatus: 'pending',
// Line items
orderedItem: [
{
$type: 'OrderItem',
product: { $type: 'Product', $id: 'prod-456' },
quantity: 2,
price: 999.0,
subtotal: 1998.0,
},
{
$type: 'OrderItem',
product: { $type: 'Product', $id: 'prod-457' },
quantity: 1,
price: 299.0,
subtotal: 299.0,
},
],
// Pricing
subtotal: 2297.0,
discount: 229.7,
tax: 186.13,
shipping: 15.0,
total: 2268.43,
// Shipping address
shippingAddress: {
$type: 'PostalAddress',
street: '456 Oak Ave',
city: 'New York',
state: 'NY',
zipCode: '10001',
country: 'US',
},
// Payment
paymentMethod: {
$type: 'PaymentMethod',
type: 'CreditCard',
last4: '4242',
},
})get()
Retrieve a specific resource by type and ID.
Signature
get(
type: string,
id: string
): Promise<BusinessResource>Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| type | string | Yes | Resource type (e.g., 'Customer', 'Order') |
| id | string | Yes | Unique identifier of the resource |
Returns
Promise that resolves to the BusinessResource.
Example
const customer = await api.resources.get('Customer', 'cust-123')
console.log('Customer:', customer.name)
console.log('Email:', customer.email)
console.log('Phone:', customer.phone)Error Handling
import { ApiError } from 'business-as-code'
try {
const resource = await api.resources.get('Customer', 'cust-999')
} catch (error) {
if (error instanceof ApiError && error.statusCode === 404) {
console.error('Customer not found')
}
}update()
Update an existing resource.
Signature
update(
resource: BusinessResource
): Promise<BusinessResource>Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| resource | BusinessResource | Yes | Resource with updated data (must include $type and $id) |
Returns
Promise that resolves to the updated BusinessResource.
Example
// Get existing resource
const customer = await api.resources.get('Customer', 'cust-123')
// Update fields
customer.email = '[email protected]'
customer.phone = '+1-555-0200'
customer.tier = 'premium'
// Save changes
const updated = await api.resources.update(customer)
console.log('Updated customer:', updated.$id)Partial Update Example
// Fetch, modify, update pattern
const order = await api.resources.get('Order', 'order-789')
order.orderStatus = 'processing'
order.updatedAt = new Date().toISOString()
order.notes = 'Payment confirmed, preparing for shipment'
await api.resources.update(order)delete()
Delete a resource.
Signature
delete(
type: string,
id: string
): Promise<void>Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| type | string | Yes | Resource type |
| id | string | Yes | Resource ID |
Returns
Promise that resolves when deletion is complete.
Example
await api.resources.delete('Customer', 'cust-123')
console.log('Customer deleted')Soft Delete Pattern
// Instead of hard delete, mark as inactive
const customer = await api.resources.get('Customer', 'cust-123')
customer.status = 'inactive'
customer.deletedAt = new Date().toISOString()
await api.resources.update(customer)list()
List all resources of a specific type.
Signature
list(type: string): Promise<BusinessResource[]>Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| type | string | Yes | Resource type to list |
Returns
Promise that resolves to an array of BusinessResource objects.
Example
// Get all customers
const customers = await api.resources.list('Customer')
console.log(`Found ${customers.length} customers`)
customers.forEach((customer) => {
console.log(`- ${customer.name} (${customer.$id})`)
})Filter Client-Side
const orders = await api.resources.list('Order')
// Filter by status
const pendingOrders = orders.filter((o) => o.orderStatus === 'pending')
// Filter by date
const recentOrders = orders.filter((o) => {
const orderDate = new Date(o.orderDate)
const thirtyDaysAgo = new Date()
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30)
return orderDate > thirtyDaysAgo
})
// Filter by customer
const customerOrders = orders.filter((o) => o.customer.$id === 'cust-123')Resource Types
Common Resource Types
Based on Schema.org vocabulary:
People & Organizations:
Person- Individual personCustomer- Business customerEmployee- Staff memberOrganization- Company or institution
Products & Services:
Product- Physical or digital productService- Service offeringOffer- Product/service offer with pricing
Commerce:
Order- Customer orderInvoice- Billing invoicePayment- Payment transactionShipment- Delivery shipment
Content:
Article- Written contentVideoObject- Video contentImageObject- Image contentDataset- Data collection
Events:
Event- Business eventMeeting- Scheduled meetingWebinar- Online seminar
Example: Complete E-commerce System
// Create product catalog
const laptop = await api.resources.create({
$type: 'Product',
$id: 'prod-laptop-001',
name: 'Professional Laptop',
brand: 'TechBrand',
model: 'Pro X1',
price: 1299.0,
currency: 'USD',
availability: 'InStock',
category: 'Electronics/Computers',
})
// Create customer
const customer = await api.resources.create({
$type: 'Customer',
$id: 'cust-jane-001',
givenName: 'Jane',
familyName: 'Smith',
email: '[email protected]',
telephone: '+1-555-0100',
customerType: 'B2C',
accountCreated: '2024-01-15T00:00:00Z',
})
// Create shopping cart
const cart = await api.resources.create({
$type: 'ShoppingCart',
$id: 'cart-abc-123',
customer: { $type: 'Customer', $id: customer.$id },
items: [
{
product: { $type: 'Product', $id: laptop.$id },
quantity: 1,
price: 1299.0,
},
],
subtotal: 1299.0,
createdAt: new Date().toISOString(),
})
// Convert cart to order
const order = await api.resources.create({
$type: 'Order',
$id: 'order-2024-001',
customer: { $type: 'Customer', $id: customer.$id },
orderDate: new Date().toISOString(),
orderStatus: 'processing',
orderedItem: cart.items.map((item) => ({
$type: 'OrderItem',
product: item.product,
quantity: item.quantity,
price: item.price,
})),
total: 1299.0,
})
// Create invoice
const invoice = await api.resources.create({
$type: 'Invoice',
$id: 'inv-2024-001',
customer: { $type: 'Customer', $id: customer.$id },
referencesOrder: { $type: 'Order', $id: order.$id },
invoiceDate: new Date().toISOString(),
paymentDueDate: new Date(Date.now() + 30 * 86400000).toISOString(),
totalPaymentDue: 1299.0,
paymentStatus: 'unpaid',
})
// Process payment
const payment = await api.resources.create({
$type: 'Payment',
$id: 'pay-2024-001',
paymentFor: { $type: 'Invoice', $id: invoice.$id },
paymentMethod: 'CreditCard',
amount: 1299.0,
currency: 'USD',
paymentDate: new Date().toISOString(),
paymentStatus: 'completed',
})
// Update order status
order.orderStatus = 'paid'
await api.resources.update(order)
// Create shipment
const shipment = await api.resources.create({
$type: 'Shipment',
$id: 'ship-2024-001',
order: { $type: 'Order', $id: order.$id },
trackingNumber: 'TRACK-123456',
carrier: 'FedEx',
shipmentStatus: 'in_transit',
expectedDelivery: new Date(Date.now() + 3 * 86400000).toISOString(),
})Resource Relationships
Reference Other Resources
// Customer with organization
const customer = await api.resources.create({
$type: 'Customer',
$id: 'cust-456',
name: 'John Doe',
email: '[email protected]',
// Reference to organization
organization: {
$type: 'Organization',
$id: 'org-789',
},
// Reference to account manager
accountManager: {
$type: 'Employee',
$id: 'emp-101',
},
})Nested Resources
// Order with embedded line items
const order = await api.resources.create({
$type: 'Order',
$id: 'order-123',
customer: { $type: 'Customer', $id: 'cust-456' },
orderedItem: [
{
$type: 'OrderItem',
product: { $type: 'Product', $id: 'prod-001' },
quantity: 2,
price: 49.99,
},
{
$type: 'OrderItem',
product: { $type: 'Product', $id: 'prod-002' },
quantity: 1,
price: 99.99,
},
],
total: 199.97,
})Bidirectional Relationships
// Employee
const employee = await api.resources.create({
$type: 'Employee',
$id: 'emp-202',
name: 'Sarah Johnson',
role: 'Sales Manager',
// Works for organization
worksFor: {
$type: 'Organization',
$id: 'org-789',
},
// Manages customers
manages: [
{ $type: 'Customer', $id: 'cust-456' },
{ $type: 'Customer', $id: 'cust-457' },
],
})
// Update customer with manager reference
const customer = await api.resources.get('Customer', 'cust-456')
customer.accountManager = { $type: 'Employee', $id: 'emp-202' }
await api.resources.update(customer)Best Practices
1. Use Schema.org Types
// ✅ Good - standard Schema.org types
const resource = await api.resources.create({
$type: 'Organization', // Standard type
$id: 'org-123',
name: 'Acme Corp',
})
// ❌ Avoid - custom types without semantic meaning
const resource = await api.resources.create({
$type: 'MyCustomThing',
$id: 'thing-123',
})2. Include Required Properties
// ✅ Good - all Schema.org required properties
const product = await api.resources.create({
$type: 'Product',
$id: 'prod-123',
name: 'Widget', // Required
description: 'A useful widget',
price: 29.99,
currency: 'USD',
availability: 'InStock',
})3. Use Descriptive IDs
// ✅ Good - descriptive IDs
const customer = await api.resources.create({
$type: 'Customer',
$id: 'cust-acme-corp-2024', // Clear, descriptive
name: 'Acme Corporation',
})
// ❌ Avoid - opaque IDs without context
const customer = await api.resources.create({
$type: 'Customer',
$id: 'abc123xyz', // Not descriptive
name: 'Acme Corporation',
})4. Validate Before Create
import { ValidationError } from 'business-as-code'
function validateCustomer(data: any): void {
if (!data.$type || data.$type !== 'Customer') {
throw new ValidationError('$type', 'Must be Customer')
}
if (!data.$id) {
throw new ValidationError('$id', 'ID is required')
}
if (!data.email || !data.email.includes('@')) {
throw new ValidationError('email', 'Valid email is required')
}
}
try {
validateCustomer(customerData)
const customer = await api.resources.create(customerData)
} catch (error) {
if (error instanceof ValidationError) {
console.error(`Invalid ${error.field}: ${error.message}`)
}
}5. Handle Relationships Properly
// ✅ Good - proper references
const order = await api.resources.create({
$type: 'Order',
$id: 'order-123',
customer: {
$type: 'Customer',
$id: 'cust-456', // Reference by ID
},
})
// ❌ Avoid - embedding full objects
const order = await api.resources.create({
$type: 'Order',
$id: 'order-123',
customer: {
// Don't embed full customer
$type: 'Customer',
$id: 'cust-456',
name: 'John Doe',
email: '[email protected]',
// ... all customer data
},
})Next Steps
- Actions API - Execute actions on resources
- Searches API - Search and query resources
- Events API - Publish events when resources change