Thanks to visit codestin.com
Credit goes to codehooks.io

Skip to main content

API Cheat Sheet

Everything you need to build a serverless backend in one place. This cheat sheet contains all essential backend APIs for creating complete serverless applications with Codehooks.io. Quick reference for routing, authentication, NoSQL databases, workflows, queues, key-value stores, and real-time features. Each API includes direct links to detailed documentation with examples and usage patterns.

Authentication & Security - Secure your APIs with tokens, JWT, OAuth, or custom auth methods.

HTTP Routing APIs

Create REST API endpoints using Express-style route handlers for all standard HTTP methods. Route handlers receive request and response objects for processing incoming HTTP requests.

  • post(path, function) - Register POST route handlers → Details
  • get(path, function) - Register GET route handlers → Details
  • put(path, function) - Register PUT route handlers → Details
  • patch(path, function) - Register PATCH route handlers → Details
  • delete(path, function) - Register DELETE route handlers → Details
  • all(path, function) - Register handlers for all HTTP methods → Details

Middleware & Authentication APIs

Add middleware functions to process requests before they reach route handlers, and serve static or uploaded files. Authentication middleware intercepts requests without valid access tokens.

  • use(function) - Register global middleware → Details
  • auth(path, function) - Register authentication middleware → Details
  • static(options, function?) - Serve static files from source code → Details
  • storage(options, function?) - Serve files from blob storage → Details

Database/NoSQL APIs

Complete NoSQL document database with CRUD operations, schema validation, and MongoDB-style queries. All data is stored as JSON documents organized in collections.

Connection & Setup

  • Datastore.open() - Connect to datastore and return API interface → Details

Document Operations

  • insertOne(collection, document) - Insert new document → Details
  • getOne(collection, query) - Get single document by ID/query → Details
  • findOne(collection, query) - Alias for getOne → Details
  • getMany(collection, query?, options?) - Get stream of documents → Details
  • find(collection, query?, options?) - Alias for getMany → Details
  • toArray(collection, query?, options?) - Get documents as array → Details
  • updateOne(collection, query, document, operators?, options?) - Update document (patch) → Details
  • updateMany(collection, query, document, operators?, options?) - Update multiple documents → Details
  • replaceOne(collection, query, document, options?) - Replace document completely → Details
  • replaceMany(collection, query, document, options?) - Replace multiple documents → Details
  • removeOne(collection, query) - Remove document → Details
  • removeMany(collection, query, options?) - Remove multiple documents → Details

Schema Management

  • setSchema(collection, schema) - Add JSON-Schema validation → Details
  • getSchema(collection) - Get collection schema → Details
  • removeSchema(collection) - Remove JSON-Schema validation → Details

Collection Management

  • createCollection(collection, options?) - Create new collection → Details
  • dropCollection(collection) - Delete collection → Details

Key-Value Store APIs

Fast in-memory key-value storage for caching, session management, and temporary data. Supports optional TTL (time-to-live) for automatic expiration.

  • set(key, value, options?) - Set key-string value pair with optional TTL → Details
  • setObj(key, value, options?) - Set key-object pair with optional TTL → Details
  • get(key, options?) - Get string value by key → Details
  • getObj(key, options?) - Get object value by key → Details
  • getAll(keyPattern, options?) - Get all key-value pairs matching pattern → Details
  • del(key, options?) - Delete key-value pair → Details
  • delAll(key, options?) - Delete all key-value pairs matching pattern → Details
  • incr(key, value, options?) - Increment numeric value → Details
  • decr(key, value, options?) - Decrement numeric value → Details

Queue & Background Processing APIs

Offload time-consuming tasks to background worker queues for asynchronous processing. Workers can process jobs in parallel based on your plan limits.

  • worker(name, function, options?) - Register worker functions → Details
  • enqueue(topic, document, options?) - Add job to queue → Details
  • enqueueFromQuery(collection, query, topic, options?) - Queue items from database query → Details

