Last updated: Aug 4, 2025, 11:26 AM UTC

API Reference Documentation

Status: Complete
Version: 2.0
Last Updated: 2024
Base URL: https://api.nudgecampaign.com/v2

Overview

The NudgeCampaign API is a RESTful API that provides programmatic access to all platform features. This comprehensive reference documentation covers authentication, all available endpoints, request/response formats, error handling, rate limiting, webhooks, and SDK usage.

API Design Principles

  1. RESTful Architecture: Standard HTTP methods and status codes
  2. JSON Format: All requests and responses use JSON
  3. Consistent Naming: Snake_case for fields, plural for collections
  4. Pagination: Cursor-based pagination for large datasets
  5. Versioning: Path-based versioning (v1, v2, etc.)
  6. Idempotency: Safe retries with idempotency keys
  7. Rate Limiting: Fair usage with clear limits

Table of Contents

  1. Authentication
  2. Core Resources
  3. Campaign Endpoints
  4. Contact Endpoints
  5. Template Endpoints
  6. Analytics Endpoints
  7. Automation Endpoints
  8. Organization Endpoints
  9. Webhook Management
  10. Error Handling
  11. Rate Limiting
  12. SDK Usage
  13. OpenAPI Specification

Authentication

NudgeCampaign uses Bearer token authentication with JWT tokens. All API requests must include a valid authentication token.

Authentication Flow

sequenceDiagram participant Client participant API participant Auth as Auth Service participant DB as Database Client->>API: POST /auth/login API->>Auth: Validate credentials Auth->>DB: Check user DB-->>Auth: User data Auth-->>API: Generate JWT API-->>Client: Access token + Refresh token Note over Client: Store tokens securely Client->>API: GET /campaigns + Bearer token API->>Auth: Validate token Auth-->>API: Token valid API->>DB: Query with RLS DB-->>API: Filtered data API-->>Client: Response data

Obtaining Access Tokens

Login Endpoint

POST /v2/auth/login
Content-Type: application/json

{
  "email": "user@example.com",
  "password": "secure_password"
}

Response:

{
  "access_token": "eyJhbGciOiJIUzI1NiIs...",
  "refresh_token": "eyJhbGciOiJIUzI1NiIs...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "user": {
    "id": "usr_abc123",
    "email": "user@example.com",
    "organization_id": "org_def456",
    "role": "admin"
  }
}

Using Access Tokens

Include the access token in the Authorization header:

GET /v2/campaigns
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...

Refreshing Tokens

POST /v2/auth/refresh
Content-Type: application/json

{
  "refresh_token": "eyJhbGciOiJIUzI1NiIs..."
}

API Key Authentication

For server-to-server communication, use API keys:

GET /v2/campaigns
X-API-Key: sk_live_abc123def456ghi789

OAuth 2.0 Support

NudgeCampaign supports OAuth 2.0 for third-party integrations:

GET /v2/oauth/authorize?
  client_id=YOUR_CLIENT_ID&
  redirect_uri=YOUR_REDIRECT_URI&
  response_type=code&
  scope=campaigns:read contacts:write&
  state=RANDOM_STATE

Core Resources

Resource Structure

All resources follow a consistent structure:

{
  "data": {
    "id": "resource_id",
    "type": "resource_type",
    "attributes": {
      // Resource-specific attributes
    },
    "relationships": {
      // Related resources
    },
    "meta": {
      "created_at": "2024-01-01T00:00:00Z",
      "updated_at": "2024-01-01T00:00:00Z"
    }
  }
}

Common Parameters

Parameter Type Description
page[size] integer Number of items per page (max: 100)
page[cursor] string Cursor for pagination
sort string Sort field (prefix with - for descending)
filter[field] string Filter by field value
include string Include related resources
fields[type] string Sparse fieldsets

Response Headers

HTTP/1.1 200 OK
Content-Type: application/json
X-Request-Id: req_abc123
X-Rate-Limit-Limit: 1000
X-Rate-Limit-Remaining: 999
X-Rate-Limit-Reset: 1640995200

Campaign Endpoints

Campaigns are the core resource for email marketing activities.

Campaign Object

{
  "id": "cmp_abc123",
  "organization_id": "org_def456",
  "user_id": "usr_ghi789",
  "name": "Summer Sale Campaign",
  "subject": "Don't Miss Our Summer Sale!",
  "from_name": "NudgeCampaign Team",
  "from_email": "hello@example.com",
  "reply_to": "support@example.com",
  "html_content": "<html>...</html>",
  "text_content": "Plain text version...",
  "status": "draft",
  "scheduled_at": "2024-07-01T10:00:00Z",
  "sent_at": null,
  "settings": {
    "track_opens": true,
    "track_clicks": true,
    "google_analytics": true,
    "auto_footer": true
  },
  "stats": {
    "recipients": 5000,
    "delivered": 4950,
    "opened": 2500,
    "clicked": 500,
    "bounced": 50,
    "complained": 5,
    "unsubscribed": 10
  },
  "created_at": "2024-01-01T00:00:00Z",
  "updated_at": "2024-01-01T00:00:00Z"
}

