API Documentation

Complete reference for Base44 SDK and integrations

Quick Start

Import the SDK

import { base44 } from '@/api/base44Client';

Basic Usage

// Get current user
const user = await base44.auth.me();

// Fetch data
const invoices = await base44.entities.Invoice.list();

// Call AI
const result = await base44.integrations.Core.InvokeLLM({
  prompt: "Your prompt here"
});
Authentication
GET
base44.auth.me()

Get current authenticated user

const user = await base44.auth.me();
// Returns: { id, email, full_name, role }
GET
base44.auth.isAuthenticated()

Check if user is authenticated

const isAuth = await base44.auth.isAuthenticated();
// Returns: boolean
POST
base44.auth.updateMe(data)

Update current user's profile

await base44.auth.updateMe({
  full_name: "John Doe",
  custom_field: "value"
});
POST
base44.auth.logout(redirectUrl?)

Logout current user (optional redirect)

base44.auth.logout('/custom-page'); 
// Or without redirect:
base44.auth.logout();
POST
base44.auth.redirectToLogin(nextUrl?)

Redirect to login page

base44.auth.redirectToLogin('/dashboard');
Entities (Database)
GET
base44.entities.{Entity}.list(sort?, limit?)

List all records with optional sorting and limit

// Get all records (default: no limit)
const all = await base44.entities.Invoice.list();

// Sort descending by created_date, limit 100
const recent = await base44.entities.Invoice.list('-created_date', 100);

// Sort ascending by amount
const sorted = await base44.entities.Invoice.list('total_amount', 50);
GET
base44.entities.{Entity}.filter(query, sort?, limit?)

Filter records with MongoDB-style queries

// Simple filter
const paid = await base44.entities.Invoice.filter({ status: 'paid' });

// Advanced operators: $gte, $lte, $gt, $lt, $ne, $in
const overdue = await base44.entities.Invoice.filter({
  status: 'overdue',
  total_amount: { $gte: 1000 },
  due_date: { $lt: new Date().toISOString() }
}, '-due_date', 50);

// Array contains
const activeClients = await base44.entities.Contact.filter({
  tags: { $in: ['vip', 'active'] }
});
GET
base44.entities.{Entity}.schema()

Get entity JSON schema (without built-in fields)

const schema = await base44.entities.Invoice.schema();
// Returns the entity definition without id, created_date, etc.
POST
base44.entities.{Entity}.create(data)

Create a new record

const invoice = await base44.entities.Invoice.create({
  client_id: "123",
  invoice_number: "INV-2026-001",
  total_amount: 5000,
  status: "draft",
  due_date: "2026-02-01"
});
POST
base44.entities.{Entity}.bulkCreate(dataArray)

Create multiple records at once

const invoices = await base44.entities.Invoice.bulkCreate([
  { client_id: "123", total_amount: 1000 },
  { client_id: "456", total_amount: 2000 },
  { client_id: "789", total_amount: 3000 }
]);
PUT
base44.entities.{Entity}.update(id, data)

Update a single record by ID

await base44.entities.Invoice.update(invoiceId, {
  status: "paid",
  paid_date: new Date().toISOString(),
  payment_method: "credit_card"
});
DELETE
base44.entities.{Entity}.delete(id)

Delete a single record by ID

await base44.entities.Invoice.delete(invoiceId);
AI Integrations
POST
base44.integrations.Core.InvokeLLM(params)

Call LLM with optional structured JSON output

// Simple text response
const text = await base44.integrations.Core.InvokeLLM({
  prompt: "Write a professional email for invoice follow-up"
});

// Structured JSON response
const analysis = await base44.integrations.Core.InvokeLLM({
  prompt: "Analyze this invoice and suggest payment plan",
  add_context_from_internet: false,
  response_json_schema: {
    type: "object",
    properties: {
      payment_plan: { 
        type: "array", 
        items: { 
          type: "object",
          properties: {
            amount: { type: "number" },
            date: { type: "string" }
          }
        }
      },
      risk_score: { type: "number" }
    }
  }
});

// With web search context
const research = await base44.integrations.Core.InvokeLLM({
  prompt: "What are the current market trends in logistics?",
  add_context_from_internet: true
});

// With file/image context
const imageAnalysis = await base44.integrations.Core.InvokeLLM({
  prompt: "Extract text from this document",
  file_urls: ["https://example.com/document.pdf"]
});
POST
base44.integrations.Core.GenerateImage(params)

Generate AI images (5-10 seconds)

const result = await base44.integrations.Core.GenerateImage({
  prompt: "Professional business logo with blue gradient, modern style, minimalist"
});
console.log(result.url); // Use this URL in <img> tags

