Expressjs-restful-apis

提供:Dev Guides
移動先:案内検索

ExpressJS-RESTFul API

モバイルアプリケーション、シングルページアプリケーションを作成し、AJAX呼び出しを使用し、クライアントにデータを提供するには、APIが常に必要です。 これらのAPIとエンドポイントを構造化して名前を付ける方法の一般的なアーキテクチャスタイルは、* REST(Representational Transfer State)と呼ばれます。 *HTTP 1.1 は、RESTの原則を念頭に置いて設計されました。 RESTは2000年に Roy Fielding のPaper Fielding Dissertationsで紹介されました。

RESTful URIとメソッドは、リクエストの処理に必要なほぼすべての情報を提供します。 以下の表は、さまざまな動詞の使用方法とURIの命名方法をまとめたものです。 最後に向けて映画APIを作成します。それがどのように構造化されるか議論しましょう。

Method URI Details Function
GET /movies Safe, cachable Gets the list of all movies and their details
GET /movies/1234 Safe, cachable Gets the details of Movie id 1234
POST /movies N/A Creates a new movie with the details provided. Response contains the URI for this newly created resource.
PUT /movies/1234 Idempotent Modifies movie id 1234(creates one if it doesn’t already exist). Response contains the URI for this newly created resource.
DELETE /movies/1234 Idempotent Movie id 1234 should be deleted, if it exists. Response should contain the status of the request.
DELETE or PUT /movies Invalid Should be invalid. DELETE *and PUT* should specify which resource they are working on.

ExpressでこのAPIを作成しましょう。 JavaScriptでの操作が簡単であり、その他の利点があるため、トランスポートデータ形式としてJSONを使用します。 次のプログラムのように、 index.js ファイルを movies.js ファイルに置き換えます。

index.js

var express = require('express');
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer();

var app = express();

app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(upload.array());

//Require the Router we defined in movies.js
var movies = require('./movies.js');

//Use the Router on the sub route/movies
app.use('/movies', movies);

app.listen(3000);

アプリケーションのセットアップが完了したので、APIの作成に集中しましょう。

movies.jsファイルをセットアップすることから始めます。 映画を保存するためにデータベースを使用するのではなく、メモリに保存します。サーバーが再起動するたびに、私たちが追加した映画は消えてしまいます。 これは、データベースまたはファイルを使用して(node fsモジュールを使用して)簡単に模倣できます。

Expressをインポートしたら、ルーターを作成し、_module.exports_を使用してエクスポートします-

var express = require('express');
var router = express.Router();
var movies = [
   {id: 101, name: "Fight Club", year: 1999, rating: 8.1},
   {id: 102, name: "Inception", year: 2010, rating: 8.7},
   {id: 103, name: "The Dark Knight", year: 2008, rating: 9},
   {id: 104, name: "12 Angry Men", year: 1957, rating: 8.9}
];

//Routes will go here
module.exports = router;

ルートを取得

すべての映画を取得するためのGETルートを定義しましょう-

router.get('/', function(req, res){
   res.json(movies);
});

これが正常に機能しているかどうかをテストするには、アプリを実行し、ターミナルを開いて入力します-

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET
localhost:3000/movies

次の応答が表示されます-

[{"id":101,"name":"Fight Club","year":1999,"rating":8.1},
{"id":102,"name":"Inception","year":2010,"rating":8.7},
{"id":103,"name":"The Dark Knight","year":2008,"rating":9},
{"id":104,"name":"12 Angry Men","year":1957,"rating":8.9}]

すべての映画を入手するルートがあります。 IDで特定の映画を取得するためのルートを作成しましょう。

router.get('/:id([0-9]{3,})', function(req, res){
   var currMovie = movies.filter(function(movie){
      if(movie.id == req.params.id){
         return true;
      }
   });
   if(currMovie.length == 1){
      res.json(currMovie[0])
   } else {
      res.status(404);//Set status to 404 as movie was not found
      res.json({message: "Not Found"});
   }
});

これにより、指定したIDに従って映画が取得されます。 出力を確認するには、端末で次のコマンドを使用します-

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET
localhost:3000/movies/101

あなたは次の応答を取得します-

{"id":101,"name":"Fight Club","year":1999,"rating":8.1}

無効なルートにアクセスすると、* GETできません*エラーが発生しますが、存在しないIDを持つ有効なルートにアクセスすると、404エラーが発生します。

GETルートの処理は完了しました。 POST ルートに進みましょう。

POSTルート

*POSTed* データを処理するには、次のルートを使用します-
router.post('/', function(req, res){
  //Check if all fields are provided and are valid:
   if(!req.body.name ||
      !req.body.year.toString().match(/^[0-9]{4}$/g) ||
      !req.body.rating.toString().match(/^[0-9]\.[0-9]$/g)){

      res.status(400);
      res.json({message: "Bad Request"});
   } else {
      var newId = movies[movies.length-1].id+1;
      movies.push({
         id: newId,
         name: req.body.name,
         year: req.body.year,
         rating: req.body.rating
      });
      res.json({message: "New movie created.", location: "/movies/" + newId});
   }
});

これにより、新しいムービーが作成され、movies変数に保存されます。 このルートを確認するには、端末に次のコードを入力します-

curl -X POST --data "name = Toy%20story&year = 1995&rating = 8.5" http://localhost:3000/movies

次の応答が表示されます-

{"message":"New movie created.","location":"/movies/105"}

これがムービーオブジェクトに追加されたかどうかをテストするには、 /movies/105 のget要求を再度実行します。 次の応答が表示されます-

{"id":105,"name":"Toy story","year":"1995","rating":"8.5"}