List Campaigns

GET /v2/campaigns

Query Parameters:

  • filter[status] - Filter by status (draft, scheduled, sending, sent, cancelled)
  • filter[created_after] - Filter by creation date
  • sort - Sort by field (created_at, scheduled_at, name)
  • include - Include related data (stats, templates, recipients)

Example Request:

GET /v2/campaigns?filter[status]=sent&sort=-created_at&page[size]=20
Authorization: Bearer YOUR_TOKEN

Response:

{
  "data": [
    {
      "id": "cmp_abc123",
      "type": "campaign",
      "attributes": {
        "name": "Summer Sale Campaign",
        "subject": "Don't Miss Our Summer Sale!",
        "status": "sent",
        "sent_at": "2024-07-01T10:00:00Z"
      }
    }
  ],
  "meta": {
    "total": 150,
    "page_size": 20,
    "has_more": true
  },
  "links": {
    "self": "/v2/campaigns?page[size]=20",
    "next": "/v2/campaigns?page[size]=20&page[cursor]=abc123"
  }
}

Get Campaign

GET /v2/campaigns/{campaign_id}

Path Parameters:

  • campaign_id - The campaign identifier

Example Request:

GET /v2/campaigns/cmp_abc123?include=stats,recipients
Authorization: Bearer YOUR_TOKEN

Create Campaign

POST /v2/campaigns

Request Body:

{
  "name": "Black Friday Sale",
  "subject": "48 Hour Flash Sale - Up to 70% Off!",
  "from_name": "Your Store",
  "from_email": "deals@yourstore.com",
  "reply_to": "support@yourstore.com",
  "html_content": "<html><body><h1>Black Friday Sale!</h1></body></html>",
  "text_content": "Black Friday Sale! Visit our store...",
  "recipient_list_id": "lst_xyz789",
  "template_id": "tpl_abc123",
  "settings": {
    "track_opens": true,
    "track_clicks": true,
    "google_analytics": true
  }
}

Response:

{
  "data": {
    "id": "cmp_new123",
    "type": "campaign",
    "attributes": {
      "name": "Black Friday Sale",
      "status": "draft",
      "created_at": "2024-01-15T10:00:00Z"
    }
  }
}

Update Campaign

PUT /v2/campaigns/{campaign_id}

Request Body:

{
  "name": "Updated Campaign Name",
  "subject": "New Subject Line",
  "html_content": "<html>Updated content</html>"
}

Delete Campaign

DELETE /v2/campaigns/{campaign_id}

Response:

HTTP/1.1 204 No Content

Schedule Campaign

POST /v2/campaigns/{campaign_id}/schedule

Request Body:

{
  "scheduled_at": "2024-07-01T10:00:00Z",
  "timezone": "America/New_York",
  "send_time_optimization": true
}

Send Test Email

POST /v2/campaigns/{campaign_id}/test

Request Body:

{
  "recipients": [
    "test1@example.com",
    "test2@example.com"
  ],
  "personalization": {
    "first_name": "John",
    "last_name": "Doe"
  }
}

Duplicate Campaign

POST /v2/campaigns/{campaign_id}/duplicate

Request Body:

{
  "name": "Copy of Summer Campaign",
  "include_recipients": false
}

Campaign Analytics

GET /v2/campaigns/{campaign_id}/analytics

Query Parameters:

  • granularity - Time granularity (hour, day, week, month)
  • metrics - Specific metrics to include
  • start_date - Start date for analytics
  • end_date - End date for analytics

Response:

{
  "data": {
    "campaign_id": "cmp_abc123",
    "metrics": {
      "sent": 5000,
      "delivered": 4950,
      "delivery_rate": 0.99,
      "opened": 2500,
      "open_rate": 0.505,
      "clicked": 500,
      "click_rate": 0.101,
      "click_to_open_rate": 0.2,
      "bounced": 50,
      "bounce_rate": 0.01,
      "complained": 5,
      "complaint_rate": 0.001,
      "unsubscribed": 10,
      "unsubscribe_rate": 0.002
    },
    "timeline": [
      {
        "timestamp": "2024-07-01T10:00:00Z",
        "sent": 1000,
        "delivered": 995,
        "opened": 100,
        "clicked": 20
      }
    ],
    "links": [
      {
        "url": "https://example.com/sale",
        "clicks": 300,
        "unique_clicks": 250
      }
    ],
    "devices": {
      "desktop": 0.6,
      "mobile": 0.35,
      "tablet": 0.05
    },
    "clients": {
      "gmail": 0.4,
      "outlook": 0.3,
      "apple_mail": 0.2,
      "other": 0.1
    }
  }
}