// With reference images
const styled = await base44.integrations.Core.GenerateImage({
  prompt: "Product photo in same style as reference",
  existing_image_urls: ["https://example.com/reference.jpg"]
});
POST
base44.integrations.Core.UploadFile(params)

Upload file to public storage

// From file input
const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];

const { file_url } = await base44.integrations.Core.UploadFile({
  file: file
});
console.log(file_url); // Public URL
POST
base44.integrations.Core.UploadPrivateFile(params)

Upload file to private storage

const { file_uri } = await base44.integrations.Core.UploadPrivateFile({
  file: fileObject
});
// file_uri is not publicly accessible, use CreateFileSignedUrl to access
POST
base44.integrations.Core.CreateFileSignedUrl(params)

Create temporary signed URL for private file

const { signed_url } = await base44.integrations.Core.CreateFileSignedUrl({
  file_uri: "private://app_files/secure-doc.pdf",
  expires_in: 300 // seconds (default: 300)
});
// Use signed_url to download/view file (expires after 5 minutes)
POST
base44.integrations.Core.SendEmail(params)

Send email from app

await base44.integrations.Core.SendEmail({
  from_name: "WorkGeniusPro", // optional
  to: "client@example.com",
  subject: "Invoice INV-001 Due",
  body: "Your invoice is due on Jan 15, 2026..."
});
POST
base44.integrations.Core.ExtractDataFromUploadedFile(params)

Extract structured data from files (CSV, PDF, images)

// First upload the file
const { file_url } = await base44.integrations.Core.UploadFile({ file });

// Then extract data
const result = await base44.integrations.Core.ExtractDataFromUploadedFile({
  file_url: file_url,
  json_schema: {
    type: "object",
    properties: {
      name: { type: "string" },
      amount: { type: "number" },
      date: { type: "string" }
    }
  }
});

if (result.status === "success") {
  console.log(result.output); // Extracted data
}
Backend Functions
POST
base44.functions.invoke(functionName, payload)

Call custom backend function

// Basic call
const response = await base44.functions.invoke('generateAccountNumber', {
  client_id: "123"
});
console.log(response.data); // Your function's return value

// Error handling
try {
  const result = await base44.functions.invoke('processPayment', {
    invoice_id: "inv_123",
    amount: 1000
  });
  if (result.data.success) {
    console.log('Payment processed');
  }
} catch (error) {
  console.error('Function error:', error.response?.data || error.message);
}
BACKEND
Backend Function Structure

How to write backend functions (Deno)

// functions/myFunction.js
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.6';

Deno.serve(async (req) => {
  try {
    // Initialize SDK from request
    const base44 = createClientFromRequest(req);
    
    // Authenticate user
    const user = await base44.auth.me();
    if (!user) {
      return Response.json({ error: 'Unauthorized' }, { status: 401 });
    }

    // Parse payload
    const payload = await req.json();
    
    // Access entities (user-scoped)
    const invoices = await base44.entities.Invoice.list();
    
    // Access entities as admin (service role)
    const allData = await base44.asServiceRole.entities.Invoice.list();
    
    // Call integrations
    const result = await base44.integrations.Core.InvokeLLM({
      prompt: "Analyze..."
    });
    
    return Response.json({ 
      success: true, 
      data: result 
    });
  } catch (error) {
    return Response.json({ 
      error: error.message 
    }, { status: 500 });
  }
});
Security & Permissions
UTIL
checkPermission(role, permission)

Check if user has permission

import { checkPermission, PERMISSIONS } from '@/components/security/PermissionGate';

const canView = checkPermission(user.role, PERMISSIONS.VIEW_FINANCE);
UTIL
logAuditEvent(action, details)

Log security event

import { logAuditEvent, AUDIT_ACTIONS } from '@/components/security/AuditLogger';

await logAuditEvent(AUDIT_ACTIONS.INVOICE_CREATED, {
  invoice_id: invoice.id,
  amount: invoice.total_amount
});
Common Patterns

Error Handling

try {
  const data = await base44.entities.Invoice.create(invoiceData);
} catch (error) {
  console.error('Failed:', error.message);
  // Handle error
}

React Query Integration

const { data: invoices = [] } = useQuery({
  queryKey: ['invoices'],
  queryFn: () => base44.entities.Invoice.list(),
  enabled: !!user
});

Permission-Protected Page

import PermissionGate, { PERMISSIONS } from '@/components/security/PermissionGate';

export default function MyPage() {
  return (
    <PermissionGate permission={PERMISSIONS.VIEW_FINANCE}>
      {/* Your page content */}
    </PermissionGate>
  );
}