Job Scheduling APIs

Schedule recurring tasks with cron expressions or run one-time delayed jobs at specific times. Perfect for periodic maintenance, reports, and scheduled notifications.

  • job(cronExpression, worker) - Register scheduled cron jobs → Details
  • schedule.runAt(when, data, worker) - Schedule one-time delayed job → Details
  • schedule.run(data, worker) - Execute worker immediately → Details

Workflow APIs

Build reliable multi-step workflows with persistent state management and automatic error recovery. Workflows can pause, resume, and handle timeouts across long-running business processes.

Workflow Management

  • createWorkflow(name, description, steps, config?) - Create new workflow definition → Details
  • start(initialState) - Start new workflow instance → Details
  • updateState(instanceId, state, options?) - Update workflow state → Details
  • setState(instanceId, stateData) - Set complete workflow state → Details
  • continue(instanceId, reset?) - Continue paused workflow → Details
  • getWorkflowStatus(id) - Get workflow status → Details
  • getInstances(filter) - List workflow instances → Details
  • cancelWorkflow(id) - Cancel workflow instance → Details

Error Recovery & Monitoring

  • continueAllTimedOut() - Continue all timed out workflows → Details
  • findTimedOutSteps(filter?) - Find timed out workflow steps → Details

Event Management

  • on(event, listener) - Register event listener → Details
  • once(event, listener) - Register one-time event listener → Details
  • off(event, listener) - Remove event listener → Details
  • emit(event, data) - Emit custom event → Details

Configuration

  • Pass configuration options as the last argument to createWorkflow()Details

File Management APIs

Store and retrieve files in blob storage with support for text, binary, and streaming operations. Ideal for user uploads, images, documents, and media files.

  • filestore.readFile(path) - Read file content as text → Details
  • filestore.readFileAsBuffer(path) - Read file content as buffer → Details
  • filestore.getReadStream(path) - Read file as binary stream → Details
  • filestore.saveFile(path, filestream) - Write binary stream to file → Details
  • filestore.deleteFile(path) - Delete file → Details
  • filestore.list(path) - List files in directory → Details

Real-time Communication APIs

Push live updates to connected clients using server-sent events (SSE). Build real-time features like chat, notifications, and live data feeds.

  • realtime.createChannel(channel) - Create real-time channel → Details
  • realtime.publishEvent(channel, data, query?) - Publish event to channel → Details
  • realtime.createListener(channel, data) - Create listener for channel → Details
  • realtime.getListener(channel, listenerID) - Get specific listener → Details
  • realtime.getListeners(channel) - Get all listeners for channel → Details
  • realtime.removeListener(channel, listenerID) - Remove listener → Details

Inter-Service Communication APIs

Make high-speed authenticated requests between Codehooks applications for microservices architecture. Optimized for internal app-to-app communication within the platform.

  • internalFetch(url, options?) - Make authenticated requests to other Codehooks APIs → Details

Template & Configuration APIs

Configure application settings and auto-generate complete CRUD REST APIs with a single function call. Use crudlify to instantly create database endpoints without writing route handlers.

  • set(key, val) - Set application configuration → Details
  • crudlify(schema?, options?) - Auto-generate CRUD REST API → Details

Application Lifecycle APIs

Initialize and bind your application to the serverless runtime. Must be called and exported as the default export from your main application file.

  • init(function?) - Initialize application and return manifest → Details
  • start(function?) - Alias for init() method → Details

Database REST API Endpoints

Auto-generated RESTful endpoints for database operations when using crudlify(). All standard CRUD operations are available with query support and pagination.

When using crudlify(), these endpoints are automatically created:

OperationMethodEndpointDescription
List allGET/:collectionGet all documents → Details
QueryGET/:collection?queryGet documents by query → Details
Get by IDGET/:collection/:idGet single document → Details
CreatePOST/:collectionCreate new document → Details
UpdatePATCH/:collection/:idUpdate document → Details
ReplacePUT/:collection/:idReplace document → Details
DeleteDELETE/:collection/:idDelete document → Details