Contact Endpoints

Contacts represent email recipients in your organization.

Contact Object

{
  "id": "con_abc123",
  "organization_id": "org_def456",
  "email": "john.doe@example.com",
  "first_name": "John",
  "last_name": "Doe",
  "status": "subscribed",
  "source": "import",
  "tags": ["customer", "vip", "newsletter"],
  "custom_fields": {
    "company": "Acme Corp",
    "birthday": "1990-01-01",
    "preferences": {
      "frequency": "weekly",
      "categories": ["tech", "news"]
    }
  },
  "lists": ["lst_abc123", "lst_def456"],
  "stats": {
    "campaigns_received": 25,
    "campaigns_opened": 20,
    "campaigns_clicked": 5,
    "last_opened_at": "2024-01-10T15:30:00Z",
    "last_clicked_at": "2024-01-08T10:15:00Z"
  },
  "subscribed_at": "2023-01-01T00:00:00Z",
  "unsubscribed_at": null,
  "created_at": "2023-01-01T00:00:00Z",
  "updated_at": "2024-01-15T00:00:00Z"
}

List Contacts

GET /v2/contacts

Query Parameters:

  • filter[status] - Filter by subscription status
  • filter[tag] - Filter by tag
  • filter[list_id] - Filter by list membership
  • search - Search by email, name
  • sort - Sort field

Example Request:

GET /v2/contacts?filter[status]=subscribed&filter[tag]=vip&sort=-created_at
Authorization: Bearer YOUR_TOKEN

Get Contact

GET /v2/contacts/{contact_id}

Create Contact

POST /v2/contacts

Request Body:

{
  "email": "new.contact@example.com",
  "first_name": "Jane",
  "last_name": "Smith",
  "tags": ["lead", "webinar"],
  "custom_fields": {
    "company": "Tech Corp",
    "role": "Marketing Manager"
  },
  "lists": ["lst_abc123"],
  "double_opt_in": true
}

Update Contact

PUT /v2/contacts/{contact_id}

Delete Contact

DELETE /v2/contacts/{contact_id}

Bulk Import Contacts

POST /v2/contacts/import

Request Body (Multipart):

Content-Type: multipart/form-data

file: contacts.csv
mapping: {"email": 0, "first_name": 1, "last_name": 2}
list_id: lst_abc123
update_existing: true
trigger_automations: false

Response:

{
  "data": {
    "import_id": "imp_abc123",
    "status": "processing",
    "total": 5000,
    "processed": 0,
    "succeeded": 0,
    "failed": 0,
    "created_at": "2024-01-15T10:00:00Z"
  }
}

Check Import Status

GET /v2/contacts/import/{import_id}

Export Contacts

POST /v2/contacts/export

Request Body:

{
  "format": "csv",
  "fields": ["email", "first_name", "last_name", "tags"],
  "filters": {
    "status": "subscribed",
    "tags": ["customer"]
  }
}

Contact Activity

GET /v2/contacts/{contact_id}/activity

Response:

{
  "data": [
    {
      "type": "email_sent",
      "campaign_id": "cmp_abc123",
      "timestamp": "2024-01-10T10:00:00Z"
    },
    {
      "type": "email_opened",
      "campaign_id": "cmp_abc123",
      "timestamp": "2024-01-10T15:30:00Z",
      "metadata": {
        "ip_address": "192.168.1.1",
        "user_agent": "Mozilla/5.0...",
        "location": "New York, US"
      }
    }
  ]
}

Subscribe/Unsubscribe

POST /v2/contacts/{contact_id}/subscribe
POST /v2/contacts/{contact_id}/unsubscribe

Request Body:

{
  "reason": "User requested",
  "feedback": "Too many emails",
  "suppress_notification": false
}

Template Endpoints

Templates are reusable email designs.

Template Object

