エクスポート機能ガイド
Laravel SpectrumはAPIドキュメントを様々なフォーマットでエクスポートできます。PostmanやInsomniaなどの人気のAPIテストツールに直接インポート可能な形式で出力します。
🔗 Postmanエクスポート
基本的なエクスポート
php artisan spectrum:export:postman
デフォルトでは storage/app/spectrum/postman/collection.json
に出力されます。
カスタム出力先
php artisan spectrum:export:postman --output=/path/to/postman_collection.json
エクスポートオプション
php artisan spectrum:export:postman \
--include-examples \
--include-tests \
--environment
オプション説明:
--include-examples
: リクエスト/レスポンス例を含める--include-tests
: 自動テストスクリプトを生成--environment
: 環境変数ファイルも生成
生成される内容
コレクション構造
{
"info": {
"name": "Laravel API",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "Authentication",
"item": [
{
"name": "Login",
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"email\": \"user@example.com\",\n \"password\": \"password123\"\n}"
},
"url": {
"raw": "{{base_url}}/api/auth/login",
"host": ["{{base_url}}"],
"path": ["api", "auth", "login"]
}
}
}
]
}
]
}
環境変数
{
"name": "Laravel API Environment",
"values": [
{
"key": "base_url",
"value": "http://localhost:8000",
"type": "default"
},
{
"key": "bearer_token",
"value": "",
"type": "secret"
}
]
}
テストスクリプト
自動生成されるテストの例:
// レスポンスステータスチェック
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
// レスポンス構造の検証
pm.test("Response has required fields", function () {
const jsonData = pm.response.json();
pm.expect(jsonData).to.have.property('data');
pm.expect(jsonData.data).to.have.property('id');
pm.expect(jsonData.data).to.have.property('email');
});
// 認証トークンの保存
if (pm.response.json().token) {
pm.environment.set("bearer_token", pm.response.json().token);
}
🦊 Insomniaエクスポート
基本的なエクスポート
php artisan spectrum:export:insomnia
デフォルトでは storage/app/spectrum/insomnia/workspace.json
に出力されます。
エクスポートオプション
php artisan spectrum:export:insomnia \
--workspace-name="My API" \
--include-environments \
--folder-structure
オプション説明:
--workspace-name
: ワークスペース名--include-environments
: 環境設定を含める--folder-structure
: フォルダ構造で整理
生成される内容
ワークスペース構造
{
"_type": "export",
"__export_format": 4,
"__export_date": "2024-01-01T00:00:00.000Z",
"__export_source": "laravel-spectrum",
"resources": [
{
"_id": "wrk_1",
"_type": "workspace",
"name": "Laravel API",
"description": "Generated by Laravel Spectrum"
},
{
"_id": "env_1",
"_type": "environment",
"parentId": "wrk_1",
"name": "Base Environment",
"data": {
"base_url": "http://localhost:8000",
"bearer_token": ""
}
}
]
}
リクエスト構造
{
"_id": "req_1",
"_type": "request",
"parentId": "fld_auth",
"name": "Create User",
"method": "POST",
"url": "{{ _.base_url }}/api/users",
"headers": [
{
"name": "Content-Type",
"value": "application/json"
},
{
"name": "Authorization",
"value": "Bearer {{ _.bearer_token }}"
}
],
"body": {
"mimeType": "application/json",
"text": "{\n \"name\": \"John Doe\",\n \"email\": \"john@example.com\",\n \"password\": \"secret123\"\n}"
}
}
🛠️ カスタマイズ
エクスポート設定
// config/spectrum.php
'export' => [
'postman' => [
// Postmanコレクションのバージョン
'version' => '2.1.0',
// デフォルトの変数
'variables' => [
'base_url' => env('APP_URL', 'http://localhost:8000'),
'api_version' => 'v1',
],
// 認証プリセット
'auth_presets' => [
'bearer' => [
'type' => 'bearer',
'bearer' => [
'token' => '{{bearer_token}}'
]
],
],
// テスト生成設定
'generate_tests' => true,
'test_templates' => [
'status_check' => true,
'response_time' => true,
'schema_validation' => true,
],
],
'insomnia' => [
// 環境設定
'environments' => [
'development' => [
'base_url' => 'http://localhost:8000',
'bearer_token' => '',
],
'staging' => [
'base_url' => 'https://staging.example.com',
'bearer_token' => '',
],
'production' => [
'base_url' => 'https://api.example.com',
'bearer_token' => '',
],
],
// フォルダ構造
'folder_by_tags' => true,
'folder_icons' => [
'Authentication' => '🔐',
'Users' => '👥',
'Admin' => '👨💼',
],
],
],
カスタムフォーマッター
独自のエクスポート形式を追加:
namespace App\Spectrum\Formatters;
use LaravelSpectrum\Contracts\ExportFormatter;
class CustomFormatter implements ExportFormatter
{
public function format(array $openapi): array
{
// OpenAPIドキュメントをカスタム形式に変換
return [
'version' => '1.0',
'endpoints' => $this->transformEndpoints($openapi['paths']),
// ...
];
}
}
登録:
// AppServiceProvider.php
use LaravelSpectrum\Facades\Spectrum;
public function boot()
{
Spectrum::addFormatter('custom', CustomFormatter::class);
}
使用:
# 代わりに特定のエクスポートコマンドを使用
php artisan spectrum:export:postman --output=api.postman.json
php artisan spectrum:export:insomnia --output=api.insomnia.json
🔄 インポート手順
Postmanへのインポート
- Postmanを開く
- 左サイドバーの「Import」をクリック
- 「Upload Files」を選択
- 生成された
collection.json
を選択 - 環境変数ファイルも同様にインポート
- 環境を選択してリクエストを実行
Insomniaへのインポート
- Insomniaを開く
- Application → Preferences → Data → Import Data
- 「From File」を選択
- 生成されたファイルを選択
- インポート設定を確認
- 環境変数を設定してテスト開始
🔧 高度な使用方法
CI/CDでの自動エクスポート
# .github/workflows/export-api.yml
name: Export API Documentation
on:
push:
branches: [main]
paths:
- 'app/Http/**'
- 'routes/**'
jobs:
export:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.2'
- name: Install Dependencies
run: composer install
- name: Generate OpenAPI
run: php artisan spectrum:generate
- name: Export to Postman
run: |
php artisan spectrum:export:postman \
--output=postman/collection.json \
--environment
- name: Export to Insomnia
run: |
php artisan spectrum:export:insomnia \
--output=insomnia/workspace.json
- name: Commit changes
uses: EndBug/add-and-commit@v9
with:
add: 'postman/* insomnia/*'
message: 'Update API exports'
チーム共有
Postman Team Workspace
# チーム用の設定でエクスポート
php artisan spectrum:export:postman \
--team-id=your-team-id \
--include-monitors \
--include-mocks
Insomnia Git Sync
# Git同期用の設定でエクスポート
php artisan spectrum:export:insomnia \
--git-sync \
--no-ids # IDを除外してコンフリクトを防ぐ
💡 ベストプラクティス
1. 環境変数の活用
すべての環境依存値を変数化:
{
"base_url": "{{base_url}}",
"api_key": "{{api_key}}",
"timeout": "{{request_timeout}}"
}
2. フォルダ構造の整理
タグごとにフォルダを作成して整理:
├── Authentication
│ ├── Login
│ ├── Logout
│ └── Refresh Token
├── Users
│ ├── List Users
│ ├── Create User
│ └── Update User
└── Admin
├── Dashboard
└── Reports
3. テストの自動化
エクスポート時に基本的なテストを含める:
// ステータスコード
pm.test("Success response", () => {
pm.response.to.have.status(200);
});
// レスポンスタイム
pm.test("Response time < 500ms", () => {
pm.expect(pm.response.responseTime).to.be.below(500);
});