本連載では第一線のPerlハッカーが回替わりで執筆していきます。今回のハッカーはWebサービスを開発している礒部浩行さんで,
本稿のコードは,
Raisin ──Rest APIマイクロフレームワーク
Raisinは,
Raisinの登場背景
Raisinは,
Plack ──PSGIユーティリティ
RaisinはPlackをもとに作成されているため,
Plackは,plackup
コマンドを使用することで,
簡単な例として,hello.
という名前で保存して,plackup
コマンドで起動します。
sub {
return [
'200',
['Content-Type' => 'text/plain'],
['Hello World']
];
}
$ plackup hello.psgi HTTP::Server::PSGI: Accepting connections at http://0:5000/
スタンドアローンアプリケーションとして起動しました。ブラウザでhttp://
を開くと,Hello World
と表示されます。
PlackとPSGIについての詳しくは,
PlackによるAPI開発の問題点
PlackをそのままAPI開発として使う場合,
記述が冗長
Plackにはルーティング機能がありません。そのため,if
文などでリクエストパスを見て処理を分岐させるか,
次のコードでは,Plack::Request
とRouter::Boom
を使用しています。
use Plack::Request;
use Router::Boom;
use JSON qw/encode_json/;
my $router = Router::Boom->new();
$router->add('/users/all', sub {
['200',
[
'Content-Type' => 'application/json',
'methods' => 'GET'
],
[encode_json({
'id' => 1,
'name' => 'Sample Taro'
})],
]
});
$router->add('/users/', sub {
['200',
[
'Content-Type' => 'application/json',
'methods' => 'POST'
],
[encode_json({
'status' => 'success'
})],
]
});
sub {
my $env = shift;
my ($destination, $captured) =
$router->match($env->{PATH_INFO});
my $req = Plack::Request->new($env);
return $destination->($req);
}
これでは毎回レスポンスコードやContent-Typeを記述する必要があり,
それに対してRaisinでは,
パラメータのチェック機能がない
Plackには入力値の型や必須パラメータのチェック機能がありません。そのため,if
文などでチェックする必要があります。
次のコードでは,name
が付与されているかどうかのバリデーションを追加しています。
use JSON qw/encode_json decode_json/;
$router->add('/users/', sub {
my $req = shift;
my $json_data = decode_json($req->param);
unless ($json_data->{ name }) {
return ['400',
[
'Content-Type' => 'application/json',
'methods' => 'POST'
],
[encode_json({
'status' => 'failed'
'error_message' => "`name` is required",
})],
]
}
['200',
[
'Content-Type' => 'application/json',
'methods' => 'POST'
],
[encode_json({
'status' => 'success'
})],
]
});
今回はname
があるかどうかをチェックしているだけですが,
それに対してRaisinでは,