> ## Documentation Index
> Fetch the complete documentation index at: https://docs.nudj.cx/llms.txt
> Use this file to discover all available pages before exploring further.

# Admin API Overview

> Complete platform control for community management, gamification configuration, and user engagement

## Overview

The Admin API is your command center for the Nudj platform, providing comprehensive control over every aspect of your gamified community. It enables you to build, customize, and manage engaging experiences at scale.

## Base URL

```bash theme={null}
https://{subdomain}.nudj.cx/api/v2/admin
```

> [!NOTE]
>
> Replace `{subdomain}` with your organization's subdomain (e.g., `acme-corp.nudj.cx`).

## Authentication

```bash theme={null}
Authorization: Bearer YOUR_ADMIN_TOKEN
```

> [!WARNING]
>
> Admin tokens grant extensive platform control. Only trusted administrators should have access. Tokens are scoped to specific organizations and roles.

## Core Capabilities

> **Community Builder**
>
> Design branded spaces with custom themes, domains, and content

> **Gamification Engine**
>
> Configure challenges, achievements, leaderboards, and progression systems

> **Reward Manager**
>
> Distribute prizes, manage giveaways, and track redemptions

> **User Administrator**
>
> Manage members, teams, roles, and permissions at scale

> **Content Controller**
>
> Create posts, moderate content, and manage community interactions

> **Platform Configurator**
>
> Set feature flags, integrations, variables, and system settings

## Platform Management Areas

## 🏗️ Community Building

Build and customize engaging community spaces with full control over branding, structure, and member experience.

> **Communities**
>
> **Complete community lifecycle management**
>
> * Create multi-tenant branded spaces
> * Configure onboarding flows and requirements
> * Set member permissions and access controls
> * Customize navigation and layout
> * Manage community-wide settings and features
>
> ```typescript theme={null}
> // Create a new community
> await admin.communities.create({
>   name: "Developer Hub",
>   subdomain: "devs",
>   theme: { primaryColor: "#7C3AED" },
>   features: ["challenges", "rewards", "leaderboards"]
> })
> ```

> **Themes & Branding**
>
> **Visual customization engine**
>
> * Custom color schemes and typography
> * Logo and asset management
> * Light/dark mode configurations
> * Component styling overrides
> * Custom CSS injection
>
> Key endpoints:
>
> * `GET/PATCH /themes` - Theme configuration
> * `POST /domains` - Custom domain setup

> **Templates Library**
>
> **Rapid deployment with pre-built templates**
>
> * Community templates for different industries
> * Challenge bundles for common use cases
> * Achievement sets for various goals
> * Reward catalogs by category
> * Action libraries for engagement
>
> ```typescript theme={null}
> // Deploy from template
> await admin.templates.createEntity({
>   templateId: "fitness-community",
>   customizations: { name: "FitClub 2024" }
> })
> ```

## 🎮 Gamification System

Design sophisticated engagement mechanics with challenges, achievements, and progression systems.

> **Challenges & Actions**
>
> **Multi-step quest builder**
>
> * Sequential and parallel action paths
> * Multiple action types available
> * Prerequisites and unlocking logic
> * Time-based challenges
> * Group challenges for team competition
>
> **Action Types Available:**
>
> * Social media integrations
> * Content creation (posts, comments)
> * External link actions
> * Custom actions
>
> ```typescript theme={null}
> // Create multi-action challenge
> const challenge = await admin.challenges.create({
>   title: "Social Media Master",
>   actions: [
>     { type: "twitter_follow", target: "@nudj" },
>     { type: "instagram_post", hashtag: "#NudjCommunity" },
>     { type: "youtube_watch", videoId: "abc123", duration: 300 }
>   ],
>   rewards: { points: 500, xp: 100 }
> })
> ```

> **Achievements System**
>
> **Milestone and badge configuration**
>
> * Progress-based achievements
> * Hidden/secret achievements
> * Tiered achievement chains
> * Custom unlock criteria
> * Visual badge designer
>
> **Criteria Types:**
>
> * Action completions
> * Point thresholds
> * Streak maintenance
> * Community contributions
> * Time-based milestones

> **Leaderboards**
>
> **Competitive dynamics engine**
>
> * Global, regional, and group leaderboards
> * Multiple ranking metrics (points, XP, achievements)
> * Time-scoped competitions (daily, weekly, seasonal)
> * Prize distribution automation
> * Real-time position tracking
>
> ```typescript theme={null}
> // Configure weekly leaderboard with rewards
> await admin.leaderboards.create({
>   type: "weekly",
>   metric: "points",
>   rewards: [
>     { rank: 1, prize: "premium_membership" },
>     { rank: [2, 5], prize: "bonus_points", amount: 1000 },
>     { rank: [6, 10], prize: "badge" }
>   ]
> })
> ```