次に、PUTおよびDELETEルートを作成します。

PUTルート

PUTルートは、POSTルートとほぼ同じです。 更新/作成されるオブジェクトのIDを指定します。 次の方法でルートを作成します。

router.put('/:id', function(req, res){
  //Check if all fields are provided and are valid:
   if(!req.body.name ||
      !req.body.year.toString().match(/^[0-9]{4}$/g) ||
      !req.body.rating.toString().match(/^[0-9]\.[0-9]$/g) ||
      !req.params.id.toString().match(/^[0-9]{3,}$/g)){

      res.status(400);
      res.json({message: "Bad Request"});
   } else {
     //Gets us the index of movie with given id.
      var updateIndex = movies.map(function(movie){
         return movie.id;
      }).indexOf(parseInt(req.params.id));

      if(updateIndex === -1){
        //Movie not found, create new
         movies.push({
            id: req.params.id,
            name: req.body.name,
            year: req.body.year,
            rating: req.body.rating
         });
         res.json({message: "New movie created.", location: "/movies/" + req.params.id});
      } else {
        //Update existing movie
         movies[updateIndex] = {
            id: req.params.id,
            name: req.body.name,
            year: req.body.year,
            rating: req.body.rating
         };
         res.json({message: "Movie id " + req.params.id + " updated.",
            location: "/movies/" + req.params.id});
      }
   }
});

このルートは、上記の表で指定された機能を実行します。 オブジェクトが存在する場合、新しい詳細でオブジェクトを更新します。 存在しない場合は、新しいオブジェクトを作成します。 ルートを確認するには、次のcurlコマンドを使用します。 これにより、既存のムービーが更新されます。 新しいムービーを作成するには、IDを存在しないIDに変更するだけです。

curl -X PUT --data "name = Toy%20story&year = 1995&rating = 8.5"
http://localhost:3000/movies/101

応答

{"message":"Movie id 101 updated.","location":"/movies/101"}

ルートを削除

次のコードを使用して、削除ルートを作成します。 −

router.delete('/:id', function(req, res){
   var removeIndex = movies.map(function(movie){
      return movie.id;
   }).indexOf(req.params.id);//Gets us the index of movie with given id.

   if(removeIndex === -1){
      res.json({message: "Not found"});
   } else {
      movies.splice(removeIndex, 1);
      res.send({message: "Movie id " + req.params.id + " removed."});
   }
});

他のルートをチェックしたのと同じ方法でルートをチェックします。 削除に成功すると(たとえばid 105)、次の出力が得られます-

{message: "Movie id 105 removed."}

最後に、 movies.js ファイルは次のようになります。

var express = require('express');
var router = express.Router();
var movies = [
   {id: 101, name: "Fight Club", year: 1999, rating: 8.1},
   {id: 102, name: "Inception", year: 2010, rating: 8.7},
   {id: 103, name: "The Dark Knight", year: 2008, rating: 9},
   {id: 104, name: "12 Angry Men", year: 1957, rating: 8.9}
];
router.get('/:id([0-9]{3,})', function(req, res){
   var currMovie = movies.filter(function(movie){
      if(movie.id == req.params.id){
         return true;
      }
   });

   if(currMovie.length == 1){
      res.json(currMovie[0])
   } else {
      res.status(404); //Set status to 404 as movie was not found
      res.json({message: "Not Found"});
   }
});
router.post('/', function(req, res){
  //Check if all fields are provided and are valid:
   if(!req.body.name ||
      !req.body.year.toString().match(/^[0-9]{4}$/g) ||
      !req.body.rating.toString().match(/^[0-9]\.[0-9]$/g)){
      res.status(400);
      res.json({message: "Bad Request"});
   } else {
      var newId = movies[movies.length-1].id+1;
      movies.push({
         id: newId,
         name: req.body.name,
         year: req.body.year,
         rating: req.body.rating
      });
      res.json({message: "New movie created.", location: "/movies/" + newId});
   }
});

router.put('/:id', function(req, res) {
  //Check if all fields are provided and are valid:
   if(!req.body.name ||
      !req.body.year.toString().match(/^[0-9]{4}$/g) ||
      !req.body.rating.toString().match(/^[0-9]\.[0-9]$/g) ||
      !req.params.id.toString().match(/^[0-9]{3,}$/g)){
      res.status(400);
      res.json({message: "Bad Request"});
   } else {
     //Gets us the index of movie with given id.
      var updateIndex = movies.map(function(movie){
         return movie.id;
      }).indexOf(parseInt(req.params.id));

      if(updateIndex === -1){
        //Movie not found, create new
         movies.push({
            id: req.params.id,
            name: req.body.name,
            year: req.body.year,
            rating: req.body.rating
         });
         res.json({
            message: "New movie created.", location: "/movies/" + req.params.id});
      } else {
        //Update existing movie
         movies[updateIndex] = {
            id: req.params.id,
            name: req.body.name,
            year: req.body.year,
            rating: req.body.rating
         };
         res.json({message: "Movie id " + req.params.id + " updated.",
            location: "/movies/" + req.params.id});
      }
   }
});

router.delete('/:id', function(req, res){
   var removeIndex = movies.map(function(movie){
      return movie.id;
   }).indexOf(req.params.id);//Gets us the index of movie with given id.

   if(removeIndex === -1){
      res.json({message: "Not found"});
   } else {
      movies.splice(removeIndex, 1);
      res.send({message: "Movie id " + req.params.id + " removed."});
   }
});
module.exports = router;

これでREST APIが完成しました。 このシンプルなアーキテクチャスタイルとExpressを使用して、はるかに複雑なアプリケーションを作成できるようになりました。