Swagger と OpenAPI によるファイルアップロード API の文書化
OpenAPI のアップロードエンドポイントには、リクエストボディ自体を必須にする指定と、そのボディ内のファイルプロパティを必須にする指定が、それぞれ必要です。このチュートリアルでは、Swagger UI でファイルをアップロードし、同じバイト列をダウンロードできるローカルの Express API を構築します。ドキュメントには、サーバーが実際に使用するフィールド、制限、API キー、エラーを記載します。
Swagger と OpenAPI とは?
OpenAPI は HTTP の仕様を記述し、Swagger UI はそのドキュメントを対話型クライアントに変えます。ここでは、swagger-jsdoc が共通定義とルートの横にあるコメントから
OpenAPI 3.0.4 ドキュメントを生成します。ファイル API には、POST /upload、POST /uploads、GET /download/{filename} の三つの操作があります。アップロードのレスポンスにはメタデータが、ダウンロードのレスポンスには保存済みのバイト列が含まれます。
requestBody.required: true と、オブジェクトの required: [file] の違いは重要です。前者はボディを必須にし、後者はそのプロパティを必須にします。複数ファイルのアップロードには、required: [files]、minItems: 1、maxItems: 10 も必要です。OpenAPI 3.0 では、各ファイルに
type: string と format: binary を使用します。これらの宣言はリクエストを記述するものであり、Express と Multer 側でも制約を適用する必要があります。OpenAPI のリクエストボディとスキーマの定義を参照してください。
プロジェクトへの Swagger の導入
Bash 互換シェル、Node.js 26、Yarn 4 を利用できる Corepack を用意してください。代替のダウンロードコマンドを使う場合は、cURL もインストールします。このサンプルは Linux 上の Node.js 26.8.1 と Yarn 4.12.0 でテストしています。Node は組み込みの型除去機能を使ってこれらの TypeScript ファイルを実行します。この機能は型チェックを行いません。
新しい file-api-swagger プロジェクトを作成する親ディレクトリで、次のコマンドを実行してください。ディレクトリがすでに存在する場合や移動に失敗した場合は、連結されたコマンドの実行が停止します。空のロックファイルにより、別のチェックアウト内に作成した場合でも、独立した Yarn プロジェクトとして認識されます。
mkdir file-api-swagger &&
cd file-api-swagger &&
printf '%s\n' '{"private":true,"type":"module","packageManager":"yarn@4.12.0"}' > package.json &&
touch yarn.lock &&
corepack yarn config set nodeLinker node-modules &&
corepack yarn add --exact express@5.2.1 multer@2.4.0 swagger-jsdoc@6.3.0 swagger-ui-express@5.0.1 swagger-ui-dist@5.33.0
再現可能なインストールのため、生成された yarn.lock を保持してください。swagger-ui-dist を固定すると、ブラウザー UI のバージョンも固定されます。固定しない場合、swagger-ui-express が依存関係のバージョン範囲から解決します。Multer 2.4.0 リリースにはセキュリティ修正が含まれています。デプロイするアプリケーションでこれらの固定バージョンを再利用する前に、最新の勧告を確認してください。
file-api-swagger に次の二つのファイルを作成してください。各ブロックはファイルの内容全体です。
openapi.ts での共通スキーマの定義
レスポンススキーマでは、サーバーが返すすべてのフィールドを必須にしています。ドキュメントに記載するすべての操作は、X-API-Key の要件を継承します。相対サーバー URL を使うことで、OS が別のポートを割り当てても、Swagger UI は同じオリジンを使用します。
import { join } from 'node:path'
import swaggerJsdoc from 'swagger-jsdoc'
function errorResponse(description: string): object {
return {
description,
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } },
}
}
export const swaggerSpec = swaggerJsdoc({
failOnErrors: true,
definition: {
openapi: '3.0.4',
info: { title: 'File Upload API', version: '1.0.0' },
servers: [{ url: '/' }],
security: [{ ApiKeyAuth: [] }],
components: {
securitySchemes: {
ApiKeyAuth: { type: 'apiKey', in: 'header', name: 'X-API-Key' },
},
schemas: {
File: {
type: 'object',
additionalProperties: false,
required: ['id', 'name', 'size', 'mimetype'],
properties: {
id: { type: 'string', pattern: '^[a-f0-9]{32}$' },
name: { type: 'string', description: 'Client filename, not a storage path.' },
size: { type: 'integer', minimum: 0, maximum: 5242880 },
mimetype: { type: 'string', enum: ['image/jpeg', 'image/png', 'application/pdf'] },
},
},
SingleUpload: {
type: 'object',
additionalProperties: false,
required: ['file'],
properties: { file: { $ref: '#/components/schemas/File' } },
},
MultipleUpload: {
type: 'object',
additionalProperties: false,
required: ['files'],
properties: {
files: {
type: 'array', minItems: 1, maxItems: 10,
items: { $ref: '#/components/schemas/File' },
},
},
},
Error: {
type: 'object',
additionalProperties: false,
required: ['error'],
properties: { error: { type: 'string' } },
},
},
responses: {
BadUpload: errorResponse('Missing file, wrong field, too many files, or malformed multipart body.'),
Unauthorized: errorResponse('Missing or incorrect X-API-Key.'),
TooLarge: errorResponse('A file exceeds 5 MiB (5,242,880 bytes).'),
UnsupportedType: errorResponse('Expected multipart/form-data with JPEG, PNG, or PDF part types.'),
NotFound: errorResponse('Unknown or invalid generated file ID.'),
ServerError: errorResponse('File operation failed.'),
},
},
},
apis: [join(import.meta.dirname, 'server.ts')],
})
swagger-jsdoc の説明にあるとおり、failOnErrors はアノテーションの解析エラーがあると起動を失敗させます。ただし、ルートの動作とドキュメントを比較するわけではありません。その点は、このチュートリアルの後半で確認します。
ファイルアップロードエンドポイントの文書化
次の内容全体を server.ts として保存してください。このコードはアップロードを解析する前に認証を行い、Multer が生成した名前で
uploads/ にファイルを保存します。このディレクトリは、認証付きのダウンロードルート経由でのみ公開します。Multer の制限で各ファイルと各リクエストの上限を設定し、テキストフィールドは拒否します。
import { timingSafeEqual } from 'node:crypto'
import { mkdirSync } from 'node:fs'
import { join } from 'node:path'
import express from 'express'
import type { ErrorRequestHandler, RequestHandler } from 'express'
import multer from 'multer'
import swaggerUi from 'swagger-ui-express'
import { swaggerSpec } from './openapi.ts'
const apiKey = process.env.FILE_API_KEY
if (!apiKey) {
console.error('Set FILE_API_KEY before starting the server.')
process.exit(1)
}
const portText = process.env.PORT ?? '0'
const port = Number(portText)
if (!/^\d+$/.test(portText) || !Number.isInteger(port) || port > 65535) {
console.error('PORT must be an integer from 0 to 65535.')
process.exit(1)
}
const expectedKey = Buffer.from(apiKey)
const requireApiKey: RequestHandler = (req, res, next) => {
const suppliedKey = Buffer.from(req.get('X-API-Key') ?? '')
if (suppliedKey.length !== expectedKey.length || !timingSafeEqual(suppliedKey, expectedKey)) {
res.status(401).json({ error: 'Unauthorized' })
return
}
next()
}
class UnsupportedFileTypeError extends Error {}
const uploadsDir = join(import.meta.dirname, 'uploads')
mkdirSync(uploadsDir, { recursive: true, mode: 0o700 })
const upload = multer({
dest: uploadsDir,
limits: { fileSize: 5 * 1024 * 1024, files: 10, fields: 0 },
fileFilter: (_req, file, callback) => {
if (!['image/jpeg', 'image/png', 'application/pdf'].includes(file.mimetype)) {
callback(new UnsupportedFileTypeError())
return
}
callback(null, true)
},
})
function metadata(file: Express.Multer.File): object {
return { id: file.filename, name: file.originalname, size: file.size, mimetype: file.mimetype }
}
const app = express()
app.get('/openapi.json', (_req, res) => res.json(swaggerSpec))
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(null, {
swaggerOptions: { url: '/openapi.json', validatorUrl: null },
}))
app.use(['/upload', '/uploads', '/download'], requireApiKey)
app.use(['/upload', '/uploads'], (req, res, next) => {
if (!req.is('multipart/form-data')) {
res.status(415).json({ error: 'Expected multipart/form-data' })
return
}
next()
})
/**
* @openapi
* /upload:
* post:
* operationId: uploadFile
* summary: Upload one file
* requestBody:
* required: true
* content:
* multipart/form-data:
* schema:
* type: object
* additionalProperties: false
* required: [file]
* properties:
* file:
* type: string
* format: binary
* description: At most 5 MiB. Empty files are accepted.
* encoding:
* file:
* contentType: image/jpeg, image/png, application/pdf
* responses:
* '200':
* description: Stored file metadata.
* content:
* application/json:
* schema: { $ref: '#/components/schemas/SingleUpload' }
* '400': { $ref: '#/components/responses/BadUpload' }
* '401': { $ref: '#/components/responses/Unauthorized' }
* '413': { $ref: '#/components/responses/TooLarge' }
* '415': { $ref: '#/components/responses/UnsupportedType' }
* '500': { $ref: '#/components/responses/ServerError' }
*/
app.post('/upload', upload.single('file'), (req, res) => {
if (!req.file) {
res.status(400).json({ error: 'No file uploaded' })
return
}
res.json({ file: metadata(req.file) })
})
/**
* @openapi
* /uploads:
* post:
* operationId: uploadFiles
* summary: Upload up to ten files
* requestBody:
* required: true
* content:
* multipart/form-data:
* schema:
* type: object
* additionalProperties: false
* required: [files]
* properties:
* files:
* type: array
* minItems: 1
* maxItems: 10
* items:
* type: string
* format: binary
* description: At most 5 MiB. Empty files are accepted.
* encoding:
* files:
* contentType: image/jpeg, image/png, application/pdf
* responses:
* '200':
* description: Stored metadata in upload order.
* content:
* application/json:
* schema: { $ref: '#/components/schemas/MultipleUpload' }
* '400': { $ref: '#/components/responses/BadUpload' }
* '401': { $ref: '#/components/responses/Unauthorized' }
* '413': { $ref: '#/components/responses/TooLarge' }
* '415': { $ref: '#/components/responses/UnsupportedType' }
* '500': { $ref: '#/components/responses/ServerError' }
*/
app.post('/uploads', upload.array('files', 10), (req, res) => {
if (!Array.isArray(req.files) || req.files.length === 0) {
res.status(400).json({ error: 'No files uploaded' })
return
}
res.json({ files: req.files.map(metadata) })
})
/**
* @openapi
* /download/{filename}:
* get:
* operationId: downloadFile
* summary: Download a stored file
* parameters:
* - in: path
* name: filename
* required: true
* description: Generated ID returned by an upload, not the client filename.
* schema: { type: string, pattern: '^[a-f0-9]{32}$' }
* responses:
* '200':
* description: Original bytes, downloaded with the generated ID as the filename.
* headers:
* Content-Disposition:
* schema: { type: string }
* description: Attachment using the generated file ID.
* content:
* application/octet-stream:
* schema: { type: string, format: binary }
* '401': { $ref: '#/components/responses/Unauthorized' }
* '404': { $ref: '#/components/responses/NotFound' }
* '500': { $ref: '#/components/responses/ServerError' }
*/
app.get('/download/:filename', (req, res, next) => {
const id = req.params.filename
if (!/^[a-f0-9]{32}$/.test(id)) {
res.status(404).json({ error: 'File not found' })
return
}
res.set('X-Content-Type-Options', 'nosniff')
res.download(id, { root: uploadsDir }, (error) => {
if (!error) return
if (res.headersSent) return next(error)
if ('code' in error && error.code === 'ENOENT') {
res.status(404).json({ error: 'File not found' })
return
}
next(error)
})
})
const handleError: ErrorRequestHandler = (error: unknown, _req, res, next) => {
if (res.headersSent) return next(error)
if (error instanceof UnsupportedFileTypeError) {
res.status(415).json({ error: 'Unsupported file type' })
return
}
if (error instanceof multer.MulterError) {
res.status(error.code === 'LIMIT_FILE_SIZE' ? 413 : 400).json({ error: 'Upload rejected' })
return
}
if (error instanceof Error && ['Multipart: Boundary not found', 'Unexpected end of form',
'Malformed part header'].includes(error.message)) {
res.status(400).json({ error: 'Invalid multipart body' })
return
}
console.error('File operation failed')
res.status(500).json({ error: 'File operation failed' })
}
app.use(handleError)
const server = app.listen(port, '127.0.0.1', (error?: Error) => {
if (error) {
console.error(`Could not listen on 127.0.0.1:${port}: ${error.message}`)
process.exitCode = 1
return
}
const address = server.address()
if (address && typeof address === 'object') {
console.log(`Swagger UI: http://127.0.0.1:${address.port}/api-docs/`)
}
})
単一ファイル用のルートは、file という名前のパートを一つ受け付けます。バッチ用のルートは一つから 10 個のパートを受け付けます。すべてのパート名は
files であり、files[] ではありません。どちらも余分なテキストフィールドと未定義のファイルフィールドを拒否します。ファイルは 5 MiB 以下である必要があります。Multer 2.4.0 は、ちょうど 5,242,880 バイトを受け付け、それより大きいファイルを拒否します。この制限は仕様に記述しますが、maxLength としては定義しません。これは文字列の長さの制約であり、マルチパートのバイト数制限を移植可能な形で指定するものではないためです。名前のある空のファイルは受け付けます。
許可するパートの MIME タイプは JPEG、PNG、PDF です。ただし、これらはクライアント側の申告です。Content-Type: application/pdf を指定して送信したテキストファイルも、このフィルターを通過します。このフィルターも encoding.contentType も、ファイルが有効な PDF や画像であることを証明するものではありません。
Swagger UI からのアップロード
プロジェクトディレクトリで、このローカルデモ専用のキーを使ってサーバーを起動してください。
FILE_API_KEY=local-demo-key node server.ts
表示された URL を開いてください。デフォルトのポートは 0 で、OS に空きポートの割り当てを要求します。ポートを選ぶには PORT を設定します。キーの欠落、無効なポート、使用中のポートは起動失敗の原因になります。Express 5 は listen の失敗をコールバックに渡すため、コールバックではエラー引数を確認します。
- Authorize を選択し、Value: に
local-demo-keyを入力してから、Authorize と Close を選択します。 POST /uploadを展開し、Try it out を選択します。fileに小さな JPEG、PNG、PDF のいずれかを選び、Execute を選択します。- サーバーのレスポンスが
200で、file.id、file.name、file.size、file.mimetypeを含むことを確認します。ダウンロード手順で使うため、file.idをコピーします。 POST /uploadsでは、最初のファイルを選択し、追加ファイルごとに Add string item を使ってから、Execute を選択します。レスポンスのfiles配列には、受け付けたファイルごとに一つのメタデータオブジェクトが含まれます。
生成されたドキュメントは、同じオリジンの /openapi.json で取得できます。Swagger UI はラッパーの URL 設定を使って、そのエンドポイントを読み込みます。公開ドキュメントにはキーのヘッダーを記述しますが、キーの値は含めません。
ファイルダウンロードエンドポイントの文書化
Swagger UI で GET /download/{filename} を展開し、Try it out を選択して、生成された ID を filename に貼り付けます。Execute を選択してから、レスポンス内の
Download file を選択します。ファイルを保存し、元のファイルと比較してください。添付ファイル名には生成された ID を使うため、元の拡張子は付きません。
空のファイルの場合、Swagger UI 5.33.0 は 200 と
Content-Length: 0 を受信しますが、ダウンロードリンクを表示しません。代わりに cURL でレスポンスを保存できます。別のターミナルで次を実行し、ポートと生成された ID を含む完全なダウンロード URL を貼り付けてください。このコマンドは、downloaded.bin がすでに存在すると置き換えます。コマンドが成功したら、元のファイルと比較してください。
read -r -p 'Paste the full download URL: ' download_url &&
curl -fsSL -H 'X-API-Key: local-demo-key' -o downloaded.bin "$download_url"
成功レスポンスは application/octet-stream と OpenAPI のバイナリスキーマを使用します。サーバーは ID の形式を確認し、非公開のアップロードディレクトリ配下のパスとして解決します。同じクライアントファイル名で再度アップロードすると、新しい ID が作成されます。以前のアップロードは上書きされません。保存したファイルは、サーバーを再起動しても残ります。ファイルが不要になったら、Ctrl+C でサーバーを停止し、このデモプロジェクトの
uploads/ ディレクトリを削除してください。自動的な保持ポリシーはありません。
仕様と実際のレスポンスの比較
実行中の /openapi.json の URL を Postman にインポートし、X-API-Key ヘッダーを指定することもできます。ドキュメントは相対サーバー URL を使うため、インポートしたコレクションのベース URL を、割り当てられたポートを含むローカルサーバーのオリジンに設定してください。どのクライアントを使う場合も、マルチパートの境界はクライアントに生成させてください。Content-Type: multipart/form-data ヘッダーだけを手動で設定すると、境界が欠落します。
成功レスポンス以外も確認してください。次のケースでは、JSON エラーボディに
error 文字列がちょうど一つ含まれます。Swagger UI が送信を防ぐ無効なリクエストには、直接リクエストを送れる HTTP クライアントを使ってください。
| リクエスト | 想定ステータス |
|---|---|
| キーなし、または誤ったキーでのアップロードやダウンロード | 401 |
| 名前のあるファイルを含まないマルチパートアップロード | 400 |
file パートを /upload に二つ、または files パートを /uploads に 11 個送信 | 400 |
| 余分なテキストフィールド、または未定義のファイルフィールド | 400 |
| 5,242,880 バイトを超えるファイル | 413 |
text/plain と申告されたパート、またはマルチパートではないアップロードボディ | 415 |
| 無効な ID、または未知の 32 文字の 16 進数 ID によるダウンロード | 404 |
許可された MIME タイプを申告する空のファイルと、ゼロバイト値および UTF-8 として無効なバイト列を含むバイナリファイルもアップロードし、両方のダウンロードをバイト単位で比較してください。スキーマ検証の成功だけでは、サーバーがバイト列を保持したことは確認できません。フィールド、個数制限、レスポンス構造を変更した場合は、実装と OpenAPI ドキュメントの両方を変更し、これらのリクエストを再実行してください。
セキュリティ上の考慮事項
このキーは、デモの保存領域全体へのアクセスを許可します。OpenAPI のセキュリティ宣言は送信方法をクライアントに伝えるだけで、実際の確認はミドルウェアが行います。複数ユーザー向けのサービスには、個別の認証情報とファイルごとの認可が必要です。このデモには、保存容量の総量制限もリクエストのレート制限もありません。
この HTTP サンプルはループバック内でのみ使用してください。デプロイするサービスには、HTTPS、保持ポリシー、アップロードの用途に適したコンテンツ検証が必要です。ファイルを処理したりインラインで配信したりする前に、解析またはセキュリティスキャンを行ってください。生成したファイル名と認証付きの添付ファイルダウンロードを維持することは有用ですが、それだけでクライアント提供の MIME メタデータが信頼できるコンテンツ検証になるわけではありません。