{
  "id": "tpl_abc123",
  "organization_id": "org_def456",
  "name": "Newsletter Template",
  "description": "Monthly newsletter design",
  "category": "newsletter",
  "thumbnail_url": "https://cdn.nudgecampaign.com/templates/thumb_abc123.png",
  "html_content": "<html>{{content}}</html>",
  "text_content": "{{content}}",
  "variables": [
    {
      "name": "header_image",
      "type": "image",
      "default": "https://example.com/header.png"
    },
    {
      "name": "content",
      "type": "html",
      "required": true
    }
  ],
  "usage_count": 45,
  "is_public": false,
  "created_at": "2024-01-01T00:00:00Z"
}

List Templates

GET /v2/templates

Query Parameters:

  • filter[category] - Filter by category
  • filter[is_public] - Filter public/private templates
  • search - Search by name or description

Get Template

GET /v2/templates/{template_id}

Create Template

POST /v2/templates

Request Body:

{
  "name": "Product Announcement",
  "description": "Template for product launches",
  "category": "announcement",
  "html_content": "<html><body>{{product_name}}</body></html>",
  "text_content": "Announcing {{product_name}}",
  "variables": [
    {
      "name": "product_name",
      "type": "text",
      "required": true
    }
  ]
}

Update Template

PUT /v2/templates/{template_id}

Delete Template

DELETE /v2/templates/{template_id}

Duplicate Template

POST /v2/templates/{template_id}/duplicate

Preview Template

POST /v2/templates/{template_id}/preview

Request Body:

{
  "variables": {
    "product_name": "Amazing Product",
    "price": "$99.99"
  },
  "contact_id": "con_abc123"
}

Analytics Endpoints

Analytics provide insights into campaign performance and engagement.

Overview Analytics

GET /v2/analytics/overview

Query Parameters:

  • period - Time period (today, week, month, year, custom)
  • start_date - Custom start date
  • end_date - Custom end date
  • timezone - Timezone for data

Response:

{
  "data": {
    "summary": {
      "total_sent": 50000,
      "total_delivered": 49500,
      "total_opened": 25000,
      "total_clicked": 5000,
      "total_revenue": 15000.00,
      "average_open_rate": 0.505,
      "average_click_rate": 0.101
    },
    "trends": {
      "sent": [
        {"date": "2024-01-01", "value": 1000},
        {"date": "2024-01-02", "value": 1200}
      ],
      "opened": [
        {"date": "2024-01-01", "value": 500},
        {"date": "2024-01-02", "value": 600}
      ]
    },
    "top_campaigns": [
      {
        "id": "cmp_abc123",
        "name": "January Newsletter",
        "open_rate": 0.65,
        "click_rate": 0.15
      }
    ],
    "engagement_by_day": {
      "monday": 0.45,
      "tuesday": 0.52,
      "wednesday": 0.58,
      "thursday": 0.55,
      "friday": 0.48,
      "saturday": 0.35,
      "sunday": 0.30
    },
    "engagement_by_hour": {
      "9": 0.65,
      "10": 0.70,
      "11": 0.68
    }
  }
}

Contact Analytics

GET /v2/analytics/contacts

Response:

{
  "data": {
    "total_contacts": 10000,
    "subscribed": 9500,
    "unsubscribed": 400,
    "bounced": 100,
    "growth_rate": 0.05,
    "churn_rate": 0.01,
    "list_growth": [
      {"date": "2024-01-01", "total": 9000},
      {"date": "2024-01-02", "total": 9050}
    ],
    "sources": {
      "import": 5000,
      "api": 2000,
      "signup_form": 2000,
      "manual": 1000
    },
    "engagement_segments": {
      "highly_engaged": 2000,
      "engaged": 3000,
      "inactive": 4000,
      "never_engaged": 1000
    }
  }
}

Revenue Analytics

GET /v2/analytics/revenue

Response:

{
  "data": {
    "total_revenue": 50000.00,
    "revenue_per_email": 1.00,
    "revenue_per_contact": 5.00,
    "conversion_rate": 0.02,
    "average_order_value": 125.00,
    "revenue_by_campaign": [
      {
        "campaign_id": "cmp_abc123",
        "campaign_name": "Summer Sale",
        "revenue": 15000.00,
        "conversions": 120
      }
    ],
    "revenue_timeline": [
      {"date": "2024-01-01", "revenue": 2000.00},
      {"date": "2024-01-02", "revenue": 2500.00}
    ]
  }
}

Email Client Analytics

GET /v2/analytics/clients

Geographic Analytics

GET /v2/analytics/geographic

Device Analytics

GET /v2/analytics/devices

Automation Endpoints

Automations enable triggered email sequences and workflows.

Automation Object

