# API Reference Source: https://backdrift.mintlify.app/api-reference/introduction Control Plane API documentation. This section documents the **Control Plane API**—the API that powers the Backdrift dashboard. This is separate from the APIs generated for your projects. ## Base URL ``` https://api.backdrift.ai ``` ## Authentication All endpoints (except `/auth/*`) require a Bearer token: ```bash theme={null} Authorization: Bearer ``` Get a token by logging in: ```bash theme={null} curl -X POST https://api.backdrift.ai/auth/login \ -H "Content-Type: application/json" \ -d '{"email": "you@example.com", "password": "your-password"}' ``` ## Common Responses ### Success ```json theme={null} { "data": { ... } } ``` ### Error ```json theme={null} { "error": "Error message", "code": "ERROR_CODE" } ``` ## Rate Limiting | Endpoint Category | Limit | | -------------------- | ------- | | Authentication | 10/min | | Project Operations | 100/min | | Blueprint Generation | 10/min | | Deployments | 5/min | ## API Categories Signup, login, token refresh Create, list, update, delete projects Chat, apply, generate blueprints from specs Generate, validate, get blueprints Version history, compare, classify changes Well-Architected validation, auto-fixes Deploy, preview, destroy, rollback Pre-built starter templates ## Authentication Endpoints ### POST /auth/signup Create a new account. ```bash theme={null} curl -X POST https://api.backdrift.ai/auth/signup \ -H "Content-Type: application/json" \ -d '{ "email": "you@example.com", "password": "SecurePass123!" }' ``` ### POST /auth/login Authenticate and get tokens. ```bash theme={null} curl -X POST https://api.backdrift.ai/auth/login \ -H "Content-Type: application/json" \ -d '{ "email": "you@example.com", "password": "SecurePass123!" }' ``` Response: ```json theme={null} { "accessToken": "eyJ...", "refreshToken": "eyJ...", "expiresIn": 3600 } ``` ### POST /auth/refresh Refresh an expired access token. ```bash theme={null} curl -X POST https://api.backdrift.ai/auth/refresh \ -H "Content-Type: application/json" \ -d '{ "refreshToken": "eyJ..." }' ``` ### GET /auth/me Get current user info. ```bash theme={null} curl https://api.backdrift.ai/auth/me \ -H "Authorization: Bearer $TOKEN" ``` ## Project Endpoints ### GET /projects List your projects. ```bash theme={null} curl https://api.backdrift.ai/projects \ -H "Authorization: Bearer $TOKEN" ``` ### POST /projects Create a new project. ```bash theme={null} curl -X POST https://api.backdrift.ai/projects \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{ "name": "My App", "description": "A task management application" }' ``` ### GET /projects/:id Get project details. ### PATCH /projects/:id Update a project. ### DELETE /projects/:id Archive a project. ## Spec Endpoints The Spec API enables conversational backend editing. Users chat with AI to refine their backend specification, then apply changes and generate blueprints. ### GET /projects/:projectId/spec Get the current project specification. ```bash theme={null} curl https://api.backdrift.ai/projects/$PROJECT_ID/spec \ -H "Authorization: Bearer $TOKEN" ``` Response: ```json theme={null} { "spec": { "id": "spec-uuid", "projectId": "project-uuid", "content": "# My App\n\n## Entities\n...", "version": 3, "lastUserMessage": "Add comments to tasks", "createdAt": "2024-01-15T10:00:00Z" }, "project": { "id": "project-uuid", "name": "My App" } } ``` ### POST /projects/:projectId/spec/chat Send a chat message to refine the spec. Returns updated spec content (draft, not saved). ```bash theme={null} curl -X POST https://api.backdrift.ai/projects/$PROJECT_ID/spec/chat \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{ "message": "Add a comments feature to tasks" }' ``` Response: ```json theme={null} { "spec": "# My App\n\n## Entities\n\n### Task\n...\n\n### Comment\n...", "previousSpec": "# My App\n\n## Entities\n\n### Task\n...", "assistantMessage": "I've added a Comment entity with task_id, author_id, content, and created_at fields.", "currentVersion": 3, "conversationId": "conv-uuid" } ``` ### POST /projects/:projectId/spec/apply Save the current spec (creates a new version). ```bash theme={null} curl -X POST https://api.backdrift.ai/projects/$PROJECT_ID/spec/apply \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{ "content": "# My App\n\n## Entities\n...", "lastUserMessage": "Add comments to tasks" }' ``` Response: ```json theme={null} { "spec": { "id": "spec-uuid", "version": 4, "content": "...", "createdAt": "2024-01-15T10:30:00Z" }, "message": "Spec saved as version 4" } ``` ### POST /projects/:projectId/spec/generate-blueprint Generate a BlueprintIR from the saved spec. Returns immediately with a status URL. ```bash theme={null} curl -X POST https://api.backdrift.ai/projects/$PROJECT_ID/spec/generate-blueprint \ -H "Authorization: Bearer $TOKEN" ``` Response (202 Accepted): ```json theme={null} { "blueprint": { "id": "blueprint-uuid", "projectId": "project-uuid", "status": "processing", "createdAt": "2024-01-15T10:35:00Z" }, "specVersion": 4, "message": "Blueprint generation started", "statusUrl": "/blueprints/blueprint-uuid/status" } ``` ### GET /projects/:projectId/spec/generation-status/:blueprintId Poll for blueprint generation progress. ```bash theme={null} curl https://api.backdrift.ai/projects/$PROJECT_ID/spec/generation-status/$BLUEPRINT_ID \ -H "Authorization: Bearer $TOKEN" ``` Response: ```json theme={null} { "status": "processing", "currentStep": "Generating data model...", "progress": 45, "startedAt": "2024-01-15T10:35:00Z" } ``` ### GET /projects/:projectId/spec/chat/history Get chat message history for a project. ```bash theme={null} curl "https://api.backdrift.ai/projects/$PROJECT_ID/spec/chat/history?limit=50" \ -H "Authorization: Bearer $TOKEN" ``` Response: ```json theme={null} { "conversationId": "conv-uuid", "messages": [ { "id": "msg-1", "role": "user", "content": "Add a comments feature to tasks", "createdAt": "2024-01-15T10:00:00Z" }, { "id": "msg-2", "role": "assistant", "content": "I've added a Comment entity...", "createdAt": "2024-01-15T10:00:05Z" } ] } ``` ### POST /projects/:projectId/spec/chat/message Add an assistant message to the chat history (used for system notifications like generation status). ```bash theme={null} curl -X POST https://api.backdrift.ai/projects/$PROJECT_ID/spec/chat/message \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{ "role": "assistant", "content": "Blueprint generated successfully!" }' ``` Response: ```json theme={null} { "message": { "id": "msg-uuid", "role": "assistant", "content": "Blueprint generated successfully!", "createdAt": "2024-01-15T10:36:00Z" }, "conversationId": "conv-uuid" } ``` ## Blueprint Endpoints ### POST /projects/:id/blueprints Generate a blueprint from a prompt. ```bash theme={null} curl -X POST https://api.backdrift.ai/projects/$PROJECT_ID/blueprints \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{ "prompt": "A task management app with projects, tasks, and team members" }' ``` ### POST /blueprints/:id/validate Run validation checks on a blueprint. ### GET /blueprints/:id/validation-report Get detailed validation results. ## Deployment Endpoints ### POST /projects/:id/validate Preview deployment (dry run). ### POST /projects/:id/deploy Deploy the project. ### GET /deployments/:id Get deployment status and logs. ### DELETE /projects/:id/stack Destroy all stacks. ### POST /projects/:id/rollback Rollback to a previous deployment. ## Artifact Endpoints ### GET /projects/:id/artifacts/openapi Get OpenAPI specification (JSON). ### GET /projects/:id/artifacts/design-doc Get design documentation. ### GET /projects/:id/artifacts/sdk/python Download Python SDK. ### GET /projects/:id/artifacts/cdk Download CDK project. ## Usage Endpoints ### GET /usage/me Get your LLM usage summary. ```bash theme={null} curl https://api.backdrift.ai/usage/me \ -H "Authorization: Bearer $TOKEN" ``` Response: ```json theme={null} { "user": { "id": "user-123", "email": "you@example.com" }, "usage": { "totalCalls": 42, "inputTokens": 150000, "outputTokens": 50000, "totalCostCents": 325, "totalCostFormatted": "$3.25" } } ``` ### GET /usage/recent Get recent LLM calls for debugging. ```bash theme={null} curl "https://api.backdrift.ai/usage/recent?limit=10" \ -H "Authorization: Bearer $TOKEN" ``` # Design Docs Source: https://backdrift.mintlify.app/artifacts/design-docs The bridge between your Backend and AI Coding Assistants. If you use tools like **Lovable**, **Bolt**, **Cursor**, or **v0**, the **Design Doc** artifact is your most powerful tool. ## What Is It? The Design Doc is a Markdown file generated specifically to be read by LLMs. It removes the fluff and provides exactly what an AI needs to write code against your API: * **Context** - High-level architecture summary * **Authentication** - Exact headers and token flows required * **Type Definitions** - Full TypeScript interfaces for your entities * **Endpoints** - Compact list of routes, methods, and parameters * **Examples** - Usage patterns ## Why It Matters When you paste the Design Doc into an AI assistant's context, it understands: ✅ Exactly which endpoints exist ✅ What parameters each endpoint accepts ✅ How to authenticate requests ✅ The shape of response data **No hallucination.** The AI won't make up endpoints that don't exist. ## Sample Design Doc ```markdown theme={null} # Task Manager API ## Base URL https://abc123.execute-api.us-east-2.amazonaws.com ## Authentication All endpoints require a Bearer token: Authorization: Bearer ## TypeScript Interfaces interface Task { id: string; title: string; description?: string; priority: 'low' | 'medium' | 'high'; status: 'pending' | 'active' | 'done'; project_id: string; assignee_id?: string; due_date?: string; created_at: string; updated_at: string; } interface Project { id: string; name: string; org_id: string; created_at: string; } ## Endpoints ### Tasks GET /v1/tasks List tasks (paginated) POST /v1/tasks Create task GET /v1/tasks/:id Get task PUT /v1/tasks/:id Update task DELETE /v1/tasks/:id Delete task ### Projects GET /v1/projects List projects POST /v1/projects Create project ... ``` ## How to Use It Go to **Artifacts** tab → Click **Design Doc** → Download Or click **Copy** to copy the full document Paste into Lovable, Bolt, Cursor, or v0's context window "Build a dashboard using this backend" ## Integration Examples ### With Lovable ``` [Paste Design Doc] Build a task management dashboard with: - A sidebar showing projects - A main area listing tasks for the selected project - Ability to create, edit, and delete tasks - Filter by priority and status ``` ### With Cursor ``` [Paste Design Doc] Create a React component that: - Fetches tasks from the API - Displays them in a table - Allows inline editing of the status field ``` ### With v0 ``` [Paste Design Doc] Design a modern, minimal task board with: - Kanban columns for each status - Drag and drop between columns - Task cards showing title, priority, and assignee ``` ## Dynamic URLs The Design Doc automatically includes your **deployed API URL**, not a placeholder. After deployment, it shows: ``` Base URL: https://your-actual-api.execute-api.us-east-2.amazonaws.com ``` This means AI-generated code will work immediately without URL updates. ## Updating the Design Doc The Design Doc regenerates whenever you: * Apply a new spec * Generate a new blueprint * Deploy changes Always use the latest version after making changes. Get pre-built Python and TypeScript clients. # React Frontend Source: https://backdrift.mintlify.app/artifacts/frontend-ui A ready-to-use React application hosted for you. Most backend tools leave you with just a JSON API. Backdrift provisions a complete **React Frontend** so you can interact with your data immediately. ## What's Included The generated frontend is a **Vite + React** application, written in TypeScript, using **shadcn/ui**. It includes: Login, signup, and password reset screens pre-wired to your auth provider. A type-safe client pre-configured with your API URL and auth headers. Auto-generated CRUD tables for every entity in your blueprint. Built with shadcn/ui components and Tailwind CSS. ## How It's Hosted We deploy your frontend to a global Content Delivery Network (CDN) using **AWS Amplify**: 1. We generate React code based on your schema 2. A serverless build pipeline compiles the assets 3. Static files are pushed to edge locations worldwide Your frontend URL looks like: `https://main.abc123xyz.amplifyapp.com` ## Rebuilding the Frontend When your schema changes, click **Rebuild Frontend** to: 1. Regenerate React components for new/modified entities 2. Update the API client with new endpoints 3. Rebuild and redeploy to Amplify This takes about 2-3 minutes. ## What the UI Looks Like ### Login Screen ``` ┌────────────────────────────────────┐ │ Task Manager │ │ │ │ Email: [________________] │ │ Password: [______________] │ │ │ │ [Sign In] │ │ │ │ Don't have an account? Sign up │ └────────────────────────────────────┘ ``` ### Data Browser ``` ┌────────────────────────────────────────────────────┐ │ Tasks [+ New] │ ├────────────────────────────────────────────────────┤ │ Title │ Priority │ Status │ Actions │ ├────────────────┼──────────┼──────────┼────────────┤ │ Fix login bug │ High │ Active │ [Edit] [🗑] │ │ Add dark mode │ Medium │ Pending │ [Edit] [🗑] │ │ Update docs │ Low │ Done │ [Edit] [🗑] │ └────────────────────────────────────────────────────┘ ``` ## Customization This isn't a proprietary "no-code" interface—it's standard React code. ### Download Source From the **Artifacts** tab, download `frontend.zip` containing: ``` frontend/ ├── package.json ├── vite.config.ts ├── tailwind.config.js ├── src/ │ ├── App.tsx │ ├── api/ │ │ └── client.ts # Pre-configured API client │ ├── components/ │ │ ├── auth/ # Login, signup, reset │ │ └── entities/ # CRUD components per entity │ └── pages/ │ └── ... └── public/ ``` ### Extend It Common customizations: * Add custom pages or dashboards * Modify the styling (Tailwind classes) * Add charts and visualizations * Integrate third-party components ### Self-Host You can deploy the frontend yourself: ```bash theme={null} unzip frontend.zip cd frontend npm install npm run build # Deploy dist/ to any static hosting ``` ## Environment Variables The frontend is configured with these environment variables at build time: | Variable | Description | | --------------------------- | --------------------- | | `VITE_API_URL` | Your backend API URL | | `VITE_COGNITO_USER_POOL_ID` | Cognito User Pool ID | | `VITE_COGNITO_CLIENT_ID` | Cognito App Client ID | | `VITE_REGION` | AWS region | Get LLM-optimized documentation for building custom frontends. # Infrastructure Export Source: https://backdrift.mintlify.app/artifacts/infrastructure Take full control with Infrastructure-as-Code. Backdrift generates standard **AWS CDK** (Cloud Development Kit) code. You can export this code and deploy it yourself, modify it, or use it as a learning resource. ## What is CDK? AWS CDK is an open-source framework that lets you define cloud infrastructure using programming languages. Backdrift generates **Python CDK** code. ## Export the CDK Project From the **Artifacts** tab, click **Export CDK** to download a ZIP file containing: ``` cdk-project/ ├── app.py # CDK app entry point ├── requirements.txt # Python dependencies ├── cdk.json # CDK configuration ├── stacks/ │ ├── cognito_stack.py # Authentication │ ├── dynamodb_stack.py # Database tables │ ├── lambda_stack.py # API handlers │ ├── api_gateway_stack.py # REST API │ ├── eventbridge_stack.py # Scheduled jobs │ ├── sqs_stack.py # Async queues │ ├── ses_stack.py # Email │ ├── s3_stack.py # File storage │ └── cloudwatch_stack.py # Monitoring ├── handlers/ │ ├── crud.py # CRUD operations │ ├── health.py # Health check │ ├── authorizer.py # JWT validation │ └── jobs/ # Job handlers └── README.md # Deployment instructions ``` ## Deploy Yourself ### Prerequisites * Python 3.9+ * AWS CLI configured with credentials * AWS CDK CLI installed ### Steps ```bash theme={null} # Unzip the export unzip cdk-export.zip cd cdk-project # Create virtual environment python -m venv .venv source .venv/bin/activate # Linux/Mac # or: .venv\Scripts\activate # Windows # Install dependencies pip install -r requirements.txt # Bootstrap CDK (first time only) cdk bootstrap # Preview changes cdk diff # Deploy cdk deploy --all ``` ## Why Export? Your infrastructure is standard AWS resources. Take it with you anytime. Modify the generated code to add features Backdrift doesn't support yet. Study how production infrastructure is built with CDK. Integrate with your existing deployment pipelines. ## What's Generated ### Cognito Stack ```python theme={null} # User Pool with password policies user_pool = cognito.UserPool( self, "UserPool", user_pool_name=f"{project_name}-users", self_sign_up_enabled=True, password_policy=cognito.PasswordPolicy( min_length=8, require_lowercase=True, require_uppercase=True, require_digits=True, ), ) ``` ### DynamoDB Stack ```python theme={null} # Table for each entity with GSIs tasks_table = dynamodb.Table( self, "TasksTable", table_name=f"{project_name}-tasks", partition_key=dynamodb.Attribute( name="id", type=dynamodb.AttributeType.STRING ), billing_mode=dynamodb.BillingMode.PAY_PER_REQUEST, point_in_time_recovery=True, ) # Global Secondary Index for tenant queries tasks_table.add_global_secondary_index( index_name="by-org", partition_key=dynamodb.Attribute( name="org_id", type=dynamodb.AttributeType.STRING ), ) ``` ### Lambda Stack ```python theme={null} # CRUD handlers with proper IAM permissions create_task = lambda_.Function( self, "CreateTask", runtime=lambda_.Runtime.PYTHON_3_11, handler="crud.create_handler", code=lambda_.Code.from_asset("handlers"), environment={ "TABLE_NAME": tasks_table.table_name, }, ) tasks_table.grant_write_data(create_task) ``` ## Modifying the Export Common modifications: ### Add a VPC ```python theme={null} from aws_cdk import aws_ec2 as ec2 vpc = ec2.Vpc(self, "ApiVpc", max_azs=2) # Update Lambda to run in VPC create_task = lambda_.Function( self, "CreateTask", vpc=vpc, vpc_subnets=ec2.SubnetSelection( subnet_type=ec2.SubnetType.PRIVATE_WITH_EGRESS ), # ... rest of config ) ``` ### Add Custom Domain ```python theme={null} from aws_cdk import aws_route53 as route53 from aws_cdk import aws_certificatemanager as acm certificate = acm.Certificate( self, "ApiCert", domain_name="api.example.com", validation=acm.CertificateValidation.from_dns(hosted_zone) ) api.add_domain_name( "CustomDomain", domain_name="api.example.com", certificate=certificate ) ``` ### Add WAF ```python theme={null} from aws_cdk import aws_wafv2 as waf web_acl = waf.CfnWebACL( self, "ApiWaf", scope="REGIONAL", # ... WAF rules ) ``` ## Stack Dependencies The CDK project respects dependencies between stacks: ``` cognito_stack ↓ dynamodb_stack ↓ lambda_stack ← depends on tables and auth ↓ api_gateway_stack ← depends on Lambda functions ↓ amplify_stack ← depends on API URL ``` Learn about managing your deployed infrastructure. # OpenAPI Specification Source: https://backdrift.mintlify.app/artifacts/openapi The standard API definition format. Backdrift generates a complete [OpenAPI 3.0](https://swagger.io/specification/) specification for your API. This is the industry-standard format for describing REST APIs. ## What's Included The OpenAPI spec describes: * **Endpoints** - All routes with methods (GET, POST, PUT, DELETE) * **Parameters** - Path, query, and body parameters * **Request Bodies** - JSON schemas for POST/PUT requests * **Responses** - Success and error response schemas * **Authentication** - Security schemes (Bearer token) * **Servers** - Your deployed API URL ## Download Formats | Format | Description | | ------ | ---------------------------------- | | JSON | Machine-readable, best for tooling | | YAML | Human-readable, easier to edit | ## Using the OpenAPI Spec ### Generate SDKs ```bash theme={null} # Install OpenAPI Generator npm install -g @openapitools/openapi-generator-cli # Generate TypeScript client openapi-generator-cli generate \ -i openapi.json \ -g typescript-fetch \ -o ./sdk-ts # Generate Python client openapi-generator-cli generate \ -i openapi.json \ -g python \ -o ./sdk-python ``` ### Import into Postman 1. Open Postman 2. Click **Import** 3. Drag your `openapi.json` file 4. Postman creates a collection with all endpoints ### Generate Documentation ```bash theme={null} # Using Redoc npx @redocly/cli build-docs openapi.json # Using Swagger UI docker run -p 8080:8080 \ -e SWAGGER_JSON=/api/openapi.json \ -v $(pwd):/api \ swaggerapi/swagger-ui ``` ### Validate API Contracts ```bash theme={null} # Using Spectral npm install -g @stoplight/spectral-cli spectral lint openapi.json ``` ## Sample OpenAPI Spec ```yaml theme={null} openapi: 3.0.0 info: title: Task Manager API version: 1.0.0 description: Auto-generated by Backdrift servers: - url: https://abc123.execute-api.us-east-2.amazonaws.com description: Production security: - bearerAuth: [] paths: /v1/tasks: get: summary: List tasks parameters: - name: limit in: query schema: type: integer default: 20 - name: cursor in: query schema: type: string responses: '200': description: Success content: application/json: schema: type: object properties: items: type: array items: $ref: '#/components/schemas/Task' next_cursor: type: string post: summary: Create task requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/CreateTaskRequest' responses: '201': description: Created content: application/json: schema: $ref: '#/components/schemas/Task' components: schemas: Task: type: object properties: id: type: string title: type: string priority: type: string enum: [low, medium, high] status: type: string enum: [pending, active, done] created_at: type: string format: date-time securitySchemes: bearerAuth: type: http scheme: bearer bearerFormat: JWT ``` ## Interactive API Docs Backdrift includes an interactive API documentation viewer (powered by Redoc): 1. Go to your project 2. Click **View API Docs** 3. Browse endpoints, try requests, and explore schemas Export the raw Infrastructure-as-Code. # SDKs Source: https://backdrift.mintlify.app/artifacts/sdks Pre-built client libraries for your API. Backdrift generates client SDKs so you can integrate with your backend from any language. ## Available SDKs ### Built-in SDKs (11 Languages) All SDKs are generated server-side using OpenAPI Generator. Download from the **Artifacts** tab: | Language | Format | Generator | | ------------ | ------ | ---------------- | | TypeScript | `.zip` | typescript-fetch | | Python | `.zip` | python | | Go | `.zip` | go | | Java | `.zip` | java | | Kotlin | `.zip` | kotlin | | Swift | `.zip` | swift5 | | C# | `.zip` | csharp | | Ruby | `.zip` | ruby | | Rust | `.zip` | rust | | Dart/Flutter | `.zip` | dart | | PHP | `.zip` | php | ### How It Works SDK generation runs on a serverless Lambda function with OpenAPI Generator CLI. Generation typically takes 1-3 seconds. ## Python SDK ### Download From the **Artifacts** tab, click **Python SDK** to download. ### Installation ```bash theme={null} unzip python-sdk.zip cd task-manager-sdk pip install -e . ``` ### Usage ```python theme={null} from task_manager import Client, Task # Initialize with your API URL client = Client( base_url="https://abc123.execute-api.us-east-2.amazonaws.com", access_token="your-jwt-token" ) # List tasks tasks = client.tasks.list() for task in tasks: print(f"{task.title} - {task.priority}") # Create a task new_task = client.tasks.create(Task( title="Ship the feature", priority="high", project_id="proj-123" )) # Update a task client.tasks.update(new_task.id, status="done") # Delete a task client.tasks.delete(new_task.id) ``` ### Type Hints The Python SDK includes full type hints for IDE autocomplete: ```python theme={null} from task_manager import Task task: Task = client.tasks.get("task-123") task.title # IDE shows: str task.priority # IDE shows: Literal['low', 'medium', 'high'] ``` ## TypeScript SDK ### Download From the **Artifacts** tab, click **TypeScript SDK** to download. ### Installation ```bash theme={null} unzip typescript-sdk.zip cd task-manager-sdk npm install npm run build ``` ### Usage ```typescript theme={null} import { Client, Task } from 'task-manager-sdk'; const client = new Client({ baseUrl: 'https://abc123.execute-api.us-east-2.amazonaws.com', accessToken: 'your-jwt-token' }); // List tasks const tasks = await client.tasks.list(); tasks.forEach(task => console.log(task.title)); // Create a task const newTask = await client.tasks.create({ title: 'Ship the feature', priority: 'high', projectId: 'proj-123' }); // Update a task await client.tasks.update(newTask.id, { status: 'done' }); // Delete a task await client.tasks.delete(newTask.id); ``` ## Generating Custom SDKs Need a language not listed above? Use [OpenAPI Generator](https://openapi-generator.tech) locally with your OpenAPI spec: ```bash theme={null} # Install OpenAPI Generator npm install -g @openapitools/openapi-generator-cli # Download your OpenAPI spec curl -o openapi.json https://backdrift.ai/api/projects/YOUR_PROJECT_ID/artifacts/openapi # Generate SDK for any supported language openapi-generator-cli generate -i openapi.json -g -o ./sdk-output ``` ### All Supported Languages Run `openapi-generator-cli list` to see all 50+ supported generators. ## Dynamic URLs SDKs are generated with your **deployed API URL** pre-configured: ```python theme={null} # The base URL is already set to your deployment client = Client(access_token="your-token") # No need to specify base_url! ``` ## Keeping SDKs Updated Regenerate SDKs whenever you: * Add new entities * Add new endpoints * Change field types * Deploy changes The **Artifacts** tab always shows SDKs for your latest deployment. Get the raw OpenAPI specification. # Authentication Source: https://backdrift.mintlify.app/capabilities/authentication Secure user management and access control. Backdrift provides a fully managed authentication system out of the box. No OAuth configuration, no JWT libraries, no security vulnerabilities. ## What You Get Self-service registration with email verification Password authentication with brute-force protection Secure password recovery via email Access and refresh tokens with configurable expiry ## Roles & Permissions Define roles in your prompt, and Backdrift enforces them at the API level: ``` "Organization admins can invite members and delete projects. Members can create tasks but not delete projects. Viewers can only read data." ``` This generates: | Role | Permissions | | ------ | --------------------------------------- | | admin | Full CRUD on all entities | | member | Create/Read/Update tasks, Read projects | | viewer | Read-only access | ## Authorization Levels Every endpoint has an authorization level: | Level | Description | | --------------- | -------------------------- | | `public` | No authentication required | | `authenticated` | Any logged-in user | | `admin` | Users with admin role | | `owner` | Only the resource owner | ### Example ``` GET /v1/tasks → authenticated (any user) POST /v1/tasks → authenticated (any user) DELETE /v1/tasks/:id → owner (only creator can delete) DELETE /v1/projects → admin (only admins) ``` ## Multi-Tenancy For SaaS applications, Backdrift automatically isolates data by tenant: ``` "Each organization should have isolated data." ``` This configures: * **Organization Entity** - Tenant boundary * **Auto-Filtering** - All queries filtered by org\_id * **JWT Claims** - Tenant ID embedded in tokens ### How It Works 1. User signs up and creates an organization 2. User's JWT includes `org_id` claim 3. Every API request is filtered by `org_id` 4. User in Org A **cannot** access data from Org B ```python theme={null} # This happens automatically in every Lambda handler: def list_tasks(event): org_id = get_org_id_from_token(event) return db.query( table="tasks", filter={"org_id": org_id} # Auto-injected ) ``` ## Password Policies Backdrift enforces secure password policies: * Minimum 8 characters * Requires uppercase letter * Requires lowercase letter * Requires number * Requires special character (optional) ## Token Configuration | Token Type | Default Expiry | Configurable | | ------------- | -------------- | ------------ | | Access Token | 1 hour | Yes | | Refresh Token | 30 days | Yes | | ID Token | 1 hour | Yes | ## Using Authentication ### Sign Up ```bash theme={null} curl -X POST https://your-api.amazonaws.com/auth/signup \ -H "Content-Type: application/json" \ -d '{ "email": "user@example.com", "password": "SecurePass123!" }' ``` ### Login ```bash theme={null} curl -X POST https://your-api.amazonaws.com/auth/login \ -H "Content-Type: application/json" \ -d '{ "email": "user@example.com", "password": "SecurePass123!" }' ``` Response: ```json theme={null} { "accessToken": "eyJhbGciOiJIUzI1NiIs...", "refreshToken": "eyJhbGciOiJIUzI1NiIs...", "expiresIn": 3600 } ``` ### Make Authenticated Requests ```bash theme={null} curl https://your-api.amazonaws.com/v1/tasks \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..." ``` ## Coming Soon * Social login (Google, GitHub, Apple) * SAML/OIDC federation * Multi-factor authentication (MFA) * API keys for machine-to-machine auth Learn how to define entities and relationships. # Data Modeling Source: https://backdrift.mintlify.app/capabilities/data-modeling Entities, fields, and relationships. Backdrift automatically designs your database schema from natural language. Describe your data, and we handle the rest. ## Database Options Backdrift supports two database backends: | Option | Best For | Features | | ---------------------- | ----------------------- | ---------------------------------------- | | **DynamoDB** (default) | Simple apps, high scale | NoSQL, auto-scaling, pay-per-request | | **RDS PostgreSQL** | Complex queries, joins | Relational, SQL, foreign key constraints | To request PostgreSQL, mention it in your prompt: ``` "A CRM with users, contacts, and deals. Use PostgreSQL for complex reporting queries." ``` ## Entities Entities are your data models. Each entity becomes a database table with automatic CRUD endpoints. ### Defining Entities ``` "Tasks have a title, description, due date, priority, and status." ``` This generates: ```typescript theme={null} interface Task { id: string; // Auto-generated primary key title: string; description?: string; due_date?: string; // ISO datetime priority: 'low' | 'medium' | 'high'; status: 'pending' | 'active' | 'done'; created_at: string; // Auto-managed updated_at: string; // Auto-managed } ``` ## Field Types | Type | Description | Example | | ---------- | -------------- | ------------------------ | | `string` | Text data | names, descriptions | | `number` | Floating point | prices, scores | | `integer` | Whole numbers | counts, ages | | `boolean` | True/false | is\_active, is\_verified | | `datetime` | ISO timestamp | due\_date, created\_at | | `date` | Date only | birth\_date | | `enum` | Fixed options | status, priority | | `json` | Arbitrary JSON | metadata, settings | ## Field Constraints ### Required vs Optional ``` "Tasks have a required title and optional description." ``` ### Unique Fields ``` "Users have a unique email address." ``` ### Default Values ``` "Task status defaults to 'pending'." ``` ### Enums ``` "Priority can be low, medium, or high." ``` ## Relationships ### One-to-Many ``` "Tasks belong to projects. A project has many tasks." ``` This creates: * `project_id` foreign key on Task * Index for efficient queries * Cascade delete options ### Many-to-Many ``` "Tasks can have multiple tags. Tags can be on multiple tasks." ``` This creates a join table automatically. ### Self-Referential ``` "Tasks can have subtasks." ``` Creates a `parent_task_id` field on Task. ## Automatic Fields Backdrift adds useful fields automatically: | Field | Description | | ------------ | ----------------------------- | | `id` | UUID primary key | | `created_at` | When record was created | | `updated_at` | When record was last modified | | `org_id` | Tenant ID (if multi-tenant) | ## Indexes Backdrift creates indexes for: * Primary keys (`id`) * Foreign keys (`project_id`) * Tenant keys (`org_id`) * Frequently queried fields ### Query Optimization ``` "Users often search tasks by status and due date." ``` This hints Backdrift to create a composite index on `(status, due_date)`. ## Multi-Tenant Data In multi-tenant mode, every entity gets: ```typescript theme={null} interface Task { id: string; org_id: string; // Auto-injected tenant ID // ... other fields } ``` All queries are automatically filtered by `org_id`. ## PII Detection Backdrift detects Personally Identifiable Information: | Field Pattern | Detection | | ------------- | ------------------ | | `email` | Email PII | | `phone` | Phone PII | | `ssn` | SSN PII (Critical) | | `address` | Address PII | When PII is detected, we recommend: * Encryption at rest * Access logging * Data retention policies ## Example: E-commerce ``` "An e-commerce platform with: - Products with name, description, price, and category - Categories with name and description - Orders with status, total, and customer - Order items linking orders to products with quantity" ``` Generates: ``` ┌─────────────┐ ┌─────────────┐ │ Category │ │ Product │ ├─────────────┤ ├─────────────┤ │ id │←────│ category_id │ │ name │ │ name │ │ description │ │ description │ └─────────────┘ │ price │ └─────────────┘ ↑ ┌─────────────┐ ┌─────────────┐ │ Order │ │ Order Item │ ├─────────────┤ ├─────────────┤ │ id │←────│ order_id │ │ customer_id │ │ product_id │─→ │ status │ │ quantity │ │ total │ │ unit_price │ └─────────────┘ └─────────────┘ ``` Learn how to run background tasks on a schedule. # Durable Workflows Source: https://backdrift.mintlify.app/capabilities/durable-workflows Long-running processes that can pause for up to a year. Some processes take days, weeks, or even months. Durable Workflows let you write these as simple code that can pause, wait, and resume—even if servers restart. ## What Are Durable Workflows? Normal serverless functions timeout after 15 minutes. Durable Workflows can: * **Pause** for minutes, days, or up to 1 year * **Wait** for external events (webhook, user action) * **Resume** exactly where they left off * **Retry** failed steps automatically ## When to Use Durable Workflows Most applications **don't need** Durable Workflows. Simple event handlers and scheduled jobs cover 90% of use cases. Use Durable Workflows **only** when you explicitly need: * **Human approval waits** - Processes that pause for days or weeks waiting for someone to approve * **Long-running processes** - Workflows that must survive beyond Lambda's 15-minute timeout * **Saga patterns** - Multi-step transactions with compensation logic if steps fail * **"Human in the loop"** - Processes that require human intervention mid-workflow **Don't use** Durable Workflows for: * Simple event handlers (use Events instead) * Scheduled jobs (use Jobs instead) * Basic CRUD operations * Workflows that complete quickly ## Use Cases Wait for manager approval before processing expense reports. Retry failed payments with exponential backoff over days. Multi-step user onboarding over days or weeks. Handle trials, renewals, and cancellations over months. ## Defining Workflows Describe the workflow in natural language: ``` "When a subscription is created: 1. Send a welcome email immediately 2. Wait 7 days 3. Send a tips & tricks email 4. Wait until 3 days before trial ends 5. Send a trial ending reminder 6. Wait for trial to end 7. If not converted, send a winback email" ``` ## How It Works ```python theme={null} # This is what Backdrift generates (simplified) def subscription_workflow(subscription): # Step 1: Immediate send_welcome_email(subscription.user) # Step 2: Wait 7 days (workflow pauses, no server running) await sleep(days=7) # Step 3: Resume and send send_tips_email(subscription.user) # Step 4: Wait until specific date await sleep_until(subscription.trial_end - days(3)) # Step 5: Check and send send_trial_reminder(subscription.user) # And so on... ``` The magic: This code **pauses** at each `await` and **resumes** later—even if the server restarts, deploys happen, or days pass. ## Waiting for Events Workflows can wait for external signals: ``` "Wait for the manager to approve the expense report. If not approved within 7 days, escalate to the director." ``` ```python theme={null} # Generated code (simplified) result = await wait_for_event( event="expense_approved", timeout=days(7) ) if result.timed_out: escalate_to_director() else: process_approved_expense() ``` ## Sending Signals External systems can signal waiting workflows: ```bash theme={null} # From your application or webhook curl -X POST https://your-api/workflows/{workflow_id}/signal \ -H "Authorization: Bearer $TOKEN" \ -d '{"event": "expense_approved", "data": {"approved_by": "manager@example.com"}}' ``` ## Retry Logic Workflows automatically retry failed steps: ``` "If payment fails, retry 3 times over 7 days with increasing delays." ``` ```python theme={null} # Generated retry policy @retry( max_attempts=3, delays=[hours(1), days(1), days(3)] ) def charge_payment(subscription): return payment_gateway.charge(subscription) ``` ## Monitoring In the **Admin Dashboard** → **Workflows** tab: * View active workflow instances * See current step and status * View history of completed steps * Send signals to waiting workflows * Cancel stuck workflows ## Region Requirements Durable Workflows require deployment to **us-east-2** (Ohio). When creating a project that needs Durable Workflows, select us-east-2 as your region. ## Examples ### Approval Flow ``` "When an expense report is submitted: 1. Notify the manager 2. Wait for approval (timeout: 7 days) 3. If approved, process reimbursement 4. If rejected, notify employee 5. If timed out, escalate to director" ``` ### Payment Retry ``` "When a payment fails: 1. Wait 1 hour and retry 2. If still failing, wait 1 day and retry 3. If still failing, wait 3 days and retry 4. If still failing, suspend subscription and notify user" ``` ### Order Fulfillment ``` "When an order is placed: 1. Reserve inventory 2. Charge payment 3. Wait for warehouse confirmation (up to 24 hours) 4. Send shipping notification 5. Wait for delivery confirmation 6. Send review request 3 days after delivery" ``` ## Limitations | Limit | Value | | ------------------------- | ------ | | Maximum workflow duration | 1 year | | Maximum step timeout | 1 year | | Payload size | 256 KB | | Concurrent workflows | 10,000 | Learn how to handle file uploads. # File Storage Source: https://backdrift.mintlify.app/capabilities/file-storage Upload, store, and serve files securely. Backdrift provides secure file storage for uploads like profile pictures, documents, and attachments. ## Defining Storage Describe what files you need to store: ``` "Users can upload profile pictures." ``` ``` "Tasks can have file attachments (PDFs, images, documents)." ``` ``` "Products have multiple gallery images." ``` ## How It Works ```mermaid theme={null} graph LR A[Client] --> B[Get Upload URL] B --> C[Upload to Storage] C --> D[Save Reference] D --> E[Retrieve File] ``` 1. Client requests a **signed upload URL** 2. Client uploads directly to storage (not through your API) 3. Client saves the file reference to the entity 4. Files are retrieved via signed URLs or CDN ## Upload Flow ### 1. Request Upload URL ```bash theme={null} POST /v1/tasks/{taskId}/attachments/upload-url { "filename": "report.pdf", "contentType": "application/pdf" } ``` Response: ```json theme={null} { "uploadUrl": "https://s3.amazonaws.com/bucket/...", "fileKey": "attachments/task-123/report.pdf", "expiresIn": 3600 } ``` ### 2. Upload File ```bash theme={null} curl -X PUT "${uploadUrl}" \ -H "Content-Type: application/pdf" \ --data-binary @report.pdf ``` ### 3. Save Reference ```bash theme={null} PATCH /v1/tasks/{taskId} { "attachment_key": "attachments/task-123/report.pdf" } ``` ## Download Flow ### Get Signed URL ```bash theme={null} GET /v1/tasks/{taskId}/attachments/{fileKey}/download-url ``` Response: ```json theme={null} { "downloadUrl": "https://s3.amazonaws.com/bucket/...", "expiresIn": 3600 } ``` ## File Restrictions Configure allowed file types and sizes: ``` "Attachments can be PDFs, images, or documents up to 10MB." ``` ``` "Profile pictures must be images under 2MB." ``` This generates: * Content-type validation * File size limits * Optional virus scanning ## Storage Configuration Backdrift configures storage with security best practices: | Setting | Default | | ------------- | -------------------------- | | Encryption | Server-side (AES-256) | | Versioning | Disabled | | Public access | Blocked | | CORS | Configured for your domain | | Lifecycle | No automatic deletion | ## Lifecycle Policies Configure automatic cleanup: ``` "Delete attachments 90 days after the task is completed." ``` ``` "Move old files to cheaper storage after 30 days." ``` ## CDN (Optional) For public files (like product images), enable CDN: ``` "Product images should be served from a CDN for fast loading." ``` This creates a CloudFront distribution with: * Global edge caching * HTTPS * Automatic compression * Custom domain support ## Image Processing For images, you can request transformations: ``` "Generate thumbnails for uploaded images." ``` ``` "Resize profile pictures to 200x200." ``` ## Multi-Tenant Storage In multi-tenant mode, files are isolated by organization: ``` files/ ├── org-123/ │ ├── tasks/ │ └── users/ ├── org-456/ │ ├── tasks/ │ └── users/ ``` A user from Org-123 cannot access files from Org-456. ## Security All uploads and downloads use time-limited signed URLs. Direct bucket access is blocked. Files are encrypted at rest using AES-256 server-side encryption. Optional: Scan uploads for malware before accepting. File access follows the same authorization rules as your entities. ## Example: Document Management ``` "A document management system where: - Documents belong to folders - Users can upload files (PDFs, Word, Excel) up to 50MB - Documents have version history - Deleted documents are retained for 30 days before permanent deletion" ``` This generates: * S3 bucket with versioning enabled * 30-day lifecycle policy for deleted objects * Signed URLs for secure upload/download * Content-type validation Learn how to build frontends with file uploads in Lovable. # Scheduled Jobs Source: https://backdrift.mintlify.app/capabilities/scheduled-jobs Run background tasks on a schedule. Backdrift supports scheduled jobs for recurring tasks like sending reports, cleaning up old data, or syncing with external systems. ## Defining Jobs Describe what should happen and when: ``` "Run a nightly job to archive completed tasks older than 30 days." ``` ``` "Every Monday at 9 AM, send a weekly summary email to all users." ``` ``` "Every hour, check for expiring subscriptions and send reminders." ``` ## Schedule Formats Backdrift understands natural language schedules: | Description | Cron Expression | | ----------------------- | ------------------ | | "Every day at midnight" | `0 0 * * *` | | "Every hour" | `0 * * * *` | | "Every Monday at 9 AM" | `0 9 * * MON` | | "First of every month" | `0 0 1 * *` | | "Every 15 minutes" | `*/15 * * * *` | | "Weekdays at 6 PM" | `0 18 * * MON-FRI` | ## How It Works ```mermaid theme={null} graph LR A[Scheduler] --> B[Job Queue] B --> C[Job Handler] C --> D[Your Logic] D --> E[Done] ``` 1. **Scheduler** triggers on the defined schedule 2. **Job Queue** ensures reliable delivery 3. **Job Handler** executes your logic 4. **Retries** if the job fails ## Job Features Jobs run exactly once, with automatic retries on failure. Failed jobs go to a dead-letter queue for debugging. Full execution logs available in the Admin Dashboard. Run jobs on-demand from the Admin Dashboard. ## Example Jobs ### Data Cleanup ``` "Every night at 2 AM, delete sessions older than 7 days." ``` ### Report Generation ``` "Every Monday at 6 AM, generate a weekly activity report and email it to organization admins." ``` ### External Sync ``` "Every 5 minutes, sync new orders with the inventory system." ``` ### Reminders ``` "Every day at 8 AM, find tasks due today and send reminder emails to assignees." ``` ## Monitoring Jobs In the **Admin Dashboard** → **Jobs** tab: * View all scheduled jobs * See last run status and timing * Expand to see execution history * Click **Run Now** to trigger manually * View logs for each execution ## Dead Letter Queue Failed jobs (after retries) go to a Dead Letter Queue: * Jobs are retained for 14 days * View failure reason and stack trace * Retry or delete from the queue * Alert on DLQ depth ## Best Practices Jobs might run twice (rare, but possible). Design for idempotency: ❌ "Send email to users" ✅ "Send email to users who haven't received it today" Jobs have a 15-minute timeout by default. For longer tasks, use [Durable Workflows](/capabilities/durable-workflows). Jobs retry 3 times with exponential backoff. After that, they go to the DLQ. Jobs run in parallel by default. If you need serial execution, specify it: "Run sequentially to avoid race conditions." ## Event-Driven Jobs Jobs can also trigger on events, not just schedules: ``` "When a task is marked complete, notify the project owner." ``` ``` "When a user signs up, send a welcome email." ``` These create event-driven triggers instead of scheduled ones. For long-running processes that need to pause and resume. # Blueprints Source: https://backdrift.mintlify.app/concepts/blueprints The universal specification that powers everything. A **Blueprint** is the heart of every Backdrift project. It's a structured representation of your backend that describes entities, relationships, authentication, and business logic in a format both humans and AI can understand. ## What is a Blueprint? Think of a Blueprint as the "source of truth" for your backend. It contains: * **Entities** - Your data models (Users, Tasks, Projects) * **Relationships** - How entities connect (Tasks belong to Projects) * **Authentication** - How users sign in and what roles exist * **API Endpoints** - What operations are available * **Workflows** - Scheduled jobs, events, and long-running processes ## The Blueprint Lifecycle ```mermaid theme={null} graph LR A[Natural Language] --> B[Spec] B --> C[Blueprint] C --> D[Infrastructure] D --> E[Cloud Resources] ``` 1. **Natural Language** → You describe what you want 2. **Spec** → AI creates an editable specification 3. **Blueprint** → The spec is compiled into a complete Blueprint IR 4. **Infrastructure** → Blueprint is transformed into cloud resource definitions 5. **Cloud Resources** → Real infrastructure is deployed ## Blueprint Structure ```json theme={null} { "project": { "name": "Task Manager", "description": "A multi-tenant task management application" }, "auth": { "strategy": "cognito", "roles": ["admin", "member", "viewer"] }, "tenancy": { "mode": "multi_tenant", "tenant_entity": "organization" }, "entities": [ { "name": "task", "fields": [ { "name": "id", "type": "string", "primary": true }, { "name": "title", "type": "string" }, { "name": "priority", "type": "enum", "enum": ["low", "medium", "high"] }, { "name": "due_date", "type": "datetime" }, { "name": "org_id", "type": "string" } ], "tenancy": "tenant" } ], "api": { "resources": [ { "entity": "task", "base_path": "/v1/tasks", "operations": ["list", "create", "get", "update", "delete"] } ] } } ``` ## Key Concepts ### Entities Entities are your data models. Each entity becomes a database table and gets automatic API endpoints. ```json theme={null} { "name": "task", "fields": [ { "name": "title", "type": "string" }, { "name": "status", "type": "enum", "enum": ["pending", "done"] }, { "name": "due_date", "type": "datetime", "nullable": true } ] } ``` ### Relationships Connect entities together with foreign keys: ```json theme={null} { "name": "task", "fields": [ { "name": "project_id", "type": "string", "foreign_key": { "entity": "project", "field": "id" } } ] } ``` ### Multi-Tenancy For SaaS applications, Backdrift automatically isolates data by tenant: ```json theme={null} { "tenancy": { "mode": "multi_tenant", "tenant_entity": "organization", "tenant_id_field": "org_id" } } ``` Every query is automatically filtered by the user's organization—a user in Org A cannot access data from Org B. ## Why Blueprints? Blueprints are cloud-agnostic. The same Blueprint could theoretically deploy to different providers. Every change creates a new revision. Roll back to any previous version with one click. The structured format means AI tools can understand, modify, and validate your backend. Download the generated Infrastructure-as-Code (CDK) to take full control. ## Next Steps Learn how to describe your backend effectively. # Bolt Integration Source: https://backdrift.mintlify.app/integrations/bolt Build full-stack apps with Bolt and Backdrift. [Bolt](https://bolt.new) by StackBlitz is an AI-powered development environment that can build and run code directly in the browser. Combined with Backdrift, you can create complete applications. ## The Workflow ```mermaid theme={null} graph LR A[Backdrift] --> B[Design Doc] B --> C[Bolt] C --> D[Full-Stack App] ``` 1. Build your backend with Backdrift 2. Export the Design Doc 3. Paste into Bolt with your requirements 4. Get a running application in the browser ## Step-by-Step ### 1. Build Your Backend Create and deploy your backend in Backdrift. ### 2. Get the Design Doc From your project's **Artifacts** tab: * Click **Design Doc** * Copy to clipboard ### 3. Open Bolt Go to [bolt.new](https://bolt.new) and start a new project. ### 4. Paste and Prompt ``` I have a backend API deployed. Here's the documentation: [DESIGN DOC CONTENT] --- Build a React app that: - Shows a login page - After login, displays a dashboard with a list of tasks - Allows creating, editing, and deleting tasks - Uses Tailwind CSS for styling ``` ### 5. Watch It Build Bolt will: * Create React components * Set up API client with your URL * Configure authentication * Run the app in the browser ### 6. Iterate ``` "Add a sidebar with project navigation" "Add drag-and-drop to reorder tasks" "Add dark mode toggle" ``` ## Bolt Advantages See your app running immediately—no deployment needed. Edit code directly in the browser with full IDE features. Run npm commands, install packages, run tests. Push to GitHub when ready for production. ## Example Prompt ``` [DESIGN DOC] --- Build a project management app with: 1. Landing page with hero section and features list 2. Login/Signup with the auth endpoints documented above 3. Dashboard showing: - Sidebar with project list - Main area with task board (Kanban style) - Header with user menu and notifications 4. Project settings page where admins can: - Rename the project - Invite team members - Delete the project Use React, Tailwind CSS, and shadcn/ui components. Include loading states and error handling. ``` ## Working with the Generated Code Bolt generates standard React code. You can: ### Edit Directly Click any file in the sidebar to edit. Changes are applied instantly. ### Install Packages ```bash theme={null} # In Bolt's terminal npm install @tanstack/react-query npm install date-fns ``` ### Run Commands ```bash theme={null} npm run build npm run test ``` ## Handling Authentication Bolt can implement the full auth flow: ``` "Implement authentication: - Login page with email and password - Signup page with email, password, and name - Store the JWT in localStorage - Add an axios interceptor to attach the token - Redirect to login if token is expired - Show user email in the navbar with logout button" ``` ## Connecting to Your API The Design Doc includes your API URL. Bolt will use it directly: ```typescript theme={null} // Generated by Bolt const API_URL = 'https://abc123.execute-api.us-east-2.amazonaws.com'; export async function fetchTasks() { const response = await fetch(`${API_URL}/v1/tasks`, { headers: { 'Authorization': `Bearer ${getToken()}` } }); return response.json(); } ``` ## Exporting Your App When ready for production: 1. Click **Export** in Bolt 2. Choose GitHub repository 3. Push the code 4. Deploy to Vercel, Netlify, or Cloudflare Pages ## Tips for Bolt Begin with core features. Add complexity later. Ask Bolt to use React Query for data fetching—it handles caching and refetching. "Add proper error handling with toast notifications for API errors." "Add skeleton loaders while data is fetching." Generate UI components with v0. # Lovable Integration Source: https://backdrift.mintlify.app/integrations/lovable Build beautiful frontends that connect to your Backdrift backend. [Lovable](https://lovable.dev) is an AI-powered frontend builder. Combined with Backdrift, you can create complete applications—frontend and backend—entirely with AI. ## The Workflow ```mermaid theme={null} graph LR A[Backdrift] --> B[Design Doc] B --> C[Lovable] C --> D[Complete App] ``` 1. Build your backend with Backdrift 2. Export the Design Doc 3. Paste into Lovable with your UI requirements 4. Get a working, connected application ## Step-by-Step ### 1. Build Your Backend Create a project in Backdrift and deploy it: ``` "A task management app with projects, tasks, and team members. Each organization has isolated data." ``` ### 2. Get the Design Doc From your project's **Artifacts** tab: * Click **Design Doc** * Copy to clipboard or download ### 3. Open Lovable Go to [lovable.dev](https://lovable.dev) and start a new project. ### 4. Paste and Prompt In Lovable's chat, paste: ``` [DESIGN DOC CONTENT] --- Build a task management dashboard with: - A sidebar showing projects - A main area listing tasks for the selected project - Ability to create, edit, and delete tasks - Filter tasks by status and priority - Assign tasks to team members Use a modern, minimal design with a dark mode option. ``` ### 5. Iterate Lovable generates a React app. Continue prompting: ``` "Add a calendar view for tasks with due dates" "Add drag-and-drop to change task status" "Add user avatars next to assigned tasks" ``` ## What Lovable Gets The Design Doc tells Lovable: | Information | How Lovable Uses It | | -------------------- | --------------------------- | | API URL | Configures fetch calls | | Auth headers | Sets up authorization | | TypeScript types | Types all API responses | | Endpoints | Knows what to call and when | | Entity relationships | Understands data structure | ## Example: E-commerce Dashboard ### Backend Prompt (Backdrift) ``` "An e-commerce platform with products, categories, orders, and customers. Admins can manage inventory and view analytics." ``` ### Frontend Prompt (Lovable) ``` [DESIGN DOC] --- Build an admin dashboard for e-commerce: - Sidebar with navigation: Dashboard, Products, Orders, Customers - Dashboard page with revenue chart, order count, low stock alerts - Products page with table, search, filters, and inline editing - Orders page with status filters and order details modal - Customers page with search and order history Use shadcn/ui components. Include dark mode. ``` ## Authentication The Design Doc includes auth flow documentation. Lovable can generate: * Login and signup pages * Protected routes * Token storage and refresh * User profile display ``` "Add login and signup pages. Redirect to login if not authenticated. Show the user's email in the header with a logout button." ``` ## File Uploads If your backend supports file storage: ``` "Add a profile picture upload to the user settings page. Use drag-and-drop with preview before uploading." ``` Lovable will: 1. Request a signed upload URL from your API 2. Upload directly to storage 3. Save the file reference ## Tips for Better Results ❌ "Add a products page" ✅ "Add a products page with a grid of cards showing image, name, price. Include search, category filter, and sort by price." "Using the Task entity from the API, build a Kanban board grouped by status." Build one feature at a time. Test, then add more. "Use a shadcn/ui DataTable for the orders list with sorting and pagination." ## Deployment After building in Lovable: 1. Export the code to GitHub 2. Deploy to Vercel, Netlify, or any static host 3. Set environment variables for your API URL Or use Lovable's built-in hosting. Build with Bolt instead. # v0 Integration Source: https://backdrift.mintlify.app/integrations/v0 Generate beautiful UI components with v0 and connect them to Backdrift. [v0](https://v0.dev) by Vercel generates React components from text descriptions. Combined with Backdrift, you can create stunning interfaces connected to real APIs. ## The Workflow ```mermaid theme={null} graph LR A[Backdrift] --> B[Design Doc] B --> C[v0] C --> D[React Components] D --> E[Your App] ``` 1. Build your backend with Backdrift 2. Export the Design Doc 3. Generate components with v0 4. Integrate into your React app ## How to Use ### 1. Get Your Design Doc From your Backdrift project's **Artifacts** tab, copy the Design Doc. ### 2. Generate in v0 Go to [v0.dev](https://v0.dev) and describe what you want: ``` Create a task management dashboard. The API returns tasks like this: { "id": "task-123", "title": "Ship the feature", "priority": "high", "status": "active", "assignee": { "id": "user-1", "name": "Alice" }, "due_date": "2024-01-20" } Include: - A table view with sortable columns - Status badges (pending=gray, active=blue, done=green) - Priority badges (low=gray, medium=yellow, high=red) - Assignee avatar and name - Due date with overdue highlighting - Actions column with edit and delete buttons ``` ### 3. Copy the Code v0 generates React + Tailwind + shadcn/ui code. Copy it to your project. ### 4. Connect to Your API Replace mock data with API calls: ```tsx theme={null} // Generated by v0 const tasks = [ { id: '1', title: 'Example', status: 'active' } ]; // Replace with: const { data: tasks } = useQuery({ queryKey: ['tasks'], queryFn: () => fetch('/api/tasks').then(r => r.json()) }); ``` ## Example: Task Board ### v0 Prompt ``` Create a Kanban board for tasks. Columns: "To Do", "In Progress", "Done" Each task card shows: - Title (bold) - Priority badge (high=red, medium=yellow, low=gray) - Assignee avatar (small circle with initials) - Due date in relative format ("Due in 3 days") Cards should be draggable between columns. Use shadcn/ui Card component with hover effects. Include a "+ Add Task" button at the bottom of each column. ``` ### Result v0 generates a complete Kanban component with: * Drag-and-drop (using @dnd-kit) * Styled cards with badges * Add task buttons * Responsive layout ## Example: Dashboard Charts ### v0 Prompt ``` Create an analytics dashboard for a task management app. Show: 1. Card with "Tasks Completed" count and +12% trend arrow 2. Card with "Active Tasks" count 3. Card with "Overdue Tasks" count (red if > 0) 4. Line chart showing tasks completed per day (last 7 days) 5. Pie chart showing task distribution by status Use shadcn/ui cards and Recharts for charts. Include loading skeletons. ``` ## Best Practices Show v0 what your API returns. Include example JSON. Include TypeScript types from your Design Doc: ``` type Task = { id: string; title: string; priority: 'low' | 'medium' | 'high'; } ``` Reference shadcn/ui components by name: "Use shadcn/ui Select for the status filter" "Make it responsive—single column on mobile, grid on desktop" ## Integrating v0 Components ### 1. Install Dependencies v0 components often need: ```bash theme={null} npm install @radix-ui/react-* # for shadcn/ui npm install recharts # for charts npm install @dnd-kit/core # for drag-and-drop ``` ### 2. Copy Component Code v0 provides copy-ready code. Paste into your project. ### 3. Add Data Fetching Replace static data with hooks: ```tsx theme={null} // From v0 (static): const tasks = [{ id: '1', title: 'Example' }]; // Your version (dynamic): const { data: tasks, isLoading } = useTasks(); if (isLoading) return ; ``` ### 4. Add Mutations Connect actions to your API: ```tsx theme={null} const updateTask = useMutation({ mutationFn: (update) => fetch(`/api/tasks/${update.id}`, { method: 'PUT', body: JSON.stringify(update) }), onSuccess: () => queryClient.invalidateQueries(['tasks']) }); // In drag handler: onDragEnd={(result) => { updateTask.mutate({ id: result.draggableId, status: result.destination.droppableId }); }} ``` ## v0 + Lovable/Bolt You can combine tools: 1. Generate **individual components** with v0 2. Build the **full application** with Lovable or Bolt 3. Copy v0 components into your Lovable/Bolt project ``` // In Lovable: "Here's a Kanban component I generated with v0: [paste component code] Integrate this into the dashboard, connected to the tasks API." ``` Learn about the built-in admin interface. # Introduction Source: https://backdrift.mintlify.app/introduction The AI Backend Engineer. Backdrift is an AI-powered platform that architects, validates, and deploys production-grade cloud backends from natural language. We bridge the gap between AI frontend builders (like **Lovable**, **Bolt**, and **v0**) and serious cloud infrastructure. You describe the logic; we handle the infrastructure complexity. ## The Backdrift Approach Describe your application ("A multi-tenant CRM") and get a fully deployed backend in minutes. We don't just build the API. We deploy a full **React + Vite** admin application to let you manage your data immediately. Our AI agents run hundreds of checks—security, cost, and architecture—before a single resource is deployed. We deploy standard cloud resources. You can export the raw Infrastructure-as-Code (CDK) at any time. ## Who is Backdrift for? Backdrift is designed for: * **Frontend developers** who want to add a backend to their AI-generated UIs without learning cloud infrastructure * **Startup founders** who need to move fast but can't afford security mistakes * **Agencies** building MVPs for clients who need production-ready backends * **Solo developers** who want enterprise-grade infrastructure without a DevOps team ## How it Works Use natural language to describe your application's entities, relationships, and business logic. Chat with the AI to iterate on your spec. Add features, adjust permissions, or clarify requirements. Our Validation Engine checks your design against security best practices, cost efficiency, and architectural patterns. One click deploys your entire backend—database, API, authentication, and frontend—to the cloud. ## What You Get Every Backdrift project includes: | Artifact | Description | | ------------------ | ----------------------------------------------------------------------------- | | **REST API** | A fully documented API with authentication, CRUD endpoints, and health checks | | **React Frontend** | A Vite + React admin app with login, data browser, and entity management | | **Authentication** | User signup, login, password reset, and role-based access control | | **Database** | DynamoDB (NoSQL) or RDS PostgreSQL with automatic schema generation | | **SDKs** | Python and TypeScript client libraries | | **Design Docs** | LLM-optimized documentation for AI coding assistants | ## Next Steps Deploy your first backend in 5 minutes. Understand the universal spec that powers everything. # Admin Dashboard Source: https://backdrift.mintlify.app/operations/admin-dashboard Manage your deployed backend with the built-in admin interface. Every Backdrift project includes an **Admin Dashboard**—a browser-based interface for managing your deployed backend without writing code. ## Accessing the Dashboard 1. Go to your project in Backdrift 2. Click the **Admin** tab 3. Use the built-in dashboard Or access the generated React frontend at your Amplify URL. ## Features View, create, edit, and delete records for any entity. View registered users, disable accounts, reset passwords. View scheduled jobs, trigger manual runs, see history. View execution logs from Lambda functions. ## Data Browser Browse and manage data for any entity in your blueprint. ### Viewing Records * Paginated table view * Sort by any column * Filter by field values * Search across text fields ### Creating Records 1. Click **+ New** 2. Fill in the form (validation included) 3. Click **Create** The form is auto-generated from your entity schema, including: * Required field indicators * Enum dropdowns * Date pickers * Foreign key selectors ### Editing Records 1. Click a row to open details 2. Click **Edit** 3. Modify fields 4. Click **Save** ### Deleting Records 1. Select rows with checkboxes 2. Click **Delete Selected** 3. Confirm deletion Deletion is permanent. Consider adding soft-delete to your blueprint if you need recovery. ## User Management View and manage users from your Cognito User Pool. ### User List | Column | Description | | ---------- | ------------------------------ | | Email | User's email address | | Status | Verified, Unverified, Disabled | | Created | Registration date | | Last Login | Most recent authentication | ### Actions * **Disable User** - Prevent login without deleting * **Enable User** - Restore access * **Reset Password** - Send password reset email * **Delete User** - Permanently remove (careful!) ## Jobs Monitor View and manage scheduled jobs. ### Job List | Column | Description | | -------- | -------------------------------- | | Name | Job identifier | | Schedule | Cron expression (human readable) | | Last Run | Timestamp and status | | Next Run | Scheduled next execution | ### Actions * **Run Now** - Trigger immediate execution * **View History** - See past 10 executions * **View Logs** - Jump to CloudWatch logs ### Execution History Expand any job to see recent runs: ``` ✅ 2024-01-15 00:00:02 (2.3s) - Success ✅ 2024-01-14 00:00:01 (2.1s) - Success ❌ 2024-01-13 00:00:03 (15.2s) - Failed: Connection timeout ✅ 2024-01-12 00:00:01 (2.0s) - Success ``` Click any run to view logs. ## Logs Viewer View execution logs from Lambda functions. ### Log Streams Select a function to see its log streams: * `create-task-handler` * `list-tasks-handler` * `job-cleanup-handler` * `health-handler` ### Log Events View individual log entries with: * Timestamp * Request ID * Log level (INFO, WARN, ERROR) * Message ### Filtering * Filter by time range * Search by keyword * Filter by log level ## Multi-Tenant View In multi-tenant mode, the Admin Dashboard respects tenant isolation: * **Organization Admins** see only their organization's data * **Platform Admins** (you) can switch between organizations ### Switching Organizations 1. Click the organization dropdown in the header 2. Select an organization 3. Data browser shows that org's data ## Seeding Data Populate your database with test data: 1. Go to the **Admin** tab 2. Click **Seed Data** 3. Choose a profile: * **Minimal** - Just enough to test * **Realistic** - Full sample dataset * **Stress Test** - Large volume for performance testing 4. Click **Seed** Seeding adds data—it doesn't clear existing records. Run on empty databases or be prepared for duplicates. ## Keyboard Shortcuts | Shortcut | Action | | -------- | --------------- | | `/` | Focus search | | `n` | New record | | `e` | Edit selected | | `d` | Delete selected | | `r` | Refresh data | | `?` | Show shortcuts | Learn more about populating test data. # Seed Data Source: https://backdrift.mintlify.app/operations/seed-data Populate your database with realistic test data. Seed data helps you test your application with realistic content. Backdrift generates contextual seed data based on your entity schemas. ## Seeding from the Dashboard 1. Go to your project's **Admin** tab 2. Click **Seed Data** 3. Select a profile 4. Click **Seed** ## Seed Profiles ### Minimal A small dataset for quick testing: * 1-2 users per role * 3-5 records per entity * Basic relationships **Use for:** Quick feature testing, demos ### Realistic A production-like dataset: * 10-20 users * 50-100 records per entity * Complex relationships * Varied data (different statuses, priorities, dates) **Use for:** User acceptance testing, screenshots, demos ### Stress Test Large volume for performance testing: * 100+ users * 1,000+ records per entity * Edge cases (very long text, special characters) **Use for:** Performance testing, pagination testing ## Smart Data Generation Backdrift generates contextually appropriate data based on field names and types: | Field | Generated Data | | -------------------- | ------------------------- | | `email` | Realistic fake emails | | `name`, `first_name` | Common names | | `phone` | Valid phone formats | | `address` | Real-looking addresses | | `title` (on Task) | Task-like titles | | `description` | Lorem-style paragraphs | | `price` | Reasonable dollar amounts | | `created_at` | Recent dates | | `due_date` | Future dates | ### Enums For enum fields, data is distributed realistically: * `status`: 40% pending, 40% active, 20% done * `priority`: 20% low, 50% medium, 30% high ### Relationships Seed data maintains referential integrity: * Tasks are assigned to existing projects * Comments belong to existing tasks * Users are linked to organizations ## Multi-Tenant Seeding In multi-tenant mode, seed data creates: * Multiple organizations * Users per organization * Isolated data per tenant Example distribution: ``` Acme Corp (org-1) ├── 5 users ├── 3 projects └── 15 tasks Beta Inc (org-2) ├── 3 users ├── 2 projects └── 10 tasks Gamma LLC (org-3) ├── 4 users ├── 4 projects └── 20 tasks ``` ## API Seeding Seed programmatically via API: ```bash theme={null} POST /projects/{projectId}/seed Authorization: Bearer $TOKEN Content-Type: application/json { "profile": "realistic", "options": { "clearExisting": false, "organizationCount": 3, "usersPerOrg": 5 } } ``` ### Options | Option | Type | Default | Description | | ------------------- | ------- | --------- | ------------------------------------- | | `profile` | string | "minimal" | minimal, realistic, stress | | `clearExisting` | boolean | false | Delete existing data first | | `organizationCount` | number | 3 | Number of tenants (multi-tenant only) | | `usersPerOrg` | number | 5 | Users per organization | ## Custom Seed Data For specific test scenarios, create records manually: 1. Use the **Data Browser** to create records 2. Export as JSON (coming soon) 3. Import to reset to that state ## Clearing Data To reset your database: 1. Go to **Admin** tab 2. Click **Clear Data** 3. Select entities to clear 4. Confirm deletion Clearing data is permanent. In production, consider using a separate test environment instead. ## Test Credentials Seeded users have predictable credentials: | Email | Password | Role | | ----------------------------------------------- | ------------ | ------ | | [admin@example.com](mailto:admin@example.com) | TestPass123! | admin | | [member@example.com](mailto:member@example.com) | TestPass123! | member | | [viewer@example.com](mailto:viewer@example.com) | TestPass123! | viewer | These are for testing only. In production, use real user signups. ## Best Practices Seed test data in dev/staging, not production. Clear and re-seed before important demos for clean data. The Stress Test profile includes edge cases—use it to find bugs. After seeding, verify relationships are correct in the Data Browser. # Quickstart Source: https://backdrift.mintlify.app/quickstart From prompt to production in 5 minutes. This guide walks you through creating and deploying your first Backdrift backend. ## Prerequisites * A Backdrift account ([sign up here](https://backdrift.ai)) * A modern web browser That's it. No AWS account, no CLI tools, no infrastructure knowledge required. ## Step 1: Create a Project Go to [backdrift.ai](https://backdrift.ai) and sign in. From the dashboard, click the **New Project** button. Give your project a name like "Task Manager" or "My First Backend". ## Step 2: Describe Your Backend You have two options: Choose from pre-built templates: * **Task Management** - Projects, tasks, team members * **E-commerce** - Products, orders, customers * **CRM** - Contacts, deals, activities * **Blog** - Posts, authors, comments Write a natural language description: ``` A task management app where users can create projects, add tasks with due dates and priorities, and assign tasks to team members. Each organization should have isolated data. ``` ## Step 3: Refine with AI Chat After your initial description, you can chat with the AI to refine your spec: ``` User: "Add a comments feature to tasks" AI: "I've added a comments entity with author, content, and timestamp fields..." User: "Tasks should have file attachments" AI: "I've added file storage support with S3 buckets configured..." ``` ## Step 4: Preview & Validate Before deploying, click **Preview** to see: * **Infrastructure Changes** - What resources will be created * **Cost Estimate** - Monthly cost at different usage tiers * **Validation Report** - Security and architecture checks Preview Dialog ## Step 5: Deploy Click **Deploy** and watch the magic happen: 1. ✅ Database tables created 2. ✅ Authentication configured 3. ✅ API endpoints deployed 4. ✅ Frontend application built 5. ✅ Health checks verified In about 2-3 minutes, you'll have: * A live **API URL** (e.g., `https://xyz123.execute-api.us-east-2.amazonaws.com`) * A live **Frontend URL** (your React admin app) * A **Cognito User Pool** for authentication ## Step 6: Test Your Backend ### Health Check ```bash theme={null} curl https://your-api-url.amazonaws.com/health ``` ```json theme={null} { "status": "healthy", "timestamp": "2024-01-15T10:30:00Z", "service": "task-manager-health-handler" } ``` ### Create a User Use the generated frontend to sign up, or use the AWS Console to create a test user in your Cognito User Pool. ### Make API Calls ```bash theme={null} # Get an access token (from Cognito) TOKEN="your-jwt-token" # List tasks curl https://your-api-url.amazonaws.com/v1/tasks \ -H "Authorization: Bearer $TOKEN" # Create a task curl -X POST https://your-api-url.amazonaws.com/v1/tasks \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"title": "My first task", "priority": "high"}' ``` ## What's Next? Get Python and TypeScript clients for your API. Use the Design Doc to build a frontend with Lovable. Use Spec Chat to add authentication, jobs, or file storage. Use the Admin Dashboard to browse and edit records. # Deployment Source: https://backdrift.mintlify.app/workflow/deployment Safe deployments, previews, and rollbacks. Backdrift deploys real cloud infrastructure. We take this seriously with previews, change classification, and instant rollbacks. ## Deployment Flow ```mermaid theme={null} graph LR A[Blueprint] --> B[Preview] B --> C[Classify Changes] C --> D[Deploy] D --> E[Monitor] E --> F[Rollback?] ``` ## Preview Before Deploy Before any infrastructure is touched, click **Preview** to see: ### Infrastructure Changes What resources will be created, updated, or deleted: ```diff theme={null} + AWS::DynamoDB::Table (tasks-table) + AWS::Lambda::Function (create-task-handler) + AWS::Lambda::Function (list-tasks-handler) ~ AWS::ApiGateway::RestApi (update routes) ``` ### Cost Estimate Estimated monthly costs at different usage tiers: | Tier | Estimated Cost | | ----------------------- | -------------- | | Starter (0-100 users) | \$12/month | | Production (100k users) | \$180/month | ### Validation Summary A final check of security, reliability, and performance issues. ## Change Classification When updating an existing deployment, changes are classified: No user confirmation needed: * Adding new entities * Adding new API endpoints * Adding new fields (nullable) * Updating Lambda function code Require acknowledgment: * Changing field types * Removing nullable constraint * Modifying indexes * Changing authentication settings Cannot proceed automatically: * Deleting entities with data * Removing required fields * Changing primary keys * Breaking API compatibility ## Deployment Progress During deployment, you see real-time progress: ``` Deploying to us-east-2... ✅ Cognito Stack (authentication) ✅ DynamoDB Stack (database) 🔄 Lambda Stack (functions) - 3/5 complete ⏳ API Gateway Stack (endpoints) ⏳ Amplify Stack (frontend) ``` Each stack deploys independently. If one fails, others continue. ## Stack Status After deployment, the **Infrastructure** tab shows per-stack status: | Stack | Status | Actions | | -------- | ---------- | ------------- | | cognito | ✅ Complete | - | | dynamodb | ✅ Complete | - | | lambda | ✅ Complete | View Logs | | api | ✅ Complete | Test Health | | amplify | ✅ Complete | View Frontend | ## Rollback Made a mistake? Rollback to any previous version: 1. Go to the **Infrastructure** tab 2. Click **Rollback** 3. Select a previous deployment 4. Confirm Rollback is fast (usually under 60 seconds) because we're reverting to a known-good state. Rollback reverts infrastructure configuration but does not restore deleted data. Always backup critical data before making changes. ## Continue Deploy If a deployment partially fails, you don't have to start over. Click **Continue Deploy** to: * Skip already-completed stacks * Retry failed stacks * Complete remaining stacks ## Regions Deploy to any supported AWS region: | Region | Location | Durable Functions | | --------- | ----------- | ----------------- | | us-east-1 | N. Virginia | ❌ | | us-east-2 | Ohio | ✅ | | us-west-2 | Oregon | ❌ | **Durable Functions** (long-running workflows) are currently only available in us-east-2. ## Destroy Stack To completely remove all infrastructure: 1. Go to the **Infrastructure** tab 2. Click **Destroy All** 3. Confirm deletion Stacks are deleted in dependency order (frontend → API → database → auth) to avoid errors. Destroying a stack permanently deletes all data. This cannot be undone. ## What Gets Deployed A typical Backdrift deployment creates: | Resource | Purpose | | ----------------- | -------------------------------- | | Cognito User Pool | Authentication | | DynamoDB Tables | Data storage | | Lambda Functions | API handlers | | API Gateway | REST API | | CloudWatch | Logs and monitoring | | Amplify App | Frontend hosting | | S3 Buckets | File storage (if configured) | | EventBridge Rules | Scheduled jobs (if configured) | | SQS Queues | Async processing (if configured) | Learn how to manage your deployed backend. # Prompting Source: https://backdrift.mintlify.app/workflow/prompting How to describe your backend to the AI. The quality of your backend depends on how well you describe it. This guide covers best practices for writing effective prompts. ## The Basics Backdrift's AI understands natural language. You don't need to use technical jargon or specific formats. Just describe what you want your application to do. ### Good Prompt Structure A good prompt typically includes: 1. **What the app does** - The core purpose 2. **Who uses it** - User types and roles 3. **What data it manages** - Entities and their relationships 4. **Special requirements** - Multi-tenancy, jobs, file storage ### Example: Task Management ``` A task management app where users can create projects, add tasks with due dates and priorities, and assign tasks to team members. Each organization should have isolated data. Organization admins can invite members and assign roles (admin, member, viewer). ``` This prompt tells Backdrift: * Core entities: projects, tasks, users * Relationships: tasks belong to projects, users belong to organizations * Multi-tenancy: organizations have isolated data * Roles: admin, member, viewer ## Prompt Patterns ### Multi-Tenant SaaS ``` A multi-tenant [type of app] where each organization has isolated data. Organization admins can invite members and assign roles. ``` ### Event-Driven Workflows ``` When a [event happens], send a [notification/email]. Run a [frequency] job to [do something]. ``` ### File Storage ``` Users can upload [file types] to [entity]. Files should be stored securely with [requirements]. ``` ## What to Include Be specific about what data you need to store: ``` Tasks have a title, description, due date, priority (low/medium/high), and status (pending/in-progress/done). ``` Explain how entities connect: ``` Tasks belong to projects. Projects belong to organizations. Users can be assigned to multiple tasks. ``` Define who can do what: ``` Admins can create and delete projects. Members can create tasks but not delete projects. Viewers can only read data. ``` Describe automated processes: ``` When a task is marked complete, notify the project owner. Every night, send a digest of overdue tasks. ``` ## What NOT to Include Avoid implementation details. Let Backdrift decide how to build it. ❌ Don't say: "Use DynamoDB with a GSI on user\_id" ✅ Do say: "Users should be able to query their own tasks efficiently" ❌ Don't say: "Create a Lambda function triggered by SQS" ✅ Do say: "Process task assignments asynchronously" ❌ Don't say: "Use Cognito with OAuth 2.0" ✅ Do say: "Users sign in with email and password" ## Example Prompts ### E-commerce Platform ``` An e-commerce platform with products, categories, and orders. Customers can browse products, add to cart, and checkout. Admins can manage products, view orders, and update inventory. When an order is placed, send a confirmation email. Run a daily job to check for low inventory and alert admins. ``` ### Customer Support System ``` A customer support ticketing system. Customers submit tickets with a subject and description. Support agents are assigned tickets and can respond. Managers can see all tickets and reassign them. Track ticket status: open, in-progress, resolved, closed. When a ticket is resolved, email the customer. ``` ### Booking System ``` A booking system for a fitness studio. Classes have a name, instructor, time, and capacity. Members can book spots in classes. Instructors can view their schedule. Don't allow overbooking—enforce capacity limits. Send a reminder email 24 hours before each class. ``` ## Iterating on Your Prompt After your initial prompt, use [Spec Chat](/workflow/spec-chat) to refine: ``` User: "Add a comments feature to tasks" User: "Make the due date required" User: "Add file attachments to tickets" User: "Change the status options to: new, active, blocked, done" ``` Learn how to iterate on your backend with conversational AI. # Spec Chat Source: https://backdrift.mintlify.app/workflow/spec-chat Iterate on your backend with conversational AI. **Spec Chat** is Backdrift's conversational interface for refining your backend specification. Instead of editing JSON or code, you chat with the AI to add features, modify entities, and adjust behavior. ## How It Works After your initial prompt generates a spec, you can continue the conversation: ``` You: "Add a comments feature to tasks" AI: "I've added a Comment entity with the following fields: - id (string, primary key) - task_id (foreign key to Task) - author_id (foreign key to User) - content (string) - created_at (datetime) Comments are scoped to the same tenant as their parent task." ``` The AI understands context from your existing spec and makes intelligent decisions about relationships, permissions, and data modeling. ## Common Operations ### Adding Features ``` "Add file attachments to tasks" "Add a comments section to projects" "Add tags to tasks with autocomplete support" ``` ### Modifying Entities ``` "Make the due_date field required" "Add a 'blocked' status to tasks" "Change priority from string to enum: low, medium, high, urgent" ``` ### Adjusting Permissions ``` "Only admins should be able to delete projects" "Viewers should not see the 'salary' field on employees" "Allow members to update tasks but not delete them" ``` ### Adding Workflows ``` "Send an email when a task is assigned" "Run a nightly job to archive completed tasks older than 30 days" "When a user signs up, create a default organization for them" ``` ## Capability Detection Spec Chat automatically detects what cloud capabilities your request needs: | Request | Detected Capability | | --------------------------------- | ---------------------------- | | "Send email notifications" | Email (SES) | | "Upload profile pictures" | File Storage (S3) | | "Run a nightly cleanup job" | Scheduled Jobs (EventBridge) | | "Process payments asynchronously" | Durable Workflows | If you request something we don't support yet, the AI will suggest alternatives: ``` You: "Add SAML single sign-on" AI: "SAML is not currently supported. However, I can configure: - Email/password authentication with MFA - Social login (Google, GitHub) via Cognito federation Would you like me to add social login instead?" ``` ## Chat History Your conversation history is saved per project. You can: * Review previous changes * Understand why certain decisions were made * Pick up where you left off ## Tips for Effective Chatting ❌ "Add notifications" ✅ "Send an email to the project owner when a task is marked complete" ❌ "Add comments, file attachments, and activity logging" ✅ "Add comments to tasks" → "Add file attachments" → "Add activity logging" You can ask the AI to explain its decisions: * "Why did you add a tenant\_id to comments?" * "What indexes will be created for tasks?" * "How will file uploads work?" If you don't like a change: * "Undo the last change" * "Remove the comments feature" * "Go back to before I added file attachments" ## Applying Changes After chatting, your changes are in a **draft** state. Click **Apply Spec** to save them to your project. Only applied specs can be: * Used to generate Blueprints * Validated * Deployed Learn how Backdrift validates your spec before deployment. # Validation & Safety Source: https://backdrift.mintlify.app/workflow/validation How we ensure your backend is secure and cost-effective. Generating code with AI is easy; generating **safe, production-ready** infrastructure is hard. Backdrift includes a dedicated Validation Engine that runs before deployment. ## The Validation Engine We analyze your Blueprint against the **Well-Architected Framework**, scoring it across five pillars: PII detection, tenant isolation, access controls Backups, recovery, fault tolerance Indexing, caching, query optimization Resource sizing, usage estimates Logging, metrics, health checks ## Validation Report After running validation, you'll see a detailed report: ``` Overall Score: 85/100 Security (90/100) ├── ✅ Multi-tenant isolation configured ├── ✅ JWT authentication enabled ├── ⚠️ PII detected: email field on User entity └── ⚠️ No audit logging configured Reliability (80/100) ├── ✅ Point-in-time recovery enabled ├── ✅ created_at/updated_at timestamps present └── ⚠️ No soft delete configured Performance (95/100) ├── ✅ Primary key indexes created ├── ✅ Foreign key indexes created └── ✅ Tenant key indexes created Cost (75/100) ├── ✅ Pay-per-request billing (no over-provisioning) └── ⚠️ Estimated monthly cost: $45-$120 Operations (85/100) ├── ✅ Health endpoint configured ├── ✅ Structured logging enabled └── ⚠️ No custom alarms configured ``` ## PII Detection Backdrift automatically detects Personally Identifiable Information: | Field Pattern | Detection | | ------------------------ | ------------------ | | `email`, `email_address` | Email PII | | `phone`, `phone_number` | Phone PII | | `ssn`, `social_security` | SSN PII (Critical) | | `address`, `street` | Address PII | | `dob`, `birth_date` | Date of Birth PII | When PII is detected, we recommend: * Encryption at rest * Access logging * Data retention policies ## Auto-Fixes Backdrift doesn't just complain—it fixes. ### Safe Fixes (Low Risk) Applied automatically or with one click: * Adding `created_at` and `updated_at` timestamps * Enabling structured logging * Adding missing indexes * Setting default retention policies ### Medium Risk Fixes Require confirmation: * Enabling encryption on existing fields * Adding audit logging * Changing field types ### High Risk Fixes Require explicit acknowledgment: * Removing fields (data loss potential) * Changing primary keys * Modifying tenant isolation ## One-Click Fix All For issues classified as **Safe**, you can apply all fixes at once: ``` Found 5 safe fixes: ├── Add created_at to Task entity ├── Add updated_at to Task entity ├── Enable point-in-time recovery on Task table ├── Add index on project_id field └── Configure log retention (30 days) [Apply All Safe Fixes] ``` ## Cost Estimation Before deploying, we estimate your monthly costs at two tiers: | Tier | Users | Estimated Cost | | -------------- | ----------- | --------------- | | **Starter** | 0-100 users | $5-$25/month | | **Production** | 100k+ users | $150-$500/month | This includes: * Database storage and read/write operations * API Gateway requests * Lambda invocations * Authentication operations * File storage (if configured) Estimates are based on typical usage patterns. Actual costs depend on your specific traffic and data volumes. ## Non-Technical Summary For stakeholders who don't speak "infrastructure", we generate plain-English summaries: ``` Your backend is ready for production with a few recommendations: ✅ Security is strong - user data is isolated by organization ✅ Performance is optimized - all queries will be fast ⚠️ Consider adding audit logging for compliance ⚠️ Email addresses should have additional protection Estimated cost: $15-$45/month for typical startup usage ``` Ready to deploy? Learn about safe deployments and rollbacks.