Authentication & Security

Secure your API endpoints and authenticate users with multiple authentication methods. Choose the approach that fits your use case: API tokens for service-to-service calls, JWT for user authentication, or custom authentication logic.

Authentication Methods

  • API Tokens - Add x-apikey header for app-to-app authentication. Create tokens with coho add-token or via web console → Details
  • JWT/JWKS - User authentication via Auth0, Clerk, or Stack-Auth. Configure JWKS endpoint with coho jwks <url>Details
  • Admin Tokens - For CLI automation and CI/CD. Create with coho add-admintoken and use with --admintoken flag → Details
  • IP Whitelisting - Restrict API access by IP address using coho whitelist <ip> or web console → Details
  • Custom Auth - Full control with codehooks-auth package. Includes OAuth (Google, GitHub), email verification, and OTP → Details

Quick Examples

# Create read-only API token
coho add-token --readonly

# Configure JWT authentication
coho jwks https://your-tenant.auth0.com/.well-known/jwks.json

# Use API token in requests
curl https://your-app.api.codehooks.io/api \
-H 'x-apikey: your-token-here'

Query Syntax Examples

MongoDB-style query syntax for filtering database documents with comparison, logical, and array operators. Queries can be written in JavaScript objects or URL parameters.

NoSQL Queries

// Simple equality
{
status: 'active';
}

// Comparison operators
{
age: {
$gt: 18;
}
}
{
price: {
$lte: 100;
}
}

// Logical operators
{
$and: [{ status: 'active' }, { age: { $gte: 18 } }];
}

// Array operations
{
tags: {
$in: ['javascript', 'nodejs'];
}
}

// Regular expressions
{
name: {
$regex: /john/i;
}
}

URL Query Parameters

# Simple query
?status=active&limit=10

# Advanced query
?q={"age":{"$gt":18}}&sort=name&fields=name,email

Common Usage Patterns

Real-world code examples showing typical patterns for building APIs, database operations, background processing, and workflows. Copy and adapt these patterns for your own applications.

Basic API Setup

import { app } from 'codehooks-js';

// Auto-generate CRUD API
app.crudlify();

// Custom routes
app.get('/hello', (req, res) => {
res.json({ message: 'Hello World' });
});

export default app.init();

Database Operations

import { Datastore } from 'codehooks-js';

async function myFunc() {
const conn = await Datastore.open();

// Insert document
const doc = await conn.insertOne('users', { name: 'John' });

// Query documents
const users = await conn.getMany('users', { active: true }).toArray();

// Key-value operations
await conn.set('session:123', { userId: 'abc' }, { ttl: 3600000 });
}
...

Background Processing

// worker options, use 5 parallel workers
const workerOpt = {workers: 5};
// Register worker
app.worker('emailWorker', async (req, res) => {
console.log('Processing email:', req.body.payload);
res.end();
}, workerOpt);

// Queue job
async function myFunc() {
const conn = await Datastore.open();
await conn.enqueue('emailWorker', { email: '[email protected]' });
}
...

Workflow Processing

// Create a workflow with persistent state
const workflow = app.createWorkflow(
'orderProcessing',
'Process customer orders',
{
start: async (state, goto) => {
state.orderId = state.orderId || generateOrderId();
goto('validatePayment', state);
},

validatePayment: async (state, goto) => {
// Validate payment logic here
if (state.paymentValid) {
goto('fulfillOrder', state);
} else {
goto('handlePaymentError', state);
}
},

fulfillOrder: async (state, goto) => {
state.status = 'fulfilled';
goto(null, state); // Complete workflow
},
}
);

// Start workflow instance
const orderWorkflow = await workflow.start({
customerId: '123',
amount: 99.99,
});

Links: