keyboard_tab Skip to content
Web Development 101

ตอนที่ 9: Rest API

ทำ Mock API

สารบัญ

Workshop ทำอะไรกันบ้าง

เราจะมาลอง Mock API เพื่อให้ได้ผลลัพธ์ที่ถูกต้องออกมาก่อน (ก่อนที่เราจะไปต่อ Database ในอันต่อไป)

Mock API คือ การทำ API ตาม specs ที่กำหนดโดยจะต้องการจำลอง response ตามที่เราต้องการออกมาก่อน

เราจะทำ API ออกมาทั้งหมด 5 path คือ

  1. GET /users สำหรับ get users ทั้งหมดที่บันทึกเข้าไปออกมา
  2. POST /users สำหรับการสร้าง users ใหม่บันทึกเข้าไป
  3. GET /users/:id สำหรับการดึง users รายคนออกมา
  4. PUT /users/:id สำหรับการแก้ไข users รายคน (ตาม id ที่บันทึกเข้าไป)
  5. DELETE /users/:id สำหรับการลบ users รายคน (ตาม id ที่บันทึกเข้าไป)

code พื้นฐานทั้งหมดข้อ 1-5 เราจะเพิ่มส่วนตรงกลางนี้กัน

javascript
const express = require('express')
const app = express()
const bodyParser = require('body-parser')

app.use(bodyParser.json())

// ใช้ users array เป็นตัวหลักในการเก็บข้อมูล
let users = []
let counter = 1

/* เพิ่มเฉพาะ code ตรงนี้เข้าไป */

app.listen(8000, () => {
  console.log('Server started on port 8000')
})

พาลง nodemon

ลง nodemon

plain
npm install nodemon  --save-dev

ลงถูกต้อง package.json จะออกมาหน้าตาแบบนี้

plain
{
  ... (ย่อ),
  "dependencies": {
    "body-parser": "^1.20.2",
    "express": "^4.18.2"
  },
  "devDependencies": {
    "nodemon": "^3.0.1" <-- จะมี nodemon โผล่มา
  }
}

และใช้คำสั่งนี้ในการรันแทน

plain
npx nodemon index.js 

1. GET /users สำหรับ get users ทั้งหมดที่บันทึกเข้าไปออกมา

javascript
...

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

...

2. POST /users สำหรับการสร้าง users ใหม่บันทึกเข้าไป

javascript
...

app.post('/users', (req, res) => {
  const data = req.body

  const newUser = {
    id: counter
    firstname: data.firstname,
    lastname: data.lastname,
    age: data.age
  }

  counter += 1

  users.push(newUser)

  // Server ตอบกลับมาว่าเพิ่มแล้วเรียบร้อย
  res.status(201).json({ message: 'User created successfully', user: newUser })
})

...

3. GET /users/:id สำหรับการดึง users รายคนออกมา

javascript

...
// Route handler for getting a user by their ID
app.get('/users/:id', (req, res) => {
  const id = req.params.id

  // Find the user with the given ID
  const user = users.find((user) => user.id === id)

  // Check if the user with the specified ID exists
  if (user) {
    res.json(user)
  } else {
    res.status(404).json({ error: 'User not found' })
  }
})

...

4. PUT /users/:id สำหรับการแก้ไข users รายคน (ตาม id ที่บันทึกเข้าไป)

javascript

...
app.put('/users/:id', (req, res) => {
  const id = req.params.id
  const data = req.body

  // Find the user with the given ID
  const user = users.find((user) => user.id === id)

  // Check if the user with the specified ID exists
  if (user) {
    // Update the user properties with the new data
    user.firstname = data.firstname || user.firstname
    user.lastname = data.lastname || user.lastname
    user.age = data.age || user.age

    res.json({ message: 'User updated successfully', user: user })
  } else {
    res.status(404).json({ error: 'User not found' })
  }
})
...

5. DELETE /users/:id สำหรับการลบ users รายคน (ตาม id ที่บันทึกเข้าไป)

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

  // Check if the index is valid
  if (index >= 0 && index < users.length) {
    // Remove the user at the specified index
    const deletedUser = users.splice(index, 1)[0]
    res.json({ message: 'User deleted successfully', user: deletedUser })
  } else {
    res.status(404).json({ error: 'User not found' })
  }
})
...

Full code ทั้งหมดดูได้ที่นี่ https://github.com/mikelopster/web101/tree/main/sessions/chapter-9

บทต่อไปเราจะมาต่อฐานข้อมูลกัน

Mikelopster

แชร์และแบ่งปันเรื่องราวสาระน่ารู้ © 2026