53
37

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Expressで簡易的にAPIを作成する

Last updated at Posted at 2018-10-22

概要

簡易的なAPIを作りたいなって人向けです。

使うモジュールをインストールする

yarn add express body-parser faker

テストデータの作成

createUser.js
const faker = require("faker/locale/ja");
const fs = require("fs");

const users = [];
const maxLength = 100, max = 85, min = 16;

for (let i = 0; i < maxLength; i++) {
  const name = faker.name.lastName() + ' ' + faker.name.firstName();
  users.push({
    id: i + 1,
    name: name,
    age: Math.floor(Math.random() * (max + 1 - min) ) + min
  })
}

fs.writeFile('users.json', JSON.stringify(users), () => {
  console.log("users.jsonを作成しました");
});

土台を作る

server.js
const express = require("express");
const app = express();
const fs = require("fs");
const bodyParser = require("body-parser");
const users = require("./users.json");

const port = 3000;

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

app.listen(port, () => {
  console.log("server is running");
})

一覧の取得

app.get('/users/', (req, res) => {
  res.json(users);
});

1つだけ取得

app.get('/users/:id', (req, res) => {
  const id = req.params.id;
  const user = users.filter(user => {
    return user.id == id;
  });
  res.json(user);
}):

保存する

app.post('/users/', (req, res) => {
  const userID = users.map(user => {
     return user.id;
  });
  users.push({
     id: Math.max(...userID) + 1,
     name: req.body.name,
     age: req.body.age
  });
  fs.writeFile('users.json', JSON.stringify(users), () => {
    res.json(users);
  });
});

更新する

app.put('/users/:id', (req, res) => {
  const id = req.params.id,
        name = req.body.name,
        age = req.body.age;
  
  // 更新しないデータ
  const newData = users.filter(user => {
    return user.id != id;
  });

  // 更新するデータ
  const alterUser = users.filter(user => {
    return user.id == id;
  })

  alterUser[0].name = name;
  alterUser[0].age = age;
  newData.push(alterUser[0]);

  fs.writeFile('users.json', JSON.stringify(newData), () => {
    res.json(newData);
  });
});

削除する

app.delete('/users/:id', (req, res) => {
  const id = req.params.id;

  const newData = users.filter(user => {
    return user.id != id;
  });

  fs.writeFile('users.json', JSON.stringify(newData), () => {
    res.json(newData);
  });
})

package.jsonの作成

npm init -y

npm-scriptsを編集する

package.json
  :
"scripts": {
  "start": "node createUser.js && node server.js"
}
  :

まとめ・反省点

もっと簡単にAPIを作成したいなって方は、json-serverがオススメです。

回りくどい方法じゃなく、NedblowdbなどのJSON型のデータベースを使えばよかった。

53
37
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
53
37

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?