Quickstart Guide
Get started with the Taruvi SDK in 5 minutes. This guide will walk you through creating your first application using the SDK.
Prerequisites
Before you begin, ensure you have:
- ✅ Installed the SDK (Installation Guide)
- ✅ Access to a Taruvi instance (URL and credentials)
- ✅ An application slug (create one in the Taruvi dashboard)
Step 1: Install the SDK
- Python
- JavaScript
pip install taruvi
npm install @taruvi/sdk
Step 2: Setup Credentials
Create a .env file in your project root:
- Python
- JavaScript
# .env
TARUVI_API_URL=https://api.taruvi.cloud
TARUVI_APP_SLUG=my-app
TARUVI_USERNAME=alice@example.com
TARUVI_PASSWORD=your-password
# .env (for Node.js)
TARUVI_API_KEY=your-site-api-key
TARUVI_APP_SLUG=my-app
TARUVI_BASE_URL=https://site.taruvi.cloud
# .env.local (for Next.js)
NEXT_PUBLIC_TARUVI_API_KEY=your-site-api-key
NEXT_PUBLIC_TARUVI_APP_SLUG=my-app
NEXT_PUBLIC_TARUVI_BASE_URL=https://site.taruvi.cloud
Never commit your .env file to version control. Add it to .gitignore!
Step 3: Write Your First Script
Create a file and add the following code:
- Python
- JavaScript
# Import the SDK
from taruvi import Client
from dotenv import load_dotenv
import os
# Load environment variables
load_dotenv()
# Create client
client = Client(
api_url=os.getenv("TARUVI_API_URL"),
app_slug=os.getenv("TARUVI_APP_SLUG")
)
# Authenticate
auth_client = client.auth.signInWithPassword(
username=os.getenv("TARUVI_USERNAME"),
password=os.getenv("TARUVI_PASSWORD")
)
# Query database
print("📊 Fetching users...")
users = auth_client.database.query("users").page_size(5).get()
print(f"✅ Found {len(users)} users")
for user in users:
print(f" - {user.get('username', 'N/A')}: {user.get('email', 'N/A')}")
# Execute a function
print("\n🚀 Executing function...")
result = auth_client.functions.execute(
"hello-world",
params={"name": "Alice"}
)
print(f"✅ Function result: {result.get('data', {})}")
print("\n🎉 Quickstart complete!")
// Import the SDK
import 'dotenv/config'
import { Client, Database, Functions } from '@taruvi/sdk'
// Create client
const client = new Client({
apiKey: process.env.TARUVI_API_KEY!,
appSlug: process.env.TARUVI_APP_SLUG!,
baseUrl: process.env.TARUVI_BASE_URL!
})
// Instantiate services
const database = new Database(client)
const functions = new Functions(client)
async function main() {
// Query database
console.log("📊 Fetching users...")
const users = await database.from("users").execute()
console.log(`✅ Found ${users.length} users`)
users.slice(0, 5).forEach(user => {
console.log(` - ${user.username}: ${user.email}`)
})
// Execute a function
console.log("\n🚀 Executing function...")
const result = await functions.execute("hello-world", {
params: { name: "Alice" }
})
console.log(`✅ Function result:`, result.data)
console.log("\n🎉 Quickstart complete!")
}
main().catch(console.error)
Step 4: Run Your Script
- Python
- JavaScript
python quickstart.py
Expected Output:
📊 Fetching users...
✅ Found 5 users
- alice: alice@example.com
- bob: bob@example.com
- charlie: charlie@example.com
- diana: diana@example.com
- eve: eve@example.com
🚀 Executing function...
✅ Function result: {'message': 'Hello, Alice!'}
🎉 Quickstart complete!
# If using TypeScript
npx tsx quickstart.ts
# If using Node.js with ES modules
node quickstart.js
Expected Output:
📊 Fetching users...
✅ Found 5 users
- alice: alice@example.com
- bob: bob@example.com
- charlie: charlie@example.com
- diana: diana@example.com
- eve: eve@example.com
🚀 Executing function...
✅ Function result: { message: 'Hello, Alice!' }
🎉 Quickstart complete!
What Just Happened?
Let's break down what the code does:
1. Import and Setup
from taruvi import Client
Import the main Client class that provides access to all SDK features.
2. Create Client
client = Client(api_url="...", app_slug="...")
Initialize the client with your Taruvi instance URL and application slug.
3. Authenticate
- Python
- JavaScript
auth_client = client.auth.signInWithPassword(
username="alice@example.com",
password="secret123"
)
Authenticate using username/password. The SDK returns a new client instance with authentication credentials attached.
const client = new Client({
apiKey: "site-api-key",
// ...
})
JavaScript uses an API key for authentication. For browser-based auth, see the Authentication Guide.
4. Query Database
users = auth_client.database.query("users").page_size(5).get()
Use the query builder to fetch data with filters, sorting, and pagination.
5. Execute Function
result = auth_client.functions.execute("hello-world", params={...})
Execute serverless functions with custom parameters.
Try More Examples
Example 1: Query with Filters
- Python
- JavaScript
# Find active users over 18 years old
active_adults = (
auth_client.database.query("users")
.filter("is_active", "eq", True)
.filter("age", "gte", 18)
.sort("created_at", "desc")
.page_size(10)
.get()
)
print(f"Found {len(active_adults)} active adult users")
// Find active users over 18 years old
const activeAdults = await database
.from("users")
.filter({
is_active: true,
age__gte: 18
})
.execute()
console.log(`Found ${activeAdults.length} active adult users`)
Example 2: Upload a File
- Python
- JavaScript
# Upload a file to storage
with open("document.pdf", "rb") as f:
result = auth_client.storage.from_("documents").upload(
files=[("document.pdf", f)],
paths=["uploads/document.pdf"]
)
print(f"File uploaded: {result[0]['path']}")
// Upload a file to storage
const storage = new Storage(client)
const file = new File([blob], "document.pdf")
const result = await storage
.from("documents")
.upload({
files: [file],
paths: ["uploads/document.pdf"]
})
.execute()
console.log(`File uploaded: ${result[0].path}`)
Example 3: Execute Async Function
- Python
- JavaScript
import time
# Execute long-running function in background
result = auth_client.functions.execute(
"process-large-dataset",
params={"dataset_id": 123},
is_async=True
)
# Get task ID
task_id = result['invocation']['celery_task_id']
print(f"Task started: {task_id}")
# Poll for result
while True:
task_result = auth_client.functions.get_result(task_id)
status = task_result['data']['status']
if status == 'SUCCESS':
print(f"Task completed: {task_result['data']['result']}")
break
elif status == 'FAILURE':
print(f"Task failed: {task_result['data']['error']}")
break
print("Task still running...")
time.sleep(2)
// Execute long-running function in background
const result = await functions.execute("process-large-dataset", {
async: true,
params: { dataset_id: 123 }
})
const taskId = result.invocation.celery_task_id
console.log(`Task started: ${taskId}`)
// In JavaScript, you would typically use polling or webhooks
// to get the result when the task completes
Example 4: Create and Update Records
- Python
- JavaScript
# Create a new user
new_user = auth_client.database.create("users", {
"username": "frank",
"email": "frank@example.com",
"age": 25
})
print(f"Created user: {new_user['id']}")
# Update the user
updated_user = auth_client.database.update(
"users",
new_user['id'],
{"age": 26}
)
print(f"Updated age to: {updated_user['age']}")
# Delete the user
auth_client.database.delete("users", record_id=new_user['id'])
print("User deleted")
// Create a new user
const newUser = await database
.from("users")
.create({
username: "frank",
email: "frank@example.com",
age: 25
})
.execute()
console.log(`Created user: ${newUser.id}`)
// Update the user
const updatedUser = await database
.from("users")
.get(newUser.id)
.update({ age: 26 })
.execute()
console.log(`Updated age to: ${updatedUser.age}`)
// Delete the user
await database
.from("users")
.get(newUser.id)
.delete()
.execute()
console.log("User deleted")
Common Patterns
Using Context Managers (Python)
from taruvi import Client
# Client automatically closes connections when done
with Client(api_url="...", app_slug="...") as client:
auth_client = client.auth.signInWithPassword(username="...", password="...")
users = auth_client.database.query("users").get()
# Connection automatically closed
Error Handling
- Python
- JavaScript
from taruvi import Client, NotFoundError, ValidationError, TaruviError
client = Client(api_url="...", app_slug="...")
try:
auth_client = client.auth.signInWithPassword(
username="alice@example.com",
password="secret123"
)
user = auth_client.database.get("users", record_id=999)
except NotFoundError as e:
print(f"User not found: {e.message}")
except ValidationError as e:
print(f"Validation error: {e.message}")
print(f"Details: {e.details}")
except TaruviError as e:
print(f"SDK error: {e.message} (status: {e.status_code})")
import { Client, Database } from '@taruvi/sdk'
const client = new Client({...})
const database = new Database(client)
try {
const user = await database.from("users").get(999).execute()
} catch (error) {
if (error.response?.status === 404) {
console.error("User not found")
} else if (error.response?.status === 400) {
console.error("Validation error:", error.response.data)
} else {
console.error("SDK error:", error.message)
}
}
The SDK provides comprehensive error handling. See specific API documentation for error details.
Next Steps
Now that you've completed the quickstart:
Getting Help
- Documentation: Browse the API Reference
- Examples: Check the Examples Cookbook
- Issues: Report bugs on GitHub
- Community: Join the discussion
Related Documentation
- Installation - Detailed installation guide
- SDK Overview - SDK features and capabilities
- Authentication - Authentication methods