Skip to content

09 - ทดสอบ API ด้วย Postman

บทนี้จะใช้ Postman ทดสอบ User API ที่สร้างไว้ เพื่อให้ผู้อ่านฝึกดู request, response, status code และ JSON body อย่างเป็นระบบ

ใน Postman ให้สร้าง collection ชื่อ:

Backend API

จากนั้นเพิ่ม folder:

01 Basic
02 Users In Memory

สร้าง environment ชื่อ:

Backend API Local

เพิ่ม variable:

baseUrl = http://localhost:8080

เวลาเรียก API ให้ใช้:

{{baseUrl}}/api/v1/users

แทนการพิมพ์ URL เต็มทุกครั้ง

GET {{baseUrl}}/health

Expected response:

OK
POST {{baseUrl}}/api/v1/users

Header:

Content-Type: application/json

Body:

{
"username": "john",
"email": "john@example.com"
}

Expected response:

{
"id": 1,
"username": "john",
"email": "john@example.com"
}
GET {{baseUrl}}/api/v1/users

Expected response:

[
{
"id": 1,
"username": "john",
"email": "john@example.com"
}
]
GET {{baseUrl}}/api/v1/users/1
DELETE {{baseUrl}}/api/v1/users/1

Expected response:

User deleted

วิธีอ่านผลลัพธ์

Section titled “วิธีอ่านผลลัพธ์”

ให้ดู 3 จุด:

  1. Status code
  2. Response body
  3. Console log ของ Spring Boot

ถ้า request ไม่ผ่าน อย่าดูแค่ Postman ให้กลับไปดู log ใน terminal ที่รัน Spring Boot ด้วย

ลองเรียก:

GET {{baseUrl}}/api/v1/users/999

ตอนนี้อาจได้ 500 Internal Server Error เพราะเรายังไม่ได้ทำ exception handling นี่เป็นเรื่องตั้งใจ เพราะภาค 4 จะสอนเปลี่ยน error นี้ให้เป็น 404 Not Found

ถ้าไม่ใช้ Postman สามารถใช้ curl:

Terminal window
curl {{baseUrl}}/health

แต่ใน terminal จริงให้แทน {{baseUrl}} เป็น URL:

Terminal window
curl http://localhost:8080/health

POST JSON บน Windows PowerShell:

Terminal window
curl -Method POST http://localhost:8080/api/v1/users `
-ContentType "application/json" `
-Body '{"username":"john","email":"john@example.com"}'

บทนี้ถือว่าสำเร็จเมื่อ collection มี request เหล่านี้:

  • Health
  • Create User
  • Get Users
  • Get User By Id
  • Delete User

แบบฝึกหัดท้ายบท

Section titled “แบบฝึกหัดท้ายบท”

เพิ่ม request สำหรับ PUT /api/v1/users/{id} ถ้าคุณทำแบบฝึกหัดจากบทก่อนหน้าแล้ว