> **Game Configurations**
>
> **Advanced gamification mechanics**
>
> * Spin wheels and slot machines
> * Daily check-in bonuses
> * Loot boxes and mystery rewards
> * Mini-games and instant wins
> * Probability-based rewards
>
> Key endpoints:
>
> * `POST /game-configs` - Create game
> * `PATCH /game-configs/{id}` - Update mechanics

## 🎁 Rewards & Incentives

Comprehensive reward management from creation to fulfillment, supporting physical, digital, and experiential prizes.

> **Reward Catalog**
>
> **Multi-type reward system**
>
> * **Digital**: Codes, vouchers, subscriptions
> * **Physical**: Merchandise, products, gift cards
> * **Experiential**: Event tickets, meetups
> * **Virtual**: Points, badges, titles
>
> **Inventory Management:**
>
> * Stock tracking and alerts
> * Automatic reordering
> * Expiration handling
> * Regional availability

> **Distribution Methods**
>
> **Flexible reward allocation**
>
> * **Direct**: Manual distribution to users
> * **Earned**: Automatic on achievement
> * **Purchased**: Points marketplace
> * **Giveaway**: Random selection
> * **Leaderboard**: Rank-based distribution
> * **Milestone**: Progress rewards
>
> ```typescript theme={null}
> // Process giveaway
> await admin.rewards.processGiveaway({
>   rewardId: "prize_123",
>   selectionMethod: "random",
>   numberOfWinners: 10,
>   eligibilityCriteria: {
>     minPoints: 100,
>     completedChallenges: ["onboarding"]
>   }
> })
> ```

> **Redemption Management**
>
> **End-to-end fulfillment**
>
> * Redemption workflows
> * Shipping integration
> * Digital delivery automation
> * Tax documentation support
> * Customer support tools

## 👥 User & Team Management

Complete member lifecycle management with sophisticated role-based access control and team collaboration features.

> **User Administration**
>
> **Comprehensive member management**
>
> * Bulk import/export
> * Custom profile fields
> * Role assignment
> * Activity monitoring
> * Points/XP adjustments
> * Account suspension/deletion
>
> ```typescript theme={null}
> // Bulk user operations
> await admin.users.bulkImport({
>   users: csvData,
>   sendWelcomeEmail: true,
>   assignToGroups: ["new_members"],
>   initialPoints: 100
> })
> ```

> **Teams & Organizations**
>
> **Multi-level hierarchy**
>
> * Organization structure
> * Department/team creation
> * Role-based permissions
> * Invitation management
> * Access control lists
> * Cross-team competitions

> **Points & Transactions**
>
> **Currency management system**
>
> * Manual point adjustments
> * Transaction history
> * Balance corrections
> * Refunds and reversals
> * Currency conversion
> * Audit trails

## ⚙️ Platform Configuration

System-wide settings and integrations for complete platform customization.

> **Authentication Setup**
>
> **Identity provider configuration**
>
> * SSO/SAML setup
> * OAuth providers
> * Magic link authentication
> * MFA requirements
> * Session management
> * Password policies

> **Integrations Hub**
>
> **Third-party connections**
>
> * Social media platforms
> * Analytics services
> * Communication tools
> * Custom webhook integrations
>
> ```typescript theme={null}
> // Configure integration
> await admin.thirdPartyConfig.update({
>   twitter: {
>     apiKey: process.env.TWITTER_KEY,
>     apiSecret: process.env.TWITTER_SECRET,
>     webhookUrl: "https://api.nudj.cx/webhooks/twitter"
>   }
> })
> ```

> **Variables System**
>
> **Dynamic configuration**
>
> * Environment-specific settings
> * A/B testing parameters
> * Feature toggles
> * Rate limits
> * Threshold values
> * System constants

> **Webhooks & Events**
>
> **Real-time event streaming**
>
> * Custom event subscriptions
> * Payload customization
> * Retry policies
> * Event filtering
> * Webhook security
> * Audit logging

## API Resource Groups

**Core Resources**

| Resource | Operations | Purpose |
| - | - | - |
| **Communities** | CRUD | Community spaces management |
| **Users** | CRUD + Bulk | Member administration |
| **Challenges** | CRUD + Distribution | Quest configuration |
| **Actions** | CRUD + Reorder | Activity building blocks |
| **Achievements** | CRUD + Distribution | Milestone system |
| **Rewards** | CRUD + Giveaway | Prize management |
| **Posts** | CRUD | Content management |
| **Teams** | CRD + Invite | Organization structure |

**Gamification**

