# 폼 생성 (POST)

호스팅 폼을 생성합니다. 생성 즉시 `https://frms.click/{tid}`에 공개되며, 모든 제출 내용은 계정의 메시지로 저장됩니다. 자세한 내용은 [폼](https://info.pocketalert.app/features/forms.md)을 참고하세요.

## 엔드포인트

```
POST https://api.pocketalert.app/v1/forms
```

## 인증

> **Info: 필수**
>
> 요청에 다음 헤더 중 하나를 포함하세요:
> - `Token: <your-api-key>` — [API 키](https://pocketalert.app/account/apikeys)에서 발급받으세요
> - `Authorization: Bearer <jwt-token>` — [로그인](https://info.pocketalert.app/api/user/login.md)에서 받은 값

## 요청

### 헤더

| 헤더 | 필수 | 설명 |
|--------|:--------:|-------------|
| `Token` | ✅ | API 키 |
| `Authorization` | ✅ | `Bearer <jwt-token>` |

### 본문 파라미터

| 파라미터 | 타입 | 필수 | 설명 |
|-----------|------|:--------:|-------------|
| `name` | string | ✅ | 내부용 이름, 최대 191자. 기본 푸시 제목으로도 사용됩니다 |
| `fields` | array | ✅ | 폼의 필드, 최대 30개. 방문자가 직접 입력하는 필드가 최소 하나 있어야 합니다 |
| `settings` | object | ❌ | 제목, 텍스트, 디자인 설정. 모든 키에 기본값이 있습니다 |
| `application_tid` | string | ❌ | 제출 내용이 속할 애플리케이션 |
| `device_tid` | string | ❌ | 대상 기기 TID 또는 `all`. 생략하면 모든 기기 |
| `default_level` | int | ❌ | 제출 내용의 우선순위 레벨(`-2`..`2`). [메시지 우선순위 레벨](https://info.pocketalert.app/api/messages/create.md#priority-levels)을 참고하세요 |
| `push_title` | string | ❌ | `{Field label}` 토큰을 포함한 푸시 제목 템플릿, 최대 191자 |
| `allowed_origins` | array | ❌ | 폼 삽입 및 제출을 허용할 호스트, 최대 10개. 비워두면 어디서나 허용 |
| `max_responses` | int | ❌ | 지정한 응답 수에 도달하면 폼 마감. `0`(기본값)은 무제한 |
| `closes_at` | string | ❌ | 마감 시각, RFC 3339 형식. UTC로 저장됩니다 |
| `is_active` | boolean | ❌ | `false`면 즉시 폼을 마감합니다. 기본값은 `true` |

### 필드

`fields`의 각 항목:

| 파라미터 | 타입 | 필수 | 설명 |
|-----------|------|:--------:|-------------|
| `id` | string | ✅ | 폼 내에서 고유해야 함: 영문자, 숫자, `_`, `-`만 사용 가능, 최대 40자 |
| `type` | string | ✅ | 아래 타입 중 하나 |
| `label` | string | ✅ | 입력란 위에 표시됨, 최대 200자(`paragraph`는 2000자) |
| `placeholder` | string | ❌ | text, textarea, email, phone, number, url, dropdown에서만 사용 |
| `required` | boolean | ❌ | 레이아웃 필드에서는 무시됨 |
| `options` | array | ✅ 선택형 필드 | `dropdown`, `radio`, `checkboxes`의 경우 최대 50개 항목 |
| `param` | string | ✅ `hidden` | 값을 읽어올 URL 파라미터, 예: `utm_source` |

| 그룹 | 타입 | 제출 값 |
|-------|-------|-----------------|
| 텍스트 | `text`, `textarea`, `email`, `phone`, `number`, `url`, `date` | 문자열. `text`는 1000자, `textarea`는 5000자까지 허용 |
| 선택 | `dropdown`, `radio` | `options` 중 하나 |
| 선택 | `checkboxes` | `options`의 배열 |
| 선택 | `checkbox` | 불리언, `Yes` / `No`로 표시 |
| 평가 | `rating`(1–5), `nps`(0–10) | 숫자 |
| 레이아웃 | `heading`, `paragraph`, `divider` | 제출되지 않음 |
| 추적 | `hidden` | 방문자가 아닌 페이지 URL에서 가져옴 |

이메일, 휴대폰, 숫자, URL, 날짜 값은 서버에서 검증됩니다. 브라우저 검사는 편의 기능일 뿐, 실제 검증은 서버에서 이루어집니다.

### 설정

모든 키는 선택 사항입니다. 생략한 항목은 기본값을 유지합니다.

| 파라미터 | 타입 | 기본값 | 설명 |
|-----------|------|---------|-------------|
| `title` | string | `""` | 폼 위에 표시되는 제목, 최대 200자 |
| `top_text` | string | `""` | 소개 텍스트, 최대 2000자. 일반 텍스트이며 링크는 클릭 가능하게 표시됩니다 |
| `bottom_text` | string | `""` | 버튼 아래 텍스트, 최대 2000자 |
| `success_message` | string | `Thanks! Your response has been sent.` | 제출 후 표시되는 메시지, 최대 500자 |
| `closed_message` | string | `This form is no longer accepting responses.` | 폼이 마감되었을 때 표시되는 메시지 |
| `background_color` | string | `#f5f5f4` | 페이지 배경색, `#rrggbb` |
| `card_color` | string | `#ffffff` | 폼 배경색 |
| `text_color` | string | `#1c1917` | 텍스트 색상 |
| `primary_color` | string | `#3f5cad` | 강조색, 별도로 재정의하지 않으면 버튼 색상으로도 사용 |
| `font_family` | string | `Inter` | 이름으로 지정하는 Google Font |
| `font_size` | int | `16` | 12–24 |
| `font_weight` | int | `400` | 300, 400, 500, 600 또는 700 |
| `border_radius` | int | `10` | 0–48 |
| `hide_branding` | boolean | `false` | "Powered by Pocket Alert" 링크를 숨깁니다. 유료 플랜 전용이며, 무료 플랜에서는 API가 `false`로 되돌립니다 |
| `submit` | object | — | `{ "text": "Submit", "color": "", "size": "md" }`. `size`는 `sm`, `md`, `lg` 중 하나이며, `color`가 비어 있으면 `primary_color`를 따릅니다 |

### 푸시 제목 템플릿

`push_title`은 응답 내용으로 알림 제목을 만듭니다:

```
New lead: {Name} ({Email})
```

토큰은 필드의 **라벨**을 기준으로 참조하며(대소문자 구분 없음), 폼 이름을 가리키는 `{form}`도 사용할 수 있습니다. 응답이 없는 토큰은 제목에서 제외되며, 남는 내용이 없으면 제목은 `Form: {name}`으로 대체됩니다. 이 템플릿은 공개 페이지에 노출되지 않습니다.

### 허용 출처

폼 ID는 공개 링크에 포함되므로, 기본적으로 이 ID를 가진 누구나 폼을 삽입할 수 있습니다. `allowed_origins`를 설정하면 이를 막을 수 있습니다. 목록에 있는 호스트만 폼을 삽입할 수 있으며, 목록에 없는 `Origin`(또는 `Referer`)에서 온 제출은 `403`으로 거부됩니다.

URL이 아닌 호스트를 입력하세요: 예를 들어 `example.com`, `app.example.com`, 모든 하위 도메인을 허용하려면 `*.example.com`, 개발 중에는 `localhost:3000`. `www.`은 무시됩니다.

### 요청 예시

**cURL**

```bash
curl -X POST "https://api.pocketalert.app/v1/forms" \
  -H "Token: your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Contact form",
    "push_title": "New lead: {Name}",
    "fields": [
      { "id": "name", "type": "text", "label": "Name", "required": true },
      { "id": "email", "type": "email", "label": "Email", "required": true },
      { "id": "message", "type": "textarea", "label": "Message" },
      { "id": "src", "type": "hidden", "label": "Source", "param": "utm_source" }
    ],
    "settings": {
      "title": "Get in touch",
      "top_text": "We reply within one business day.",
      "primary_color": "#3f5cad"
    }
  }'
```

**JavaScript**

```javascript
const response = await fetch('https://api.pocketalert.app/v1/forms', {
  method: 'POST',
  headers: {
    'Token': 'your-api-key',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'Contact form',
    push_title: 'New lead: {Name}',
    fields: [
      { id: 'name', type: 'text', label: 'Name', required: true },
      { id: 'email', type: 'email', label: 'Email', required: true },
      { id: 'message', type: 'textarea', label: 'Message' }
    ],
    settings: { title: 'Get in touch' }
  })
});

const form = await response.json();
console.log('Form link:', `https://frms.click/${form.tid}`);
```

**Python**

```python
import requests

response = requests.post(
    'https://api.pocketalert.app/v1/forms',
    headers={'Token': 'your-api-key'},
    json={
        'name': 'Contact form',
        'push_title': 'New lead: {Name}',
        'fields': [
            {'id': 'name', 'type': 'text', 'label': 'Name', 'required': True},
            {'id': 'email', 'type': 'email', 'label': 'Email', 'required': True},
            {'id': 'message', 'type': 'textarea', 'label': 'Message'},
        ],
        'settings': {'title': 'Get in touch'},
    }
)

form = response.json()
print(f"Form link: https://frms.click/{form['tid']}")
```

**PHP**

```php
$form = Http::withHeaders([
    'Token' => 'your-api-key',
])->post('https://api.pocketalert.app/v1/forms', [
    'name' => 'Contact form',
    'push_title' => 'New lead: {Name}',
    'fields' => [
        ['id' => 'name', 'type' => 'text', 'label' => 'Name', 'required' => true],
        ['id' => 'email', 'type' => 'email', 'label' => 'Email', 'required' => true],
        ['id' => 'message', 'type' => 'textarea', 'label' => 'Message'],
    ],
    'settings' => ['title' => 'Get in touch'],
])->json();

echo 'Form link: https://frms.click/'.$form['tid'];
```

## 응답

### 성공 응답

> **Tip: 201 Created**
>
> 폼이 공개되었습니다. `https://frms.click/{tid}`를 공유하거나, [폼](https://info.pocketalert.app/features/forms.md#embedding)을 참고해 삽입하세요.

응답 본문은 [모든 폼 조회](https://info.pocketalert.app/api/forms/get-forms.md#response)의 항목 하나와 같은 형식입니다.

```json
{
  "tid": "vml19aihrga216gt8apc5e3m9",
  "name": "Contact form",
  "fields": [
    { "id": "name", "type": "text", "label": "Name", "required": true },
    { "id": "email", "type": "email", "label": "Email", "required": true },
    { "id": "message", "type": "textarea", "label": "Message" },
    { "id": "src", "type": "hidden", "label": "Source", "param": "utm_source" }
  ],
  "settings": {
    "title": "Get in touch",
    "top_text": "We reply within one business day.",
    "success_message": "Thanks! Your response has been sent.",
    "closed_message": "This form is no longer accepting responses.",
    "background_color": "#f5f5f4",
    "card_color": "#ffffff",
    "text_color": "#1c1917",
    "primary_color": "#3f5cad",
    "font_family": "Inter",
    "font_size": 16,
    "font_weight": 400,
    "border_radius": 10,
    "hide_branding": false,
    "submit": { "text": "Submit", "color": "", "size": "md" }
  },
  "application_tid": "",
  "device_tid": "",
  "default_level": null,
  "push_title": "New lead: {Name}",
  "allowed_origins": [],
  "max_responses": 0,
  "closes_at": null,
  "closed": false,
  "is_active": true,
  "submissions_count": 0,
  "last_submission_at": "",
  "created_at": "23.09.2026 11:40:02"
}
```

### 오류 응답

| 상태 | 설명 |
|:------:|-------------|
| `400` | 유효성 검사 오류 — `error` 필드에 잘못된 필드 또는 설정이 표시됩니다 |
| `401` | 인증되지 않음 — 토큰이 잘못되었거나 없습니다 |
| `403` | 플랜에서 허용하는 폼 개수에 도달했습니다 |
| `500` | 폼 생성에 실패했습니다 |
