🎯
WordPress で作成した Web ページから プラグインを使用せず API へアクセスする方法
概要
WordPress で作成した Web ページから外部 API サービスへアクセスする方法を説明します。
開発環境(ローカル)と本番環境(WordPress)で異なるエンドポイントを使用する実装方法を紹介します。
システム構成
環境構成
- 開発環境:
localhost:8000
(FastAPI サーバー) - 本番環境: WordPress 環境
技術スタック
- WordPress
- TypeScript
- webpack
- FastAPI(外部 API サービス)
実装手順
1. WordPress 側の設定
1.1 API キーの設定
wp-config.php
に API キーを定義します:
// APIキーの定義
define('EXTERNAL_SERVICE_API_KEY', 'your-api-key-here');
1.2 WordPress の REST API エンドポイント作成
functions.php
に REST API エンドポイントを追加します:
add_action('rest_api_init', function () {
register_rest_route('myapp/v1', '/process', [
'methods' => 'POST',
'callback' => 'handle_external_api_request',
'permission_callback' => '__return_true',
]);
});
function handle_external_api_request(WP_REST_Request $request) {
$data = $request->get_json_params();
// 外部APIエンドポイント
$api_url = 'https://api.example.com/process';
$api_key = EXTERNAL_SERVICE_API_KEY;
$response = wp_remote_post($api_url, [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $api_key
],
'body' => json_encode($data),
'timeout' => 20,
]);
if (is_wp_error($response)) {
return new WP_Error('api_error', 'APIリクエストエラー', ['status' => 500]);
}
return json_decode(wp_remote_retrieve_body($response), true);
}
2. フロントエンド実装
2.1 環境設定ファイル
.env
ファイルで環境変数を設定:
API_URL_DEV=http://localhost:8000/process
API_URL_PROD=/wp-json/myapp/v1/process
2.2 API サービスクラスの実装
// src/services/api/apiService.ts
interface ApiConfig {
environment: string;
endpoints: {
[key: string]: {
url: string;
};
};
}
export class ApiService {
private static instance: ApiService;
private env: ApiConfig;
private constructor() {
this.env = {
environment: process.env.NODE_ENV || "production",
endpoints: {
development: {
url: process.env.API_URL_DEV,
},
production: {
url: process.env.API_URL_PROD,
},
},
};
}
public static getInstance(): ApiService {
if (!ApiService.instance) {
ApiService.instance = new ApiService();
}
return ApiService.instance;
}
public async processData(data: any): Promise<any> {
const apiUrl = this.env.endpoints[this.env.environment].url;
try {
const response = await fetch(apiUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
if (!response.ok) {
throw new Error("API request failed");
}
return await response.json();
} catch (error) {
console.error("Error:", error);
throw error;
}
}
}
3. 環境切り替えの仕組み
開発環境(ローカル)
- FastAPI サーバー(
localhost:8000
)に直接アクセス - API キーは FastAPI 側で検証
本番環境(WordPress)
- WordPress の REST API エンドポイントを経由
- WordPress が API キーを使用して外部 API にアクセス
セキュリティ対策
-
API キーの管理
- API キーは必ず
wp-config.php
で管理 - 公開リポジトリにはコミットしない
- 本番環境の API キーは開発環境と別のものを使用
- API キーは必ず
-
通信のセキュリティ
- HTTPS 通信を強制
- タイムアウトの設定
- エラーハンドリングの実装
デバッグ方法
WordPress のデバッグログを有効化:
// wp-config.php
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
// functions.php でのログ出力例
if (defined('WP_DEBUG') && WP_DEBUG) {
error_log('API Request: ' . print_r($request_data, true));
}
Discussion