| Resource | Operations | Purpose |
| - | - | - |
| **Leaderboards** | CRUD + Distribution | Competition configuration |
| **Game Configs** | CRUD | Mini-game mechanics |
| **Streaks** | CRU | Consistency tracking |
| **Action Participations** | R | Activity monitoring |
| **Challenge Groups** | CRUD | Challenge organization |
| **Variables** | CRUD + Values | Dynamic parameters |

**Configuration**

| Resource | Operations | Purpose |
| - | - | - |
| **Auth Config** | RU | Authentication setup |
| **Feature Flags** | RU | Feature toggles |
| **Themes** | RU | Visual customization |
| **Third Party Config** | RU | Integration settings |
| **Legal Policies** | RU | Terms and privacy |
| **Domains** | CR | Custom domains |
| **Languages** | CR | Localization |
| **Webhooks** | RU | Event subscriptions |

**Templates**

| Resource | Operations | Purpose |
| - | - | - |
| **Community Templates** | R + Create | Pre-built communities |
| **Challenge Templates** | R + Create | Challenge bundles |
| **Achievement Templates** | R + Create | Achievement sets |
| **Action Templates** | R + Create | Action libraries |
| **Reward Templates** | R + Create | Prize catalogs |
| **Post Templates** | R + Create | Content templates |

## Quick Start Examples

```typescript TypeScript theme={null}
import { createAdminClient } from '@nudj-digital/api/admin';

const admin = createAdminClient({
  baseUrl: 'https://acme-corp.nudj.cx/api/v2/admin',
  headers: {
    'Authorization': `Bearer ${process.env.NUDJ_ADMIN_TOKEN}`
  }
});

// Create complete challenge with rewards
const challenge = await admin.challenges.create({
  title: "Welcome Week Challenge",
  description: "Complete these actions to earn rewards!",
  startDate: new Date(),
  endDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
  actions: [
    { type: "profile_complete", points: 50 },
    { type: "first_post", points: 100 },
    { type: "invite_friend", points: 150 }
  ],
  rewards: {
    completion: { points: 500, badge: "early_adopter" },
    leaderboard: [
      { position: 1, reward: "premium_month" },
      { position: [2, 10], reward: "bonus_points", amount: 1000 }
    ]
  }
});

// Process reward giveaway
const winners = await admin.rewards.processGiveaway({
  rewardId: "reward_abc123",
  numberOfWinners: 5,
  eligibility: {
    minEngagementScore: 80,
    requiredChallenges: ["onboarding"]
  }
});
```

```javascript JavaScript theme={null}
const response = await fetch('https://acme-corp.nudj.cx/api/v2/admin/challenges', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_ADMIN_TOKEN',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: "Welcome Week Challenge",
    description: "Complete actions to earn rewards!",
    actions: [
      { type: "profile_complete", points: 50 }
    ]
  })
});

const challenge = await response.json();
```

```python Python theme={null}
import requests

# Create challenge
response = requests.post(
    'https://acme-corp.nudj.cx/api/v2/admin/challenges',
    headers={
        'Authorization': 'Bearer YOUR_ADMIN_TOKEN',
        'Content-Type': 'application/json'
    },
    json={
        'title': 'Welcome Week Challenge',
        'description': 'Complete actions to earn rewards!',
        'actions': [
            {'type': 'profile_complete', 'points': 50}
        ]
    }
)

challenge = response.json()
```

```bash cURL theme={null}
# Create a new challenge
curl -X POST https://acme-corp.nudj.cx/api/v2/admin/challenges \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Welcome Week Challenge",
    "description": "Complete actions to earn rewards!",
    "actions": [
      {"type": "profile_complete", "points": 50}
    ]
  }'
```

## Common Workflows

> **Launch a Community Campaign**
>
> 1. Create campaign structure with challenges
> 2. Configure rewards and distribution rules
> 3. Set up leaderboards and competitions
> 4. Enable relevant feature flags
> 5. Configure webhooks for tracking
> 6. Import or invite users
> 7. Monitor via analytics

> **Run a Giveaway**
>
> 1. Create reward with inventory
> 2. Define eligibility criteria
> 3. Set participation period
> 4. Process random selection
> 5. Notify winners
> 6. Handle fulfillment
> 7. Generate tax documents

> **Onboard Enterprise Client**
>
> 1. Create organization and community
> 2. Configure SSO authentication
> 3. Apply custom theme and domain
> 4. Set up team structure
> 5. Import users with roles
> 6. Deploy from templates
> 7. Configure integrations

> **Seasonal Event Management**
>
> 1. Create time-limited challenges
> 2. Configure special rewards
> 3. Set up event leaderboards
> 4. Enable event features
> 5. Schedule content
> 6. Automate distributions
> 7. Archive post-event

## Response Format

All Admin API responses follow a consistent structure:

