[A-00107]ExpressでRestAPIを作成する
expressを使用してサーバーサイドを実装してRestAPIを立ててみたいと思います。
参考文献はこちら
https://zenn.dev/oreo2990/articles/b4719c78aa0832
https://qiita.com/ryome/items/16659012ed8aa0aa1fac
・専用のディレクトリを作成・初期化する
npmで初期化する専用のディレクトリを作成します。
mkdir express_test1 && chmod 777 express_test1npm init --yexpress_test1ディレクトリ直下にpackage.jsonが作成されたことを確認してください。
次にexpressをインストールします。
npm install express --save[–save]オプションで、package.jsonにexpressのバージョン情報を自動追記します。package.jsonは下記のようになります。
{
  "name": "express_test1",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2"
  }
}
・RestAPIを作成する
アプリケーションファイルを作成して下記のようにコードを記載します。
touch api_get.js && chmod 777 api_get.jsconst express = require('express')
const api_app = express()
api_app.listen(8080, () => {
    console.log("Server is Running....")
});
api_app.get('/', (req, res) => {
    res.json({"message": "Nice to meet you!"});
    console.log('Got a Request!')
    res.end();
})上記のAPIを起動してリクエストを投げてみます。コンソール1で起動、コンソール2でリクエストを投げます。
下記はコンソール1で実行してください。
node api_get.jsMacBook-Pro:express_test1$ node api_get.js 
Server is Running....下記はコンソール2で実行してください。
curl -X GET http://localhost:8080/MacBook-Pro:js$ curl -X GET http://localhost:8080/
{"message":"Nice to meet you!"}上記を実行するとコンソール1に[Got a Request!]とログが追記されます。
MacBook-Pro:express_test1$ node api_get.js 
Server is Running....
Got a Request!・各メソッドの処理を作成してみる
RestAPIの基本的なメソッドであるpost, get, put, deleteを作成してみたいと思います。
const express = require('express')
const api_app = express()
api_app.listen(8080, () => {
    console.log("Server is Running....");
});
// Get Method
api_app.get('/', (req, res) => {
    res.json({"message": "GET Method is executed."});
    console.log('GET!')
    res.end();
});
// Post Method
api_app.post('/', (req, res) => {
    res.json({"message": "POST Method is executed."});
    console.log('POST!');
    res.end();
});
// Put Method
api_app.put('/', (req, res) => {
    res.json({"message": "PUT Method is executed."});
    console.log('PUT!');
    res.end();
});
// Delete Method
api_app.delete('/', (req, res) => {
    res.json({"message": "DELETE Method is executed."});
    console.log('DELETE!');
    res.end();
});
実際に動かしてみると下記のようになります。
MacBook-Pro:~$ curl -X GET http://localhost:8080/
{"message":"GET Method is executed."}
MacBook-Pro:~$ curl -X POST http://localhost:8080/
{"message":"POST Method is executed."}
MacBook-Pro:~$ curl -X PUT http://localhost:8080/
{"message":"PUT Method is executed."}
MacBook-Pro:~$ curl -X DELETE http://localhost:8080/
{"message":"DELETE Method is executed."}MacBook-Pro:express_test1$ node restapi.js 
Server is Running....
GET!
POST!
PUT!
DELETE!上記の通り、expressで簡単なRestAPIを作成しましたが、非常に少ないコードで実装できる事がわかりました。
いちいちjavaなどで作成しなくともこちらで十分ですね。
コメントを残す