{
  "id": "aut_abc123",
  "organization_id": "org_def456",
  "name": "Welcome Series",
  "description": "3-email welcome sequence for new subscribers",
  "status": "active",
  "trigger": {
    "type": "contact_subscribed",
    "conditions": {
      "list_id": "lst_abc123"
    }
  },
  "workflow": {
    "steps": [
      {
        "id": "step_1",
        "type": "send_email",
        "delay": "immediate",
        "campaign_id": "cmp_welcome1"
      },
      {
        "id": "step_2",
        "type": "wait",
        "delay": "2 days"
      },
      {
        "id": "step_3",
        "type": "send_email",
        "campaign_id": "cmp_welcome2"
      }
    ]
  },
  "stats": {
    "total_enrolled": 1500,
    "currently_active": 50,
    "completed": 1450,
    "stopped": 0
  },
  "created_at": "2024-01-01T00:00:00Z"
}

List Automations

GET /v2/automations

Get Automation

GET /v2/automations/{automation_id}

Create Automation

POST /v2/automations

Request Body:

{
  "name": "Abandoned Cart Recovery",
  "description": "Recover abandoned shopping carts",
  "trigger": {
    "type": "custom_event",
    "event_name": "cart_abandoned"
  },
  "workflow": {
    "steps": [
      {
        "type": "wait",
        "delay": "1 hour"
      },
      {
        "type": "send_email",
        "template_id": "tpl_cart_recovery",
        "subject": "You left something behind!"
      },
      {
        "type": "condition",
        "if": {
          "event": "purchase_completed"
        },
        "then": "exit",
        "else": "continue"
      },
      {
        "type": "wait",
        "delay": "24 hours"
      },
      {
        "type": "send_email",
        "template_id": "tpl_cart_discount",
        "subject": "10% off your cart items!"
      }
    ]
  }
}

Update Automation

PUT /v2/automations/{automation_id}

Delete Automation

DELETE /v2/automations/{automation_id}

Start/Pause Automation

POST /v2/automations/{automation_id}/start
POST /v2/automations/{automation_id}/pause

Automation Activity

GET /v2/automations/{automation_id}/activity

Enroll Contact in Automation

POST /v2/automations/{automation_id}/enroll

Request Body:

{
  "contact_id": "con_abc123",
  "metadata": {
    "source": "api",
    "custom_field": "value"
  }
}

Organization Endpoints

Organizations represent customer accounts in the multi-tenant system.

Organization Object

{
  "id": "org_abc123",
  "name": "Acme Corporation",
  "slug": "acme-corp",
  "domain": "acme.com",
  "timezone": "America/New_York",
  "settings": {
    "default_from_name": "Acme Team",
    "default_from_email": "hello@acme.com",
    "footer_address": "123 Main St, New York, NY 10001",
    "branding": {
      "logo_url": "https://cdn.nudgecampaign.com/logos/acme.png",
      "primary_color": "#22C55E",
      "font_family": "Inter"
    }
  },
  "subscription": {
    "plan": "pro",
    "status": "active",
    "email_limit": 100000,
    "emails_sent": 45000,
    "billing_period_end": "2024-02-01T00:00:00Z"
  },
  "stats": {
    "total_contacts": 10000,
    "total_campaigns": 150,
    "total_emails_sent": 500000
  },
  "created_at": "2023-01-01T00:00:00Z"
}

Get Organization

GET /v2/organization

Update Organization

PUT /v2/organization

Request Body:

{
  "name": "Updated Company Name",
  "timezone": "Europe/London",
  "settings": {
    "default_from_name": "New Team Name"
  }
}

Organization Users

GET /v2/organization/users

Response:

{
  "data": [
    {
      "id": "usr_abc123",
      "email": "admin@acme.com",
      "full_name": "John Admin",
      "role": "owner",
      "status": "active",
      "last_login_at": "2024-01-15T10:00:00Z"
    }
  ]
}

Invite User

POST /v2/organization/users/invite

Request Body:

{
  "email": "newuser@acme.com",
  "role": "editor",
  "send_invitation_email": true
}

Update User Role

PUT /v2/organization/users/{user_id}

Request Body:

{
  "role": "admin"
}

Remove User

DELETE /v2/organization/users/{user_id}

Organization API Keys

GET /v2/organization/api-keys

Create API Key

POST /v2/organization/api-keys

Request Body:

{
  "name": "Production API Key",
  "scopes": ["campaigns:read", "campaigns:write", "contacts:read"],
  "expires_at": "2025-01-01T00:00:00Z"
}

Response:

{
  "data": {
    "id": "key_abc123",
    "key": "sk_live_abc123def456ghi789",
    "name": "Production API Key",
    "scopes": ["campaigns:read", "campaigns:write", "contacts:read"],
    "created_at": "2024-01-15T10:00:00Z",
    "expires_at": "2025-01-01T00:00:00Z"
  }
}