```json theme={null}
{
  "data": {
    "id": "resource_123",
    "type": "challenge",
    "attributes": {
      "title": "Welcome Challenge",
      "status": "active",
      "startDate": "2024-01-15T00:00:00Z"
    },
    "relationships": {
      "actions": {
        "data": [
          { "id": "action_456", "type": "action" }
        ]
      }
    }
  },
  "meta": {
    "timestamp": "2024-01-15T10:30:00Z",
    "requestId": "req_abc123",
    "version": "2.0"
  }
}
```

## Error Handling

**Error Codes**

| Code | Description | Resolution |
| - | - | - |
| `INSUFFICIENT_PERMISSIONS` | Missing required role | Check admin permissions |
| `RESOURCE_LOCKED` | Concurrent modification | Retry with backoff |
| `VALIDATION_ERROR` | Invalid input data | Check request schema |
| `DEPENDENCY_ERROR` | Related resource issue | Resolve dependencies |
| `QUOTA_EXCEEDED` | Limit reached | Upgrade plan or wait |
| `INTEGRITY_ERROR` | Data consistency issue | Contact support |

**Error Response**

```json theme={null}
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid challenge configuration",
    "details": [
      {
        "field": "endDate",
        "issue": "Must be after startDate"
      }
    ],
    "requestId": "req_xyz789",
    "documentation": "https://docs.nudj.cx/errors/VALIDATION_ERROR"
  }
}
```

**Best Practices**

* Implement exponential backoff for retries
* Log error request IDs for support
* Validate input before API calls
* Handle rate limits gracefully
* Use idempotency keys for critical operations
* Monitor error rates and patterns

## Rate Limits & Performance

> [!WARNING]
>
> Admin operations can affect many users. Rate limits are enforced to maintain platform stability.

**Rate Limits**

Rate limits are enforced on all Admin API endpoints. Check response headers for current limits:

* `X-RateLimit-Remaining`
* `X-RateLimit-Reset`
* `Retry-After`

**Optimization Tips**

**Batch Operations**

* Use bulk endpoints when available
* Group related updates in single requests
* Leverage transactions for consistency

**Caching Strategy**

* Cache configuration data locally
* Use ETags for conditional requests
* Subscribe to webhooks for updates

**Async Processing**

* Use job queues for heavy operations
* Implement webhooks for completion
* Poll status endpoints for progress

**Pagination**

```typescript theme={null}
// Paginate through large datasets
let hasMore = true;
let skip = 0;
const limit = 100;
const allUsers = [];

while (hasMore) {
  const response = await admin.users.list({
    params: { limit, skip }
  });
  
  allUsers.push(...response.data);
  hasMore = response.meta.hasMore;
  skip += limit;
}
```

## Security & Compliance

**Access Control**

**Role-Based Permissions**

| Role | Capabilities |
| - | - |
| `super_admin` | Full platform control |
| `admin` | Community management |
| `moderator` | Content and users |
| `analyst` | Read-only access |
| `support` | User assistance |

**Security Requirements**

* Strong authentication required for admin accounts
* API tokens should be kept secure and rotated regularly

**Audit Logging**

All admin operations are logged:

```json theme={null}
{
  "event": "resource.updated",
  "actor": {
    "id": "user_123",
    "role": "admin",
    "ip": "192.168.1.1"
  },
  "resource": {
    "type": "challenge",
    "id": "challenge_456"
  },
  "changes": {
    "status": ["draft", "active"]
  },
  "timestamp": "2024-01-15T10:30:00Z"
}
```

**Data Protection**

**PII Handling**

* Encryption in transit and at rest
* Access controls for sensitive data

**Compliance**

* GDPR data portability
* Right to erasure support

## Migration & Deployment

> **Staging to Production**
>
> ```typescript theme={null}
> // Export from staging
> const config = await staging.admin.export({
>   include: ['challenges', 'rewards', 'achievements'],
>   excludePII: true
> });
>
> // Import to production
> await production.admin.import({
>   data: config,
>   mode: 'merge', // or 'replace'
>   dryRun: true   // Test first
> });
> ```

## Advanced Features

> **Bulk Operations**
>
> Process multiple records efficiently with batch endpoints

> **Webhook Support**
>
> Real-time event notifications for system changes

## Support & Resources

> **[API Reference](https://docs.nudj.cx/api-reference/admin/get-communities.md)**
>
> Detailed endpoint documentation

> **[SDKs & Libraries](https://github.com/nudj-digital/sdks)**
>
> Official client libraries

> **[Status Page](https://status.nudj.cx)**
>
> Service health monitoring

> **[Developer Forum](https://community.nudj.cx/developers)**
>
> Community support

> **[Enterprise Support](https://support.nudj.cx)**
>
> Priority assistance

> **[Changelog](https://changelog.nudj.cx)**
>
> Latest updates


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.