Examples
Learn from real-world examples and common use cases.
Basic CRUD Operations
Creating Resources
create-resource.ts
import { SDK } from "our-sdk";
const sdk = new SDK({
apiKey: process.env.SDK_API_KEY,
});
async function createExample() {
// Create a single resource
const resource = await sdk.create({
name: "My First Resource",
description: "This is an example",
metadata: {
tags: ["example", "tutorial"],
priority: "high",
},
});
console.log("Created:", resource);
return resource;
}
Reading Resources
read-resources.ts
async function readExample() {
// Get a single resource
const resource = await sdk.get("res_123");
// List all resources with filters
const list = await sdk.list({
filter: {
status: "active",
},
limit: 50,
});
console.log(`Found ${list.data.length} resources`);
return list;
}
Updating Resources
update-resource.ts
async function updateExample() {
const updated = await sdk.update("res_123", {
name: "Updated Name",
metadata: {
lastModified: new Date().toISOString(),
},
});
console.log("Updated:", updated);
}
Deleting Resources
delete-resource.ts
async function deleteExample() {
try {
await sdk.delete("res_123");
console.log("Resource deleted successfully");
} catch (error) {
if (error instanceof SDK.NotFoundError) {
console.log("Resource not found");
}
}
}
Error Handling
Comprehensive Error Handling
error-handling.ts
async function errorHandlingExample() {
try {
const resource = await sdk.get("res_123");
return resource;
} catch (error) {
if (error instanceof SDK.NotFoundError) {
console.error("Resource not found:", error.message);
// Handle not found case
return null;
} else if (error instanceof SDK.ValidationError) {
console.error("Validation failed:", error.details);
// Show validation errors to user
return null;
} else if (error instanceof SDK.AuthenticationError) {
console.error("Authentication failed - check your API key");
// Redirect to login or show error
throw error;
} else if (error instanceof SDK.RateLimitError) {
console.error("Rate limit exceeded, retry after:", error.retryAfter);
// Implement retry with backoff
await new Promise((resolve) =>
setTimeout(resolve, error.retryAfter * 1000)
);
return errorHandlingExample(); // Retry
} else {
console.error("Unexpected error:", error);
throw error;
}
}
}
Pagination
Cursor-based Pagination
pagination.ts
async function paginationExample() {
let cursor: string | undefined;
const allResources: Resource[] = [];
do {
const response = await sdk.list({
limit: 100,
cursor,
});
allResources.push(...response.data);
cursor = response.nextCursor;
console.log(`Fetched ${response.data.length} resources`);
} while (cursor);
console.log(`Total resources: ${allResources.length}`);
return allResources;
}
Batch Operations
Batch Create with Error Handling
batch-create.ts
async function batchCreateExample() {
const itemsToCreate = [
{ name: "Resource 1", description: "First" },
{ name: "Resource 2", description: "Second" },
{ name: "Resource 3", description: "Third" },
// ... more items
];
const result = await sdk.batchCreate(itemsToCreate);
console.log(`Successfully created: ${result.successful.length}`);
console.log(`Failed: ${result.failed.length}`);
// Handle failed items
if (result.failed.length > 0) {
console.error("Failed items:", result.failed);
// Retry failed items or log for manual review
}
return result;
}
Search & Filter
Advanced Filtering
advanced-filter.ts
async function advancedFilterExample() {
const results = await sdk.filter({
// Status must be active
status: { equals: "active" },
// Created in the last 30 days
createdAt: {
gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
},
// Name contains 'example'
name: { contains: "example" },
// Metadata tag includes 'important'
"metadata.tags": { includes: "important" },
});
return results;
}
Full-text Search
search.ts
async function searchExample() {
const results = await sdk.search("keyword", {
fields: ["name", "description", "metadata.content"],
limit: 20,
highlight: true,
});
results.forEach((result) => {
console.log(`Score: ${result.score}`);
console.log(`Match: ${result.highlight}`);
});
return results;
}
Check out the Advanced Examples for more complex use cases.
Next Steps
- Explore Advanced Examples
- Review the API Reference
- Learn about Best Practices