Revoke API Key

DELETE /v2/organization/api-keys/{key_id}

Webhook Management

Webhooks provide real-time notifications for events in your account.

Webhook Events

Available webhook events:

  • email.sent - Email was sent
  • email.delivered - Email was delivered
  • email.opened - Email was opened
  • email.clicked - Link was clicked
  • email.bounced - Email bounced
  • email.complained - Spam complaint received
  • contact.subscribed - Contact subscribed
  • contact.unsubscribed - Contact unsubscribed
  • contact.updated - Contact information updated
  • campaign.completed - Campaign finished sending
  • automation.enrolled - Contact enrolled in automation
  • automation.completed - Contact completed automation

Webhook Payload

{
  "id": "evt_abc123",
  "type": "email.opened",
  "created_at": "2024-01-15T10:30:00Z",
  "data": {
    "campaign_id": "cmp_abc123",
    "contact_id": "con_def456",
    "email": "user@example.com",
    "timestamp": "2024-01-15T10:30:00Z",
    "metadata": {
      "ip_address": "192.168.1.1",
      "user_agent": "Mozilla/5.0...",
      "location": "New York, US"
    }
  }
}

Webhook Security

All webhook requests include a signature header for verification:

POST https://your-webhook-url.com/webhook
Content-Type: application/json
X-NudgeCampaign-Signature: sha256=abc123def456...

{...webhook payload...}

Verification Example (Node.js):

const crypto = require('crypto');

function verifyWebhook(payload, signature, secret) {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(payload)
    .digest('hex');
  
  return `sha256=${expectedSignature}` === signature;
}

List Webhooks

GET /v2/webhooks

Create Webhook

POST /v2/webhooks

Request Body:

{
  "url": "https://your-app.com/webhook",
  "events": ["email.opened", "email.clicked", "contact.subscribed"],
  "description": "Production webhook",
  "active": true
}

Update Webhook

PUT /v2/webhooks/{webhook_id}

Delete Webhook

DELETE /v2/webhooks/{webhook_id}

Test Webhook

POST /v2/webhooks/{webhook_id}/test

Request Body:

{
  "event": "email.opened"
}

Webhook Logs

GET /v2/webhooks/{webhook_id}/logs

Response:

{
  "data": [
    {
      "id": "log_abc123",
      "webhook_id": "whk_def456",
      "event_type": "email.opened",
      "status": "success",
      "status_code": 200,
      "duration_ms": 125,
      "timestamp": "2024-01-15T10:30:00Z",
      "request": {
        "headers": {...},
        "body": {...}
      },
      "response": {
        "headers": {...},
        "body": "OK"
      }
    }
  ]
}

Error Handling

NudgeCampaign API uses standard HTTP status codes and provides detailed error responses.

Error Response Format

{
  "error": {
    "type": "validation_error",
    "message": "The request contains invalid parameters",
    "code": "ERR_VALIDATION",
    "details": [
      {
        "field": "email",
        "message": "Invalid email format",
        "code": "invalid_format"
      }
    ],
    "request_id": "req_abc123",
    "documentation_url": "https://docs.nudgecampaign.com/api/errors/ERR_VALIDATION"
  }
}

HTTP Status Codes

Status Code Description
200 OK Request succeeded
201 Created Resource created successfully
204 No Content Request succeeded with no response body
400 Bad Request Invalid request parameters
401 Unauthorized Missing or invalid authentication
403 Forbidden Insufficient permissions
404 Not Found Resource not found
409 Conflict Resource conflict (e.g., duplicate)
422 Unprocessable Entity Validation error
429 Too Many Requests Rate limit exceeded
500 Internal Server Error Server error
503 Service Unavailable Service temporarily unavailable

Error Types

Error Type Description
authentication_error Authentication failed
authorization_error Insufficient permissions
validation_error Invalid request data
not_found_error Resource not found
rate_limit_error Rate limit exceeded
quota_error Account quota exceeded
payment_error Payment processing error
server_error Internal server error

Common Error Codes

Code Description
ERR_AUTH_INVALID_TOKEN Invalid or expired token
ERR_AUTH_MISSING_TOKEN No authentication token provided
ERR_PERMISSION_DENIED User lacks required permission
ERR_RESOURCE_NOT_FOUND Requested resource not found
ERR_VALIDATION Request validation failed
ERR_DUPLICATE_RESOURCE Resource already exists
ERR_RATE_LIMIT Too many requests
ERR_QUOTA_EXCEEDED Account quota exceeded
ERR_PAYMENT_REQUIRED Payment required for this action
ERR_SERVER_ERROR Internal server error

