Initialize the client with your API key
Inserts a new record into the specified WorqDB table. This endpoint allows you to add new data to your database tables with optional control over the document identifier.
POST https://api.worqhat.com/db/insert
What Does This Endpoint Do?
This endpoint creates new records in your database tables. Think of it like adding a new row to a spreadsheet - you specify which table to add to and what data should be included in the new record.
When to Use Insert Data
You'll find this endpoint useful when you need to:
- Create user accounts: Add new users to your system
- Store form submissions: Save data submitted through forms
- Log events: Record activities or events as they happen
- Add inventory items: Create new product entries
- Create content: Add new articles, posts, or other content
- Store application data: Persist any data your application needs to save
How It Works
- You specify the table name where you want to insert data
- You provide the data as key-value pairs
- You can optionally specify a documentId to use as the primary key
- The API inserts the record and returns the complete inserted data
Code Examples
Example 1: Basic Insert
This example shows how to insert a record with an auto-generated documentId.
insert-record.js
import Worqhat from 'worqhat';// Initialize the client with your API keyconst client = new Worqhat({apiKey: process.env.WORQHAT_API_KEY, // Always use environment variables for API keys});async function createUser() {try { // Call the insertRecord method const response = await client.db.insertRecord({ table: 'users', // The table to insert into data: { // The data to insert name: 'John Doe', email: 'john@example.com', role: 'user', active: true }, environment: process.env.WORQHAT_ENVIRONMENT || 'production' // Defaults to production }); // Handle the successful response console.log('User created with ID:', response.data.documentId); console.log('Created user:', response.data); return response;} catch (error) { // Handle any errors console.error('Error creating user:', error.message);}}// Call the functioncreateUser();Example 2: Insert with Custom Document ID
This example shows how to insert a record with a custom documentId that you specify.
insert-custom-id.js
import Worqhat from 'worqhat';// Initialize the client with your API keyconst client = new Worqhat({apiKey: process.env.WORQHAT_API_KEY,});async function createProductWithCustomId() {try { // Generate a custom ID const customId = `prod_${Date.now()}`; // Call the insertRecord method with custom documentId const response = await client.db.insertRecord({ table: 'products', // The table to insert into data: { // The data to insert documentId: customId, // Specify your own document ID name: 'Premium Widget', price: 99.99, inStock: true, category: 'electronics' }, environment: process.env.WORQHAT_ENVIRONMENT || 'production' // Defaults to production }); // Handle the successful response console.log(`Product created with custom ID: ${response.data.documentId}`); return response;} catch (error) { console.error('Error creating product:', error.message);}}createProductWithCustomId();Example 3: Batch Insert with Array of JSON Objects
This example shows how to insert multiple records at once by providing an array of JSON objects.
batch-insert.js
import Worqhat from 'worqhat';// Initialize the client with your API keyconst client = new Worqhat({apiKey: process.env.WORQHAT_API_KEY,});async function createMultipleProducts() {try { // Call the insertRecord method with an array of data objects const response = await client.db.insertRecord({ table: 'products', // The table to insert into data: [ // Array of data objects to insert { name: 'Basic Widget', price: 19.99, inStock: true, category: 'essentials' }, { name: 'Standard Widget', price: 49.99, inStock: true, category: 'essentials' }, { name: 'Premium Widget', price: 99.99, inStock: false, category: 'premium' } ], environment: process.env.WORQHAT_ENVIRONMENT || 'production' // Defaults to production }); // Handle the successful response console.log(`Inserted ${response.data.length} products`); console.log('Created products:', response.data); return response;} catch (error) { console.error('Error creating products:', error.message);}}createMultipleProducts();Request Body Explained
The name of the table where you want to insert the record. For example, users, products, or orders.
The data to insert, which can be provided in two formats:
Single Object Format: A single JSON object with key-value pairs where each key represents a field name, and its value is the data you want to store.
Array Format: An array of JSON objects for batch insertion of multiple records at once. Each object in the array follows the same structure as the single object format.
In either format, you can optionally include a documentId field in each object to specify your own unique identifier for the record. If not provided, the system will generate one automatically.
Response Fields Explained
true if the insert was successful, false otherwise.
For single record inserts:
- The complete inserted record as an object, including any auto-generated fields like
documentId(if you didn't specify one) and all the data you provided in the request.
For batch inserts:
- An array of objects, where each object represents a successfully inserted record with its complete data.
A human-readable message describing the result of the operation.
Example Response
Single Record Insert
response.json
{"success": true,"data": { "documentId": "doc_12345abcde", "name": "John Doe", "email": "john@example.com", "role": "user", "active": true},"message": "Record inserted successfully"}Batch Insert
batch-response.json
{"success": true,"data": [ { "documentId": "doc_12345abcde", "name": "Basic Widget", "price": 19.99, "inStock": true, "category": "essentials" }, { "documentId": "doc_67890fghij", "name": "Standard Widget", "price": 49.99, "inStock": true, "category": "essentials" }, { "documentId": "doc_54321klmno", "name": "Premium Widget", "price": 99.99, "inStock": false, "category": "premium" }],"message": "3 records inserted successfully"}Common Errors and How to Fix Them
| Error | Cause | Solution |
|---|---|---|
| "Table not found" | The specified table doesn't exist | Check your table name for typos |
| "Duplicate documentId" | The documentId you provided already exists | Use a different documentId or let the system generate one |
| "Missing required field" | You didn't provide a required parameter | Make sure you include table and data fields |
| "Unauthorized" | Invalid or missing API key | Check that you're using a valid API key |
Tips for Successful Inserts
- If you need to reference the record later, save the returned
documentId - For records that need a predictable ID, provide your own
documentId - For records where the ID doesn't matter, let the system generate one
- The
documentIdis used as the primary key for all operations (update, delete, query) - The system will handle all internal record management automatically
