# 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)
- [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-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)
- [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://api.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 |

---

## 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 target audience. Supports SSE streaming for real-time status updates.

- **Timing:** 30s-5min
- **Cost:** 5-15 tokens
- **Supports SSE streaming**

#### Request Body

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `url` | string | Yes | The company website URL to research. Example: `"https://example.com"` |

#### 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://api.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.

- **Timing:** 30s-5min
- **Cost:** 10-30 tokens
- **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. |

#### 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://api.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.

- **Timing:** 10-30s
- **Cost:** 2-5 tokens

#### 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. |

#### Response

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

#### cURL Example

```bash
curl -X POST https://api.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-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.

- **Timing:** 1-10min (depends on lead count)
- **Cost:** 2-5 tokens per lead

#### 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). |

#### 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://api.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://api.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://api.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://api.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://api.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://api.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://api.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://api.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://api.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://api.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://api.hypema.app/api/v1/lead-groups/group-uuid-here/leads \
  -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://api.hypema.app/api/v1/usage \
  -H "Authorization: Bearer hpm_live_your_key_here"
```