Handling Errors

JavaScript Example:

try {
  const response = await fetch('https://api.nudgecampaign.com/v2/campaigns', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(campaignData)
  });

  if (!response.ok) {
    const error = await response.json();
    
    switch (error.error.type) {
      case 'validation_error':
        // Handle validation errors
        console.error('Validation failed:', error.error.details);
        break;
      case 'rate_limit_error':
        // Handle rate limiting
        const retryAfter = response.headers.get('X-RateLimit-Reset');
        console.log(`Rate limited. Retry after: ${retryAfter}`);
        break;
      default:
        console.error('API Error:', error.error.message);
    }
  }
} catch (err) {
  console.error('Network error:', err);
}

Rate Limiting

API rate limits ensure fair usage and system stability.

Rate Limit Headers

HTTP/1.1 200 OK
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1640995200
X-RateLimit-Reset-After: 3600

Rate Limit Tiers

Plan Requests/Hour Burst Limit Concurrent Requests
Free 100 10/second 2
Starter 1,000 50/second 5
Pro 10,000 100/second 10
Enterprise Custom Custom Custom

Rate Limit Response

When rate limited, the API returns:

HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 3600

{
  "error": {
    "type": "rate_limit_error",
    "message": "Rate limit exceeded. Please retry after 3600 seconds",
    "code": "ERR_RATE_LIMIT",
    "retry_after": 3600
  }
}

Best Practices

  1. Implement exponential backoff for retries
  2. Cache responses when possible
  3. Use webhooks instead of polling
  4. Batch operations to reduce API calls
  5. Monitor rate limit headers proactively

Exponential Backoff Example:

async function apiCallWithRetry(url, options, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const response = await fetch(url, options);
      
      if (response.status === 429) {
        const retryAfter = parseInt(response.headers.get('Retry-After')) || Math.pow(2, i);
        await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
        continue;
      }
      
      return response;
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      await new Promise(resolve => setTimeout(resolve, Math.pow(2, i) * 1000));
    }
  }
}

SDK Usage

NudgeCampaign provides official SDKs for popular programming languages.

JavaScript/TypeScript SDK

Installation:

npm install @nudgecampaign/sdk

Usage:

import { NudgeCampaign } from '@nudgecampaign/sdk';

const client = new NudgeCampaign({
  apiKey: 'sk_live_your_api_key',
  // or use token authentication
  // token: 'your_jwt_token'
});

// List campaigns
const campaigns = await client.campaigns.list({
  filter: { status: 'sent' },
  sort: '-created_at',
  page: { size: 20 }
});

// Create campaign
const campaign = await client.campaigns.create({
  name: 'Summer Newsletter',
  subject: 'Hot Summer Deals!',
  html_content: '<html>...</html>',
  recipient_list_id: 'lst_abc123'
});

// Send campaign
await client.campaigns.send(campaign.id, {
  scheduled_at: new Date('2024-07-01T10:00:00Z')
});

// Handle errors
try {
  await client.contacts.create({
    email: 'invalid-email'
  });
} catch (error) {
  if (error.type === 'validation_error') {
    console.error('Validation failed:', error.details);
  }
}

Python SDK

Installation:

pip install nudgecampaign

Usage:

from nudgecampaign import Client
from nudgecampaign.exceptions import ValidationError

client = Client(api_key='sk_live_your_api_key')

# List campaigns
campaigns = client.campaigns.list(
    filter={'status': 'sent'},
    sort='-created_at',
    page_size=20
)

# Create contact
try:
    contact = client.contacts.create(
        email='user@example.com',
        first_name='John',
        last_name='Doe',
        tags=['customer', 'vip']
    )
except ValidationError as e:
    print(f"Validation error: {e.details}")

# Set up webhook
webhook = client.webhooks.create(
    url='https://your-app.com/webhook',
    events=['email.opened', 'email.clicked']
)

PHP SDK

Installation:

composer require nudgecampaign/nudgecampaign-php

Usage:

use NudgeCampaign\Client;
use NudgeCampaign\Exception\ValidationException;

$client = new Client('sk_live_your_api_key');

// List contacts
$contacts = $client->contacts->list([
    'filter' => ['status' => 'subscribed'],
    'page' => ['size' => 50]
]);

// Create campaign
$campaign = $client->campaigns->create([
    'name' => 'Newsletter',
    'subject' => 'Monthly Update',
    'html_content' => '<html>...</html>'
]);

// Handle errors
try {
    $client->contacts->create([
        'email' => 'invalid'
    ]);
} catch (ValidationException $e) {
    echo "Error: " . $e->getMessage();
    foreach ($e->getDetails() as $detail) {
        echo $detail['field'] . ': ' . $detail['message'];
    }
}

