Task API
Simple REST API for managing scheduled tasks.
Create Task
- POST /api/tasks/
Create a new task.
Request:
{ "task_name": "process_data", "task_args": ["file.csv"], "task_kwargs": {"format": "csv"}, "callback_url": "https://example.com/webhook", "schedule_time": "2025-01-01T12:00:00Z" }
Parameters:
task_name(string, required): Name of the tasktask_args(array, optional): Task argumentstask_kwargs(object, optional): Task keyword argumentscallback_url(string, optional): Webhook URLschedule_time(string, optional): When to execute (ISO 8601 format)
Response:
{ "task_id": "123e4567-e89b-12d3-a456-426614174000", "task_name": "process_data", "status": "scheduled", "created_at": "2025-01-01T10:00:00Z" }
List Tasks
- GET /api/tasks/
Get all tasks for the current user.
Response:
{ "count": 2, "results": [ { "task_id": "123e4567-e89b-12d3-a456-426614174000", "task_name": "process_data", "status": "scheduled", "created_at": "2025-01-01T10:00:00Z" } ] }
Get Task
- GET /api/tasks/(task_id)/
Get a specific task.
Response:
{ "task_id": "123e4567-e89b-12d3-a456-426614174000", "task_name": "process_data", "task_args": ["file.csv"], "task_kwargs": {"format": "csv"}, "callback_url": "https://example.com/webhook", "schedule_time": "2025-01-01T12:00:00Z", "status": "scheduled", "created_at": "2025-01-01T10:00:00Z" }
Delete Task
- DELETE /api/tasks/(task_id)/
Delete a task.
Response:
204 No Content
Webhook
When a task’s time arrives, a POST request is sent to the callback_url:
{
"task_id": "123e4567-e89b-12d3-a456-426614174000",
"task_name": "process_data",
"task_args": ["file.csv"],
"task_kwargs": {"format": "csv"},
"triggered_at": "2025-01-01T12:00:00Z"
}
Example Usage
This section provides complete examples of how to schedule tasks and handle webhooks.
Scheduling an Email Task
Here’s how to schedule a “send_email” task using curl:
curl -X POST http://localhost:8000/api/tasks/ \
-H "Authorization: Api-Key YOUR_API_KEY" \
# Get your API key from https://orkera.com/
-H "Content-Type: application/json" \
-d '{
"task_name": "send_email",
"task_args": ["user@example.com"],
"task_kwargs": {
"subject": "Welcome to Orkera!",
"template": "welcome_email",
"user_id": 123,
"priority": "high"
},
"callback_url": "https://your-app.com/webhooks/email-complete",
"schedule_time": "2025-01-15T14:30:00Z"
}'
Response:
{
"task_id": "550e8400-e29b-41d4-a716-446655440000",
"task_name": "send_email",
"status": "scheduled",
"created_at": "2025-01-15T10:00:00Z"
}
When the scheduled time arrives, Orkera will send this webhook to your callback URL:
{
"task_id": "550e8400-e29b-41d4-a716-446655440000",
"task_name": "send_email",
"task_args": ["user@example.com"],
"task_kwargs": {
"subject": "Welcome to Orkera!",
"template": "welcome_email",
"user_id": 123,
"priority": "high"
},
"triggered_at": "2025-01-15T14:30:00Z"
}
Webhook Server Examples
FastAPI Webhook Server (Python)
Here’s a complete FastAPI server to handle email webhooks:
from fastapi import FastAPI, Request, HTTPException
from pydantic import BaseModel
from typing import List, Dict, Any
import httpx
import logging
from datetime import datetime
app = FastAPI(title="Email Webhook Handler")
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class WebhookPayload(BaseModel):
task_id: str
task_name: str
task_args: List[Any]
task_kwargs: Dict[str, Any]
triggered_at: str
@app.post("/webhooks/email-complete")
async def handle_email_webhook(payload: WebhookPayload):
"""Handle email task webhooks from Orkera"""
logger.info(f"Received webhook for task {payload.task_id}")
try:
# Extract email details from the webhook
recipient_email = payload.task_args[0]
subject = payload.task_kwargs.get("subject")
template = payload.task_kwargs.get("template")
user_id = payload.task_kwargs.get("user_id")
priority = payload.task_kwargs.get("priority", "normal")
# Log the webhook details
logger.info(f"Processing email to {recipient_email}")
logger.info(f"Subject: {subject}, Template: {template}")
# Here you would implement your actual email sending logic
await send_email(
to_email=recipient_email,
subject=subject,
template=template,
user_id=user_id,
priority=priority
)
logger.info(f"Email sent successfully for task {payload.task_id}")
return {"status": "success", "message": "Email processed"}
except Exception as e:
logger.error(f"Error processing email webhook: {str(e)}")
raise HTTPException(status_code=500, detail="Failed to process email")
async def send_email(to_email: str, subject: str, template: str,
user_id: int, priority: str):
"""Mock email sending function - replace with your actual email service"""
# Example: Send email using your preferred service (SendGrid, AWS SES, etc.)
# async with httpx.AsyncClient() as client:
# response = await client.post(
# "https://api.sendgrid.com/v3/mail/send",
# headers={"Authorization": f"Bearer {SENDGRID_API_KEY}"},
# json={
# "personalizations": [{"to": [{"email": to_email}]}],
# "from": {"email": "noreply@yourcompany.com"},
# "subject": subject,
# "content": [{"type": "text/html", "value": f"<h1>{subject}</h1>"}]
# }
# )
# For demo purposes, just log the email details
logger.info(f"Would send email to {to_email} with subject '{subject}'")
logger.info(f"Using template '{template}' for user {user_id} (priority: {priority})")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8001)
To run the FastAPI server:
pip install fastapi uvicorn httpx
python webhook_server.py
Node.js Webhook Server
Here’s a complete Node.js/Express server to handle email webhooks:
const express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios');
const app = express();
const PORT = 8001;
// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Webhook endpoint for email tasks
app.post('/webhooks/email-complete', async (req, res) => {
try {
const {
task_id,
task_name,
task_args,
task_kwargs,
triggered_at
} = req.body;
console.log(`Received webhook for task ${task_id}`);
// Extract email details
const recipientEmail = task_args[0];
const { subject, template, user_id, priority = 'normal' } = task_kwargs;
console.log(`Processing email to ${recipientEmail}`);
console.log(`Subject: ${subject}, Template: ${template}`);
// Send the actual email
await sendEmail({
toEmail: recipientEmail,
subject,
template,
userId: user_id,
priority
});
console.log(`Email sent successfully for task ${task_id}`);
res.json({
status: 'success',
message: 'Email processed successfully'
});
} catch (error) {
console.error('Error processing email webhook:', error);
res.status(500).json({
status: 'error',
message: 'Failed to process email'
});
}
});
async function sendEmail({ toEmail, subject, template, userId, priority }) {
// Example: Send email using your preferred service
// This is a mock implementation - replace with your actual email service
console.log(`Would send email to ${toEmail} with subject '${subject}'`);
console.log(`Using template '${template}' for user ${userId} (priority: ${priority})`);
// Example using SendGrid:
// const sgMail = require('@sendgrid/mail');
// sgMail.setApiKey(process.env.SENDGRID_API_KEY);
// const msg = {
// to: toEmail,
// from: 'noreply@yourcompany.com',
// subject: subject,
// html: `<h1>${subject}</h1><p>This is a ${template} email for user ${userId}</p>`
// };
// await sgMail.send(msg);
}
// Health check endpoint
app.get('/health', (req, res) => {
res.json({ status: 'healthy', timestamp: new Date().toISOString() });
});
app.listen(PORT, () => {
console.log(`Email webhook server running on port ${PORT}`);
console.log(`Webhook endpoint: http://localhost:${PORT}/webhooks/email-complete`);
});
To run the Node.js server:
npm init -y
npm install express body-parser axios
node webhook_server.js
Testing the Complete Flow
Start your webhook server (FastAPI or Node.js)
Schedule an email task:
curl -X POST http://localhost:8000/api/tasks/ \ -H "Authorization: Api-Key YOUR_API_KEY" \ # Get your API key from https://orkera.com/ -H "Content-Type: application/json" \ -d '{ "task_name": "send_email", "task_args": ["test@example.com"], "task_kwargs": { "subject": "Test Email", "template": "test_template", "user_id": 456, "priority": "high" }, "callback_url": "http://localhost:8001/webhooks/email-complete", "schedule_time": "2025-01-15T14:35:00Z" }'
Wait for the scheduled time (or use a past time for immediate testing)
Check your webhook server logs to see the incoming webhook
Verify the email processing in your server logs
This complete example shows how to: - Schedule tasks with complex arguments and keyword arguments - Handle webhooks in both Python (FastAPI) and Node.js - Process task data and execute business logic - Handle errors and provide proper responses