Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
37
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

Organization

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

概要

簡易的な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型のデータベースを使えばよかった。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
37
Help us understand the problem. What are the problem?