Ruby SDK

Installation:

gem install nudgecampaign

Usage:

require 'nudgecampaign'

client = NudgeCampaign::Client.new(api_key: 'sk_live_your_api_key')

# List campaigns
campaigns = client.campaigns.list(
  filter: { status: 'sent' },
  sort: '-created_at'
)

# Create contact
contact = client.contacts.create(
  email: 'user@example.com',
  first_name: 'Jane',
  tags: ['lead']
)

# Error handling
begin
  client.campaigns.send(campaign_id)
rescue NudgeCampaign::RateLimitError => e
  sleep(e.retry_after)
  retry
rescue NudgeCampaign::Error => e
  puts "Error: #{e.message}"
end

Go SDK

Installation:

go get github.com/nudgecampaign/nudgecampaign-go

Usage:

package main

import (
    "github.com/nudgecampaign/nudgecampaign-go"
    "log"
)

func main() {
    client := nudgecampaign.NewClient("sk_live_your_api_key")
    
    // List campaigns
    campaigns, err := client.Campaigns.List(&nudgecampaign.ListOptions{
        Filter: map[string]string{"status": "sent"},
        Sort: "-created_at",
    })
    if err != nil {
        log.Fatal(err)
    }
    
    // Create contact
    contact, err := client.Contacts.Create(&nudgecampaign.Contact{
        Email: "user@example.com",
        FirstName: "John",
        Tags: []string{"customer"},
    })
    if err != nil {
        if validationErr, ok := err.(*nudgecampaign.ValidationError); ok {
            log.Printf("Validation error: %v", validationErr.Details)
        }
    }
}

OpenAPI Specification

The complete OpenAPI 3.0 specification is available for generating client libraries and API documentation.

Download OpenAPI Spec

GET /v2/openapi.json
GET /v2/openapi.yaml

OpenAPI Example (Partial)

openapi: 3.0.0
info:
  title: NudgeCampaign API
  version: 2.0.0
  description: Email marketing platform API with AI-powered features
  contact:
    name: API Support
    email: api@nudgecampaign.com
    url: https://docs.nudgecampaign.com
  
servers:
  - url: https://api.nudgecampaign.com/v2
    description: Production server
  - url: https://api-staging.nudgecampaign.com/v2
    description: Staging server

security:
  - BearerAuth: []
  - ApiKeyAuth: []

paths:
  /campaigns:
    get:
      summary: List campaigns
      operationId: listCampaigns
      tags:
        - Campaigns
      parameters:
        - name: filter[status]
          in: query
          schema:
            type: string
            enum: [draft, scheduled, sending, sent, cancelled]
        - name: sort
          in: query
          schema:
            type: string
        - name: page[size]
          in: query
          schema:
            type: integer
            maximum: 100
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CampaignList'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '429':
          $ref: '#/components/responses/RateLimited'

components:
  schemas:
    Campaign:
      type: object
      required:
        - name
        - subject
        - html_content
      properties:
        id:
          type: string
          readOnly: true
        name:
          type: string
          maxLength: 255
        subject:
          type: string
          maxLength: 255
        html_content:
          type: string
        status:
          type: string
          enum: [draft, scheduled, sending, sent, cancelled]
          readOnly: true
        
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-Key

Code Generation

Generate client libraries using OpenAPI Generator:

# JavaScript
openapi-generator-cli generate \
  -i https://api.nudgecampaign.com/v2/openapi.json \
  -g javascript \
  -o ./nudgecampaign-js-client

# Python
openapi-generator-cli generate \
  -i https://api.nudgecampaign.com/v2/openapi.json \
  -g python \
  -o ./nudgecampaign-python-client

# Java
openapi-generator-cli generate \
  -i https://api.nudgecampaign.com/v2/openapi.json \
  -g java \
  -o ./nudgecampaign-java-client

API Changelog

Version 2.0 (Current)

  • Added Maya AI endpoints
  • Improved automation workflows
  • Enhanced analytics with revenue tracking
  • Added webhook management endpoints
  • Implemented cursor-based pagination

Version 1.0 (Deprecated)

  • Initial API release
  • Basic CRUD operations
  • Simple authentication
  • Offset-based pagination

Support and Resources

Documentation

Support Channels

API Status

Conclusion

The NudgeCampaign API provides comprehensive access to all platform features with a focus on developer experience, security, and scalability. With official SDKs, detailed documentation, and robust error handling, integrating NudgeCampaign into your applications is straightforward and reliable.

For additional support or feature requests, please contact our API team at api@nudgecampaign.com.