テスト · API
サンプルのアドレスではなく Mock API でテストする
他人のものかもしれないアドレスではなく、Prism、WireMock、MSW、json-server を相手に開発・テストします。
ガイド · API
api.example-petstore.com などのアドレスへのリクエストは、サンプルのアドレスを今もベース URL として使っているコードから送られています。このガイドでは、そのアドレスがよく設定されている場所、設定へ移す方法、再発を防ぐ方法を説明します。
サンプルからコピーしたベース URL
API_BASE_URL=https://api.example-petstore.comGET /v2/pet/42 Authorization: Bearer ••••api.example-petstore.com410 Gone キーが第三者に届きました: 無効化してください設定から読み込んだベース URL
API_BASE_URL=${API_BASE_URL}GET /v2/pet/42 Authorization: Bearer ••••200 OK リクエストとキーが正しいサービスに届きます本文付きのリクエスト、/v2/pet などの API 形式のパスへのリクエスト、JSON を要求するリクエストには、問題の詳細(RFC 9457)とともに 410 Gone が返されます。
HTTP/1.1 410 Gone
Content-Type: application/problem+json; charset=utf-8
{"type":"https://example-petstore.com/#where","title":"Example domain, not a real service",
"status":410,"detail":"api.example-petstore.com is an example domain used in documentation. …"}
このドメインは、petstore.swagger.io にある Swagger Petstore サンプル API ではありません。
BASE_URL = "https://api.example-petstore.com").env ファイル、環境変数host フィールドまたは servers フィールド{{baseUrl}} などの Postman や Insomnia の環境変数アドレスは設定から読み込み、設定されていない場合は明確なエラーで停止するようにします。
# Python: read the address from configuration, not from the code
import os
BASE_URL = os.environ["API_BASE_URL"]
// JavaScript / Node.js
const baseURL = process.env.API_BASE_URL;
// PHP 8
$baseUrl = getenv('API_BASE_URL') ?: throw new RuntimeException('API_BASE_URL is not set');
# Python, httpx
client = httpx.Client(base_url=os.environ["API_BASE_URL"])
// Node.js, axios
const api = axios.create({ baseURL: process.env.API_BASE_URL });
# Generated OpenAPI client (Python)
configuration = Configuration(host=os.environ["API_BASE_URL"])
// PHP, Guzzle
$client = new GuzzleHttp\Client(['base_uri' => getenv('API_BASE_URL')]);
// PHP, Symfony HttpClient
$client = Symfony\Component\HttpClient\HttpClient::createForBaseUri(getenv('API_BASE_URL'));
Postman や Insomnia では、環境ごとに baseUrl を設定し、送信前に正しい環境を選択します。
起動時またはテスト時に、サンプルのアドレスを拒否するチェックを追加します。
# Python
import os, re
base = os.environ["API_BASE_URL"]
if re.search(r"example-(petstore|commerce-host)\.com", base):
raise RuntimeError(f"API_BASE_URL still points at an example domain: {base}")
// PHP
$base = getenv('API_BASE_URL') ?: '';
if (preg_match('/example-(petstore|commerce-host)\.com/', $base)) {
throw new RuntimeException("API_BASE_URL still points at an example domain: $base");
}
自社のドキュメントやサンプルでは、api.example.com など、その目的のために予約された名前を使用してください。詳しくはサンプル ドメインをご覧ください。
リクエストに API キー、トークン、パスワード、セッション Cookie が含まれていた場合、それらは誤ったサーバーに届いています。発行したサービスで無効にし、新しいものを発行してください。漏えいした認証情報: 今すぐ行うべきこと
本物のサービスを使わずにテストするには: サンプルのアドレスではなく Mock API でテストする