親切なAPI仕様書を作る
モチベーション
REST APIを作ってもどんなコマンドでどんなエンドポイントに
何があるのか、どれくらいのAPIがあるのかわからないので知りたい
API設計ツール
色々なツールが出ているみたい
- API Blueprint
- Swagger(OpenAPI)
- apiary
2016年1月にSwaggerはOpenAPIとなった経緯があるそうで
API設計の標準化が目指されているようです。
Swagger(OpenAPI)の導入
下記の環境を想定しているので、hapi用のswaggerモジュールである
hapi-swaggerを公式サイト(https://github.com/glennjones/hapi-swagger)の
Quick Startを元にインストールしてみます。
環境
OS : macOS High Sierra
NodeJS : v9.5.0
hapi : v17.0.0
npm install hapi-swagger --save
npm install inert --save
npm install vision --save
サンプルコードの実行
Quick Start にあるコードが少し間違っているので
修正した下記コードを実行
Routes部分は適切に変更する必要がある。
hoge.js
const Hapi = require('hapi');
const Inert = require('inert');
const Vision = require('vision');
const HapiSwagger = require('hapi-swagger');
const Pack = require('./package');
const Joi = require('joi');
(async () => {
const server = await new Hapi.Server({
host: 'localhost',
port: 3000,
});
const swaggerOptions = {
info: {
title: 'Test API Documentation',
version: Pack.version,
},
};
await server.register([
Inert,
Vision,
{
plugin: HapiSwagger,
options: swaggerOptions
}
]);
try {
await server.start();
console.log('Server running at:', server.info.uri);
} catch(err) {
console.log(err);
}
server.route({
method: 'GET',
path: '/todo/{id}/',
config: {
handler: function(request, h){
return "本来なら戻り値をかくよ"
},
description: 'Get todo',
notes: 'Returns a todo item by the id passed in the path',
tags: ['api'], // ADD THIS TAG
validate: {
params: {
id : Joi.number()
.required()
.description('the id for the todo item'),
}
}
},
});
})();
node hoge.jsで実行してみる
valueに値を入れてTry it outボタンを押すと
API実行時のcurlやリクエスト、レスポンスが下記のように表示される。
javadocにコード実行機能が付いたような使い勝手でいいかんじ!