Mutations with React Query

const createInvoice = useMutation({
  mutationFn: (data) => base44.entities.Invoice.create(data),
  onSuccess: () => {
    queryClient.invalidateQueries(['invoices']);
    toast.success('Invoice created');
  }
});

// Usage
createInvoice.mutate({ client_id: '123', total_amount: 5000 });

Optimistic Updates

const updateStatus = useMutation({
  mutationFn: ({ id, status }) => 
    base44.entities.Invoice.update(id, { status }),
  onMutate: async ({ id, status }) => {
    await queryClient.cancelQueries(['invoices']);
    const previous = queryClient.getQueryData(['invoices']);
    
    queryClient.setQueryData(['invoices'], old =>
      old.map(inv => inv.id === id ? {...inv, status} : inv)
    );
    
    return { previous };
  },
  onError: (err, vars, context) => {
    queryClient.setQueryData(['invoices'], context.previous);
  }
});

Client Portal Authentication

// Login
const { data } = await base44.functions.invoke('clientPortalLogin', {
  email: 'client@example.com',
  password: 'password123'
});
sessionStorage.setItem('client_portal_user', JSON.stringify(data.client));

// Protected Route
import ClientAuthGuard from '@/components/client/ClientAuthGuard';

export default function ClientPortal() {
  return (
    <ClientAuthGuard>
      {/* Portal content */}
    </ClientAuthGuard>
  );
}
Advanced Topics

Entity Relationships

// One-to-Many: Get all invoices for a client
const clientInvoices = await base44.entities.Invoice.filter({
  client_id: clientId
});

// Many-to-Many: Filter by array contains
const projects = await base44.entities.ClientProject.filter({
  client_portal_users: { $in: [userId] }
});

Complex Queries

// Multiple conditions
const overdueHighValue = await base44.entities.Invoice.filter({
  status: { $in: ['sent', 'overdue'] },
  total_amount: { $gte: 5000 },
  due_date: { $lt: new Date().toISOString() }
}, '-total_amount', 20);

// Exclude values
const activeNonPaid = await base44.entities.Invoice.filter({
  status: { $ne: 'paid' },
  client_id: { $ne: null }
});

Rate Limiting & Caching

// React Query with caching
const { data } = useQuery({
  queryKey: ['invoices', filters],
  queryFn: () => base44.entities.Invoice.filter(filters),
  staleTime: 60000, // 1 minute
  cacheTime: 300000, // 5 minutes
  refetchOnWindowFocus: false
});

// Debounced searches
import { useDebounce } from '@/components/hooks/useDebounce';

const debouncedSearch = useDebounce(searchTerm, 500);
const { data } = useQuery({
  queryKey: ['search', debouncedSearch],
  queryFn: () => base44.entities.Contact.filter({
    full_name: { $regex: debouncedSearch }
  }),
  enabled: debouncedSearch.length > 2
});

File Upload Patterns

// Upload with progress
const handleUpload = async (file) => {
  try {
    const { file_url } = await base44.integrations.Core.UploadFile({ file });
    
    // Save reference to entity
    await base44.entities.ProjectDocument.create({
      document_name: file.name,
      file_url: file_url,
      project_id: projectId
    });
  } catch (error) {
    console.error('Upload failed:', error);
  }
};

// Image generation + upload workflow
const generateAndSave = async () => {
  const { url } = await base44.integrations.Core.GenerateImage({
    prompt: "Professional headshot"
  });
  
  // Save to user profile
  await base44.auth.updateMe({ profile_image: url });
};

AI Streaming Responses

// For long-form AI content, use backend functions
// Backend: functions/streamAI.js
const stream = await openai.chat.completions.create({
  model: "gpt-4",
  messages: [{ role: "user", content: prompt }],
  stream: true
});

for await (const chunk of stream) {
  // Send chunks via SSE or WebSocket
}

// Frontend: Handle streaming
const response = await fetch('/api/streamAI', {
  method: 'POST',
  body: JSON.stringify({ prompt })
});

const reader = response.body.getReader();
// Process stream...
Best Practices & Tips
Always authenticate in backend functions: Use base44.auth.me() to validate users
Use service role sparingly: Only use base44.asServiceRole for admin operations
Implement proper error handling: Wrap API calls in try/catch blocks
Cache with React Query: Set appropriate staleTime and cacheTime
Validate inputs: Check required fields before API calls
Don't expose sensitive data: Never return password hashes or API keys
Don't skip authentication: Always verify user permissions in backend functions

Need help? Check the User Manual or Setup Guide

WorkGeniusPro v2.0 • Base44 SDK v0.8.6