Express.jsを使ったREST APIの作成
はじめに
Node.jsのフレームワークであるExpress.jsを使用すると、簡単にREST APIを作成できます。本記事では、基本的なREST APIの作成方法を解説します。
環境設定
1. Node.jsのインストール
Node.jsがインストールされていない場合は、公式サイトからダウンロードしてください。
2. 新しいプロジェクトの作成
ターミナルで以下のコマンドを実行し、新しいプロジェクトを作成します。
mkdir my-rest-api
cd my-rest-api
npm init -y
3. Expressのインストール
npm install express
REST APIの実装
1. 基本的なExpressサーバーの作成
まず、server.js
というファイルを作成し、基本的なサーバーを実装します。
const express = require('express');
const app = express();
const PORT = 3000;
app.use(express.json());
app.get('/', (req, res) => {
res.send('Welcome to Express REST API!');
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
2. CRUDエンドポイントの作成
以下のコードを追加し、ユーザー情報を管理するAPIを作成します。
let users = [
{ id: 1, name: "Taro" },
{ id: 2, name: "Jiro" }
];
// ユーザー一覧を取得
app.get('/users', (req, res) => {
res.json(users);
});
// ユーザーを追加
app.post('/users', (req, res) => {
const newUser = { id: users.length + 1, name: req.body.name };
users.push(newUser);
res.status(201).json(newUser);
});
// ユーザーを更新
app.put('/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (user) {
user.name = req.body.name;
res.json(user);
} else {
res.status(404).send('User not found');
}
});
// ユーザーを削除
app.delete('/users/:id', (req, res) => {
users = users.filter(u => u.id !== parseInt(req.params.id));
res.status(204).send();
});
APIのテスト
Postmanやcurl
を使ってAPIをテストできます。
# ユーザー一覧を取得
curl -X GET http://localhost:3000/users
# 新しいユーザーを追加
curl -X POST http://localhost:3000/users -H "Content-Type: application/json" -d '{"name":"Saburo"}'
# ユーザーを更新
curl -X PUT http://localhost:3000/users/1 -H "Content-Type: application/json" -d '{"name":"Taro Updated"}'
# ユーザーを削除
curl -X DELETE http://localhost:3000/users/2
まとめ
本記事では、Express.jsを使用した基本的なREST APIの作成方法を解説しました。次回は、データベースと連携する方法について紹介します。
https://rb.gy/3jou1h
https://rb.gy/c676x6
https://rb.gy/zxg0ue
https://rb.gy/81ytn0
Top comments (0)