# HyPeMa - API Reference
> Complete reference for the HyPeMa REST API with all endpoints, parameters, and examples.

---

## Table of Contents

- [Introduction](#introduction)
  - [Base URL](#base-url)
  - [Authentication](#authentication)
  - [Response Envelope](#response-envelope)
  - [Rate Limiting](#rate-limiting)
  - [Errors](#errors)
  - [SSE Streaming](#sse-streaming)
  - [Quickstart — end-to-end flow](#quickstart--end-to-end-flow)
- [AI Operations](#ai-operations)
  - [POST /ai/research-company](#post-airesearch-company)
  - [POST /ai/generate-leads](#post-aigenerate-leads)
- [Email Operations](#email-operations)
  - [POST /emails/generate](#post-emailsgenerate)
  - [POST /emails/generate-preview](#post-emailsgenerate-preview)
  - [POST /emails/generate-batch](#post-emailsgenerate-batch)
  - [GET /emails/:id](#get-emailsid)
  - [POST /emails/drafts/payload](#post-emailsdraftspayload)
- [Leads](#leads)
  - [GET /leads](#get-leads)
  - [POST /leads](#post-leads)
  - [GET /leads/:id](#get-leadsid)
  - [PATCH /leads/:id](#patch-leadsid)
  - [DELETE /leads/:id](#delete-leadsid)
- [Lead Groups](#lead-groups)
  - [GET /lead-groups](#get-lead-groups)
  - [POST /lead-groups](#post-lead-groups)
  - [GET /lead-groups/:id/leads](#get-lead-groupsidleads)
- [Campaigns](#campaigns)
  - [GET /campaigns](#get-campaigns)
  - [GET /campaigns/:id](#get-campaignsid)
  - [GET /campaigns/:id/stats](#get-campaignsidstats)
  - [GET /campaigns/:id/emails](#get-campaignsidemails)
- [Usage](#usage)
  - [GET /usage](#get-usage)

---

## Introduction

Complete reference for the HyPeMa REST API. All endpoints are versioned under `/v1` and return JSON responses.

### Base URL

```
https://hypema.app/api/v1
```

### Authentication

All requests require an API key in the Authorization header:

```
Authorization: Bearer hpm_live_your_key_here
```

Create API keys in **Settings -> API Keys**.

### Response Envelope

Every response follows this structure:

```json
{
  "data": { ... },
  "error": null,
  "meta": {
    "requestId": "req_abc123",
    "tokensConsumed": 30
  }
}
```

AI-powered endpoints return the actual HyPeMa tokens consumed in `tokensConsumed`. Non-AI endpoints return 0. The `GET /usage` endpoint additionally returns `tokensRemaining`.

### Rate Limiting

Complexity-based rate limiting. Each endpoint has a cost weight:

| Type | Weight | Examples |
|------|--------|----------|
| Read | 1 | GET /leads, GET /usage |
| Write | 2 | POST /leads, PATCH /leads/:id |
| AI (single) | 5 | POST /emails/generate |
| AI (heavy) | 10-15 | POST /ai/research-company, POST /emails/generate-batch |

**Response headers:** `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`, `X-RateLimit-Cost`

**Free tier:** 100 points/min. **Pro tier:** 500 points/min.

### Errors

| Status | Code | Description |
|--------|------|-------------|
| 400 | `VALIDATION_ERROR` | Invalid request body or parameters |
| 401 | `UNAUTHORIZED` | Missing or invalid API key |
| 403 | `TOKEN_LIMIT_EXCEEDED` | Out of HyPeMa tokens |
| 404 | `NOT_FOUND` | Resource not found |
| 429 | `RATE_LIMITED` | Rate limit exceeded |
| 500 | `INTERNAL_ERROR` | Server error |

### SSE Streaming

Long-running AI endpoints (`/ai/research-company`, `/ai/generate-leads`, `/emails/generate-batch`) support Server-Sent Events so you can stream progress to users instead of polling. Set `Accept: text/event-stream` on the request.

Events you'll receive:

- `status` — human progress message (e.g. "Searching company website…")
- `thinking` — incremental reasoning chunks (when higher Thinking Depth is active)
- `result` — the final JSON payload, same shape as the non-SSE response

```javascript
// Node / browser — fetch + stream parser
const res = await fetch('https://hypema.app/api/v1/ai/research-company', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer hpm_live_your_key_here',
    'Content-Type': 'application/json',
    'Accept': 'text/event-stream',
  },
  body: JSON.stringify({ url: 'https://stripe.com' }),
});

const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = '';

while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  buffer += decoder.decode(value, { stream: true });

  // Each event is separated by a blank line. Each block has "event: X" and "data: {...}".
  const events = buffer.split('\n\n');
  buffer = events.pop() ?? '';

  for (const block of events) {
    const eventLine = block.match(/^event: (.+)$/m)?.[1];
    const dataLine  = block.match(/^data: (.+)$/m)?.[1];
    if (!dataLine) continue;
    const payload = JSON.parse(dataLine);

    if (eventLine === 'status')   console.log('[status]', payload.message);
    if (eventLine === 'thinking') process.stdout.write(payload.delta);
    if (eventLine === 'result')   console.log('[done]', payload);
  }
}
```

If you don't need live progress, omit the `Accept: text/event-stream` header and the endpoint returns a single JSON response when complete.

### Quickstart — end-to-end flow

A full HyPeMa campaign in six cURL calls: research a company, find leads, preview emails, iterate with feedback, batch-generate for the whole group, and build a send-ready Gmail payload. Each step uses the output of the one before.

```bash
# 0. Set your key
export HPM_KEY="hpm_live_your_key_here"

# 1. Research a company
curl -X POST https://hypema.app/api/v1/ai/research-company \
  -H "Authorization: Bearer $HPM_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://stripe.com"}'

# 2. Find 5 leads matching given criteria (returns leadGroupId)
curl -X POST https://hypema.app/api/v1/ai/generate-leads \
  -H "Authorization: Bearer $HPM_KEY" \
  -H "Content-Type: application/json" \
  -d '{"industry": "your target industry", "roleTitle": "decision-maker role", "region": "Berlin", "count": 5}'

# 3. Preview 3 sample emails (no tokens committed to batch yet)
curl -X POST https://hypema.app/api/v1/emails/generate-preview \
  -H "Authorization: Bearer $HPM_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "leadGroupId": "GROUP_UUID",
    "topicGoalText": "Introducing our AI payments infra; want a 10-min exploratory call",
    "sampleCount": 3,
    "secretSauceVariant": "positive_reply_rate",
    "effort": "medium"
  }'

# 4. Batch-generate for every lead in the group
curl -X POST https://hypema.app/api/v1/emails/generate-batch \
  -H "Authorization: Bearer $HPM_KEY" \
  -H "Content-Type: application/json" \
  -d '{"leadGroupId": "GROUP_UUID", "topicGoalText": "...", "secretSauceVariant": "positive_reply_rate"}'

# 5. Build a send-ready payload for one generated email
curl -X POST https://hypema.app/api/v1/emails/drafts/payload \
  -H "Authorization: Bearer $HPM_KEY" \
  -H "Content-Type: application/json" \
  -d '{"leadId": "LEAD_UUID", "generatedEmailId": "EMAIL_UUID"}'

# 6. Check campaign reply rate after sending
curl https://hypema.app/api/v1/campaigns/CAMPAIGN_UUID/stats \
  -H "Authorization: Bearer $HPM_KEY"
```

Hand the payload from step 5 to Gmail's API, SMTP, or any email-send tool — HyPeMa doesn't send on your behalf. Campaigns are auto-created at step 4 and appear in your Workspace.

---

## AI Operations

### POST /ai/research-company

**Research a company by website URL**

Analyzes a company website using AI-powered web search. Returns structured data about the company name, industry, products, leadership, and customer profile. Supports SSE streaming for real-time status updates. Cost varies by thinking depth.

- **Timing:** 30s-5min
- **Cost:** 5-15 tokens (varies by thinking depth)
- **Supports SSE streaming**

#### Request Body

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `url` | string | Yes | The company website URL to research. Example: `"https://example.com"` |
| `effort` | `"max"`\|`"xhigh"`\|`"high"`\|`"medium"`\|`"low"` | No | AI thinking depth override. If omitted, uses Company Research default from Settings. |

#### Response

```json
{
  "data": {
    "companyName": "ExampleCo",
    "description": "A leading SaaS company...",
    "industry": "Technology",
    "productName": "ExampleProduct",
    "valueProposition": "Helps teams collaborate...",
    "targetAudience": "Enterprise companies...",
    "ceoName": "Jane Smith",
    "ceoRole": "CEO & Co-founder"
  },
  "error": null,
  "meta": {
    "requestId": "req_abc123",
    "tokensConsumed": 8
  }
}
```

#### cURL Example

```bash
curl -X POST https://hypema.app/api/v1/ai/research-company \
  -H "Authorization: Bearer hpm_live_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://example.com"}'
```

---

### POST /ai/generate-leads

**Find real leads using AI web search**

Uses AI-powered web search to discover real, verified leads matching your criteria. Creates a new lead group and saves all found leads to your database. Supports SSE streaming. Cost varies by thinking depth.

- **Timing:** 30s-5min
- **Cost:** 10-30 tokens (varies by thinking depth)
- **Supports SSE streaming**

#### Request Body

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `industry` | string | Yes | Target industry. Example: `"accounting"` |
| `roleTitle` | string | No | Job role to target. Example: `"Managing Partner"` |
| `region` | string | No | Geographic region. Example: `"Munich, Germany"` |
| `count` | integer | No | Number of leads to find. Default 5, max 50. Example: `5` |
| `companySize` | string | No | Company size filter. Example: `"10-50 employees"` |
| `excludeGroupIds` | string[] | No | Lead group IDs to exclude duplicates from. |
| `effort` | `"max"`\|`"xhigh"`\|`"high"`\|`"medium"`\|`"low"` | No | AI thinking depth override. If omitted, uses Lead Generation default from Settings. |

#### Response

```json
{
  "data": {
    "leads": [
      {
        "id": "...",
        "email": "jane@example.com",
        "firstName": "Jane",
        "lastName": "Smith",
        "company": "ExampleCo",
        "roleTitle": "CTO",
        "country": "Germany"
      }
    ],
    "count": 3,
    "leadGroupId": "uuid-here"
  },
  "error": null,
  "meta": {
    "requestId": "req_def456",
    "tokensConsumed": 15
  }
}
```

#### cURL Example

```bash
curl -X POST https://hypema.app/api/v1/ai/generate-leads \
  -H "Authorization: Bearer hpm_live_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{"industry": "accounting", "region": "Munich, Germany", "count": 5}'
```

---

## Email Operations

### POST /emails/generate

**Generate a personalized email for a lead**

Uses AI to generate a hyper-personalized cold email for a specific lead. The email is saved to the database and the lead status is updated to 'generated'. Requires topicGoalText describing what you're selling/pitching. Optionally specify a Secret Sauce mode. Cost varies by Secret Sauce mode and thinking depth.

- **Timing:** 10-30s
- **Cost:** ~2 tokens (default), ~6 tokens (reply\_rate), ~10 tokens (positive\_reply\_rate) -- varies by thinking depth

#### Request Body

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `leadId` | string (uuid) | Yes | The lead to generate an email for. |
| `topicGoalText` | string | Yes | Describe your product/pitch/goal. Min 10 chars. Example: `"Introducing our AI accounting software that automates bookkeeping"` |
| `feedbackHistory` | string[] | No | Previous feedback to refine the email style. |
| `secretSauceVariant` | string | No | Secret Sauce mode: `"reply_rate"`, `"positive_reply_rate"`, or `"none"` (default). Overrides tenant-level setting for this email. |
| `effort` | `"max"`\|`"xhigh"`\|`"high"`\|`"medium"`\|`"low"` | No | AI thinking depth override. If omitted, uses Email default from Settings. |

#### Response

```json
{
  "data": {
    "id": "email-uuid",
    "subject": "Quick question about your bookkeeping",
    "body": "Hi Jane,\n\nI noticed ExampleCo has been growing...",
    "unsubscribeUrl": "https://hypema.app/u/token123",
    "campaignId": "campaign-uuid"
  },
  "error": null,
  "meta": {
    "requestId": "req_ghi789",
    "tokensConsumed": 3
  }
}
```

#### cURL Example

```bash
curl -X POST https://hypema.app/api/v1/emails/generate \
  -H "Authorization: Bearer hpm_live_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{"leadId": "lead-uuid-here", "topicGoalText": "Introducing our AI accounting software that automates bookkeeping"}'
```

---

### POST /emails/generate-preview

**Preview email drafts without saving**

Generates preview emails for leads in a group without saving them to the database. Use this to review email quality and iterate with feedback before committing to a full batch. Supports the same Secret Sauce modes as generate. Cost varies by Secret Sauce mode and thinking depth.

- **Timing:** 10-60s (depends on sample count)
- **Cost:** ~2 tokens/preview (default), ~6 tokens/preview (reply\_rate), ~10 tokens/preview (positive\_reply\_rate) -- varies by thinking depth

#### Request Body

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `leadGroupId` | string (uuid) | Yes | The lead group to preview emails for. |
| `topicGoalText` | string | No | Your pitch/goal text. Min 10 chars. |
| `feedbackHistory` | string[] | No | Feedback to refine the style (e.g. `["Make it shorter", "More casual tone"]`). Use for iterative improvement. |
| `sampleCount` | integer | No | Number of previews to generate (1-10). Default 3. |
| `leadIds` | string[] | No | Specific lead IDs to preview. If omitted, picks from the group. |
| `secretSauceVariant` | string | No | Secret Sauce mode: `"reply_rate"`, `"positive_reply_rate"`, or `"none"`. |
| `effort` | `"max"`\|`"xhigh"`\|`"high"`\|`"medium"`\|`"low"` | No | AI thinking depth override. If omitted, uses Email default from Settings. |

#### Response

```json
{
  "data": {
    "previews": [
      {
        "leadId": "lead-uuid",
        "lead": {
          "firstName": "Jane",
          "lastName": "Smith",
          "company": "ExampleCo",
          "email": "jane@example.com"
        },
        "subject": "Quick question about your bookkeeping",
        "body": "Hi Jane,\n\nI noticed ExampleCo has been growing..."
      }
    ],
    "count": 3
  },
  "error": null,
  "meta": {
    "requestId": "req_abc123",
    "tokensConsumed": 6
  }
}
```

#### Typical workflow

1. Call `generate-preview` with your lead group and topic
2. Review the previews
3. If needed, call again with `feedbackHistory` to refine (e.g. `["Shorter emails", "Mention their recent funding round"]`)
4. When satisfied, call `generate-batch` with the same parameters to generate and save all emails

#### cURL Example

```bash
curl -X POST https://hypema.app/api/v1/emails/generate-preview \
  -H "Authorization: Bearer hpm_live_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{"leadGroupId": "group-uuid-here", "topicGoalText": "Introducing our AI accounting software", "sampleCount": 3}'
```

---

### POST /emails/generate-batch

**Generate emails for multiple leads at once**

Generates personalized emails for all leads in a lead group. For groups with 10+ leads, this is more efficient than calling generateEmail individually. Each email is saved to the database. Optionally specify a Secret Sauce mode. Cost varies by Secret Sauce mode and thinking depth.

- **Timing:** 1-10min (depends on lead count)
- **Cost:** ~2 tokens/lead (default), ~6 tokens/lead (reply\_rate), ~10 tokens/lead (positive\_reply\_rate) -- varies by thinking depth

#### Request Body

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `leadGroupId` | string (uuid) | Yes | The lead group to generate emails for. |
| `topicGoalText` | string | No | Your pitch/goal text. Min 10 chars. |
| `feedbackHistory` | string[] | No | Style feedback. |
| `leadIds` | string[] | No | Specific lead IDs to generate for (subset of group). |
| `secretSauceVariant` | string | No | Secret Sauce mode: `"reply_rate"`, `"positive_reply_rate"`, or `"none"` (default). Applied to all emails in the batch. |
| `effort` | `"max"`\|`"xhigh"`\|`"high"`\|`"medium"`\|`"low"` | No | AI thinking depth override. If omitted, uses Email default from Settings. Applied to entire batch. |

#### Response

```json
{
  "data": {
    "results": [
      {
        "id": "email-uuid",
        "subject": "...",
        "body": "...",
        "unsubscribeUrl": "..."
      }
    ],
    "failedLeads": []
  },
  "error": null,
  "meta": {
    "requestId": "req_jkl012",
    "tokensConsumed": 25
  }
}
```

#### cURL Example

```bash
curl -X POST https://hypema.app/api/v1/emails/generate-batch \
  -H "Authorization: Bearer hpm_live_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{"leadGroupId": "group-uuid-here", "topicGoalText": "Introducing our AI accounting software"}'
```

---

### GET /emails/:id

**Retrieve a generated email by ID**

Fetches a previously generated email. Use this to review an email before building the draft payload for sending.

- **Timing:** < 1s
- **Cost:** Free

#### Path Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | string (uuid) | Yes | The generated email ID. |

#### Response

```json
{
  "data": {
    "id": "email-uuid",
    "leadId": "lead-uuid",
    "subject": "Quick question about your bookkeeping",
    "body": "Hi Jane,...",
    "unsubscribeUrl": "https://..."
  },
  "error": null,
  "meta": {
    "requestId": "req_mno345"
  }
}
```

#### cURL Example

```bash
curl https://hypema.app/api/v1/emails/email-uuid-here \
  -H "Authorization: Bearer hpm_live_your_key_here"
```

---

### POST /emails/drafts/payload

**Build a ready-to-send email payload**

Takes a lead ID and generated email ID, validates the email hasn't expired and the recipient isn't suppressed, marks the lead as 'drafted', and returns a payload with provider, recipient address, subject, and body -- everything you need to send via Gmail API, SMTP, or any email service.

- **Timing:** < 1s
- **Cost:** Free

#### Request Body

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `leadId` | string (uuid) | Yes | The lead this email is for. |
| `generatedEmailId` | string (uuid) | Yes | The generated email ID. |

#### Response

```json
{
  "data": {
    "provider": "gmail",
    "to": "jane@example.com",
    "subject": "Quick question about your bookkeeping",
    "body": "Hi Jane,..."
  },
  "error": null,
  "meta": {
    "requestId": "req_pqr678"
  }
}
```

#### cURL Example

```bash
curl -X POST https://hypema.app/api/v1/emails/drafts/payload \
  -H "Authorization: Bearer hpm_live_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{"leadId": "lead-uuid", "generatedEmailId": "email-uuid"}'
```

---

## Leads

### GET /leads

**List leads with pagination and filters**

- **Timing:** < 1s
- **Cost:** Free

#### Query Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `page` | integer | No | Page number. Default 1. |
| `per_page` | integer | No | Results per page. Default 20, max 100. |
| `status` | string | No | Filter by status: new | generated | drafted | sent. |
| `search` | string | No | Search by name, email, or company. |

#### Response

```json
{
  "data": [
    {
      "id": "...",
      "email": "jane@example.com",
      "firstName": "Jane",
      "lastName": "Smith",
      "company": "ExampleCo",
      "roleTitle": "CTO",
      "country": "Germany",
      "sourceUrl": null,
      "notes": null,
      "status": "new",
      "createdAt": "2026-04-01T12:00:00Z"
    }
  ],
  "error": null,
  "meta": {
    "requestId": "req_stu901",
    "tokensConsumed": 0,
    "pagination": {
      "total": 42,
      "page": 1,
      "perPage": 20,
      "hasMore": true
    }
  }
}
```

#### cURL Example

```bash
curl "https://hypema.app/api/v1/leads?page=1&per_page=20&status=new" \
  -H "Authorization: Bearer hpm_live_your_key_here"
```

---

### POST /leads

**Create a single lead**

- **Timing:** < 1s
- **Cost:** Free

#### Request Body

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `email` | string | Yes | Lead's email address. |
| `firstName` | string | No | First name. |
| `lastName` | string | No | Last name. |
| `company` | string | No | Company name. |
| `roleTitle` | string | No | Job title. |
| `country` | string | No | Country or location. |
| `sourceUrl` | string | No | Where you found this lead. |
| `notes` | string | No | Additional notes. |
| `leadGroupId` | string (uuid) | No | Assign to a lead group. |

#### Response

```json
{
  "data": {
    "id": "new-lead-uuid",
    "email": "jane@example.com",
    "firstName": "Jane",
    "lastName": "Smith",
    "company": "ExampleCo",
    "roleTitle": "CTO",
    "country": "Germany",
    "sourceUrl": null,
    "notes": null,
    "status": "new",
    "createdAt": "2026-04-01T12:00:00Z"
  },
  "error": null,
  "meta": {
    "requestId": "req_vwx234",
    "tokensConsumed": 0
  }
}
```

#### cURL Example

```bash
curl -X POST https://hypema.app/api/v1/leads \
  -H "Authorization: Bearer hpm_live_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{"email": "jane@example.com", "firstName": "Jane", "lastName": "Smith", "company": "ExampleCo"}'
```

---

### GET /leads/:id

**Get a single lead by ID**

- **Timing:** < 1s
- **Cost:** Free

#### Path Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | string (uuid) | Yes | The lead ID. |

#### Response

```json
{
  "data": {
    "id": "lead-uuid",
    "email": "jane@example.com",
    "firstName": "Jane",
    "lastName": "Smith",
    "company": "ExampleCo",
    "roleTitle": "CTO",
    "country": "Germany",
    "sourceUrl": null,
    "notes": null,
    "status": "new",
    "createdAt": "2026-04-01T12:00:00Z"
  },
  "error": null,
  "meta": {
    "requestId": "req_abc012",
    "tokensConsumed": 0
  }
}
```

#### cURL Example

```bash
curl https://hypema.app/api/v1/leads/lead-uuid-here \
  -H "Authorization: Bearer hpm_live_your_key_here"
```

---

### PATCH /leads/:id

**Update a lead's fields**

- **Timing:** < 1s
- **Cost:** Free

#### Path Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | string (uuid) | Yes | The lead ID. |

#### Request Body

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `email` | string | No | New email. |
| `firstName` | string &#124; null | No | First name (null to clear). |
| `lastName` | string &#124; null | No | Last name. |
| `company` | string &#124; null | No | Company. |
| `roleTitle` | string &#124; null | No | Job title. |
| `country` | string &#124; null | No | Country. |
| `notes` | string &#124; null | No | Notes. |
| `status` | enum | No | Status: new &#124; generated &#124; drafted &#124; sent. |

#### Response

```json
{
  "data": {
    "id": "lead-uuid",
    "email": "jane@example.com",
    "firstName": "Jane",
    "lastName": "Smith",
    "company": "NewCompanyName",
    "roleTitle": "CTO",
    "country": "Germany",
    "sourceUrl": null,
    "notes": "Updated via API",
    "status": "new",
    "createdAt": "2026-04-01T12:00:00Z"
  },
  "error": null,
  "meta": {
    "requestId": "req_def345",
    "tokensConsumed": 0
  }
}
```

#### cURL Example

```bash
curl -X PATCH https://hypema.app/api/v1/leads/lead-uuid-here \
  -H "Authorization: Bearer hpm_live_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{"company": "NewCompanyName", "notes": "Updated via API"}'
```

---

### DELETE /leads/:id

**Delete a lead permanently**

Permanently removes a lead. This action is irreversible.

- **Timing:** < 1s
- **Cost:** Free

#### Path Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | string (uuid) | Yes | The lead ID. |

#### Response

```json
{
  "data": null,
  "error": null,
  "meta": {
    "requestId": "req_yza567"
  }
}
```

#### cURL Example

```bash
curl -X DELETE https://hypema.app/api/v1/leads/lead-uuid-here \
  -H "Authorization: Bearer hpm_live_your_key_here"
```

---

## Lead Groups

### GET /lead-groups

**List all lead groups**

- **Timing:** < 1s
- **Cost:** Free

#### Response

```json
{
  "data": [
    {
      "id": "group-uuid",
      "name": "Munich Accountants",
      "source": "ai",
      "createdAt": "2026-04-01T12:00:00Z",
      "leadCount": 15
    }
  ],
  "error": null,
  "meta": {
    "requestId": "req_bcd890"
  }
}
```

#### cURL Example

```bash
curl https://hypema.app/api/v1/lead-groups \
  -H "Authorization: Bearer hpm_live_your_key_here"
```

---

### POST /lead-groups

**Create a new lead group**

- **Timing:** < 1s
- **Cost:** Free

#### Request Body

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `name` | string | Yes | Group name. Max 200 characters. |
| `source` | string | No | How this group was created: manual &#124; csv &#124; ai. Default: manual. |

#### Response

```json
{
  "data": {
    "id": "new-group-uuid",
    "name": "My API Group",
    "source": "manual",
    "createdAt": "2026-04-01T12:00:00Z",
    "leadCount": 0
  },
  "error": null,
  "meta": {
    "requestId": "req_efg123"
  }
}
```

#### cURL Example

```bash
curl -X POST https://hypema.app/api/v1/lead-groups \
  -H "Authorization: Bearer hpm_live_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{"name": "My API Group"}'
```

---

### GET /lead-groups/:id/leads

**Get all leads in a group**

- **Timing:** < 1s
- **Cost:** Free

#### Path Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | string (uuid) | Yes | The lead group ID. |

#### Response

```json
{
  "data": [
    {
      "id": "...",
      "email": "...",
      "firstName": "...",
      "status": "new"
    }
  ],
  "error": null,
  "meta": {
    "requestId": "req_hij456"
  }
}
```

#### cURL Example

```bash
curl https://hypema.app/api/v1/lead-groups/group-uuid-here/leads \
  -H "Authorization: Bearer hpm_live_your_key_here"
```

---

## Campaigns

Campaigns are automatically created when you generate emails. Each campaign tracks the leads, emails sent, and reply rates for an outreach run.

### GET /campaigns

**List all campaigns**

Returns every campaign for your workspace, most recent first. Each row includes inline stats: lead count, emails generated, emails sent, replies received, and reply rate.

- **Timing:** < 1s
- **Cost:** Free

#### Response

```json
{
  "data": [
    {
      "id": "c1a2b3c4-...",
      "name": "Spring Outreach - Apr 8",
      "tone": "professional",
      "createdAt": "2026-04-08T10:30:00Z",
      "leadCount": 25,
      "emailsGenerated": 25,
      "emailsSent": 20,
      "repliesReceived": 5,
      "replyRate": 25
    }
  ],
  "error": null,
  "meta": { "requestId": "req_abc123", "tokensConsumed": 0 }
}
```

#### cURL Example

```bash
curl https://hypema.app/api/v1/campaigns \
  -H "Authorization: Bearer hpm_live_your_key_here"
```

---

### GET /campaigns/:id

**Get a single campaign**

Returns campaign details with computed stats (lead count, emails sent, reply rate).

- **Timing:** < 1s
- **Cost:** Free

#### Path Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | string (uuid) | Yes | The campaign ID. |

#### Response

```json
{
  "data": {
    "id": "c1a2b3c4-...",
    "name": "Spring Outreach - Apr 8",
    "tone": "professional",
    "createdAt": "2026-04-08T10:30:00Z",
    "leadCount": 25,
    "emailsGenerated": 25,
    "emailsSent": 20,
    "repliesReceived": 5,
    "replyRate": 25
  },
  "error": null,
  "meta": { "requestId": "req_def456", "tokensConsumed": 0 }
}
```

#### cURL Example

```bash
curl https://hypema.app/api/v1/campaigns/CAMPAIGN_ID \
  -H "Authorization: Bearer hpm_live_your_key_here"
```

---

### GET /campaigns/:id/stats

**Get campaign stats**

Returns just the aggregated metrics: `totalLeads`, `emailsGenerated`, `emailsSent`, `repliesReceived`, and `replyRate` (percentage).

- **Timing:** < 1s
- **Cost:** Free

#### Response

```json
{
  "data": {
    "totalLeads": 25,
    "emailsGenerated": 25,
    "emailsSent": 20,
    "repliesReceived": 5,
    "replyRate": 25
  },
  "error": null,
  "meta": { "requestId": "req_ghi789", "tokensConsumed": 0 }
}
```

#### cURL Example

```bash
curl https://hypema.app/api/v1/campaigns/CAMPAIGN_ID/stats \
  -H "Authorization: Bearer hpm_live_your_key_here"
```

---

### GET /campaigns/:id/emails

**Get campaign emails with lead data**

Returns every lead in a campaign with its email content, send status, and reply data. Filter by status to see only `sent`, `replied`, or any combination.

- **Timing:** < 1s
- **Cost:** Free

#### Query Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `status` | string | No | Comma-separated statuses to filter (e.g. `sent,replied`). |

#### Response

```json
{
  "data": [
    {
      "leadId": "lead-uuid-...",
      "email": "jane@example.com",
      "firstName": "Jane",
      "lastName": "Smith",
      "company": "Acme Inc",
      "roleTitle": "CTO",
      "status": "replied",
      "sentAt": "2026-04-08T11:00:00Z",
      "repliedAt": "2026-04-09T14:30:00Z",
      "replySnippet": "Thanks for reaching out!...",
      "subject": "Quick question about Acme's infrastructure",
      "body": "Hi Jane, I noticed Acme recently..."
    }
  ],
  "error": null,
  "meta": { "requestId": "req_jkl012", "tokensConsumed": 0 }
}
```

#### cURL Example

```bash
curl "https://hypema.app/api/v1/campaigns/CAMPAIGN_ID/emails?status=replied" \
  -H "Authorization: Bearer hpm_live_your_key_here"
```

---

## Usage

### GET /usage

**Get current token balance**

Returns your current HyPeMa token usage and limits. Use this to check remaining tokens before making AI calls.

- **Timing:** < 1s
- **Cost:** Free

#### Response

```json
{
  "data": {
    "allowed": true,
    "used": 520,
    "limit": 5000,
    "remaining": 4480
  },
  "error": null,
  "meta": {
    "requestId": "req_klm789",
    "tokensConsumed": 0,
    "tokensRemaining": 4480
  }
}
```

#### cURL Example

```bash
curl https://hypema.app/api/v1/usage \
  -H "Authorization: Bearer hpm_live_your_key_here"
```
