# フォーム作成 (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 件）。少なくとも 1 件は訪問者が入力する項目である必要があります |
| `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` のいずれか 1 つ |
| 選択 | `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 Fonts のフォント名 |
| `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) の 1 件分と同じ形式です。

```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` | フォームの作成に失敗しました |
