はじめに
Swagger UIのCORSエラーの回避方法を紹介する。Swagger UIで参照されるAPIサーバーには、CORS対策がされていない状況で、CORS Anywhereを使うことで回避する。
前提
- APIサーバーが、既に構築されデプロイされている(自身では変更不可)
要件
- 上記APIサーバーに対して、Swagger UIからAPIを実行できること
動作確認環境
- Ubuntu 22.04 x86_64
- Docker ver.20.10.17
- Docker Compose v2.11.0
方法
CORS Anywhereサーバーを使うことで、CORSエラーを回避するためにCORSヘッダーを付与することができる。
構成要素 | エンドポイント | 備考 |
---|---|---|
APIサーバー | https://example.com/api |
任意のREST APIサーバー |
Swagger UIサーバー | http://localhost:8080 |
|
CORS Anywhereサーバー | http://localhost:8081 |
プロキシサーバー |
Swagger UIとCORS AnywhereのDocker Composeファイルは以下のようになる。ここで、openapi.jsonは、APIサーバーのOpenAPI仕様である。
version: "3.9"
services:
swagger-ui:
image: swaggerapi/swagger-ui:latest
ports:
- 8080:8080
volumes:
- ./openapi.json:/openapi.json
environment:
SWAGGER_JSON: /openapi.json
PORT: 8080
BASE_URL: /docs
restart: always
depends_on:
- cors-anywhere
cors-anywhere:
image: testcab/cors-anywhere:latest
ports:
- "8081:8080"
environment:
- CORSANYWHERE_ALLOW_ORIGINS=*
- CORSANYWHERE_DISABLE_HOST_CHECK=true
- CORSANYWHERE_REQUIRE_HEADER_ORIGIN=false
command: ["node", "server.js", "--origin-whitelist=*"]
- 備考
- swagger-ui
- FastAPIのエンドポイントと同じにするため、
BASE_URL: /docs
を設定した
- FastAPIのエンドポイントと同じにするため、
- cors-anywhere
- CORS Anywhereは、公開Dockerイメージ:testcab/cors-anywhere:latestを利用した
- swagger-ui
次にOpenAPI仕様の例を示す。
-
ポイント
- CORS Anywhereを経由するには、
servers
キーを以下のように設定する"url": "{cors.anywhere.address}/{api.address}"
- {cors.anywhere.address}: CORS Anywhereサーバーアドレス
- {api.address}: REST APIサーバーアドレス
例:"url": "http://localhost:8081/https://example.com/api"
- つまり Swagger UI からは http://localhost:8081/ にリクエストを送信し、CORS Anywhere が https://example.com/api に中継する
- CORS Anywhereを経由するには、
{
"openapi": "3.0.0",
"info": {
"title": "Test API",
"version": "1.0.0"
},
"servers": [
{
"url": "http://localhost:8081/https://example.com/api"
}
],
"paths": {
...
}
}
ダミーのAPIサーバーを利用したサンプルを作成したので動作を確認したい方は下記を参照。
READMEに従い、プログラムを起動して、ブラウザで、http://localhost:8080/docs
にアクセスするとSwagger UIでAPIのテストができる。
Serversに、CORS Anywhereを経由してアクセスする設定となっている。
まとめ
Swagger UIのCORSエラーの回避方法を紹介した。具体的には、Swagger UIで参照されるAPIサーバーには、CORS対策がされていない状況で、CORS Anywhereを使うことで回避する方法を紹介した。今回紹介した方法は、検証環境向けであり、本番利用する場合は APIサーバー側でCORS 設定を行うことを推奨する。
参考