09 - ทดสอบ API ด้วย Postman
เป้าหมายของบท
Section titled “เป้าหมายของบท”บทนี้จะใช้ Postman ทดสอบ User API ที่สร้างไว้ เพื่อให้ผู้อ่านฝึกดู request, response, status code และ JSON body อย่างเป็นระบบ
สร้าง Collection
Section titled “สร้าง Collection”ใน Postman ให้สร้าง collection ชื่อ:
Backend APIจากนั้นเพิ่ม folder:
01 Basic02 Users In Memoryสร้าง Environment
Section titled “สร้าง Environment”สร้าง environment ชื่อ:
Backend API Localเพิ่ม variable:
baseUrl = http://localhost:8080เวลาเรียก API ให้ใช้:
{{baseUrl}}/api/v1/usersแทนการพิมพ์ URL เต็มทุกครั้ง
Request 1: Health
Section titled “Request 1: Health”GET {{baseUrl}}/healthExpected response:
OKRequest 2: Create User
Section titled “Request 2: Create User”POST {{baseUrl}}/api/v1/usersHeader:
Content-Type: application/jsonBody:
{ "username": "john", "email": "john@example.com"}Expected response:
{ "id": 1, "username": "john", "email": "john@example.com"}Request 3: Get Users
Section titled “Request 3: Get Users”GET {{baseUrl}}/api/v1/usersExpected response:
[ { "id": 1, "username": "john", "email": "john@example.com" }]Request 4: Get User By Id
Section titled “Request 4: Get User By Id”GET {{baseUrl}}/api/v1/users/1Request 5: Delete User
Section titled “Request 5: Delete User”DELETE {{baseUrl}}/api/v1/users/1Expected response:
User deletedวิธีอ่านผลลัพธ์
Section titled “วิธีอ่านผลลัพธ์”ให้ดู 3 จุด:
- Status code
- Response body
- Console log ของ Spring Boot
ถ้า request ไม่ผ่าน อย่าดูแค่ Postman ให้กลับไปดู log ใน terminal ที่รัน Spring Boot ด้วย
Error ที่ควรลอง
Section titled “Error ที่ควรลอง”ลองเรียก:
GET {{baseUrl}}/api/v1/users/999ตอนนี้อาจได้ 500 Internal Server Error เพราะเรายังไม่ได้ทำ exception handling นี่เป็นเรื่องตั้งใจ เพราะภาค 4 จะสอนเปลี่ยน error นี้ให้เป็น 404 Not Found
ทดสอบด้วย curl
Section titled “ทดสอบด้วย curl”ถ้าไม่ใช้ Postman สามารถใช้ curl:
curl {{baseUrl}}/healthแต่ใน terminal จริงให้แทน {{baseUrl}} เป็น URL:
curl http://localhost:8080/healthPOST JSON บน Windows PowerShell:
curl -Method POST http://localhost:8080/api/v1/users ` -ContentType "application/json" ` -Body '{"username":"john","email":"john@example.com"}'Checkpoint
Section titled “Checkpoint”บทนี้ถือว่าสำเร็จเมื่อ collection มี request เหล่านี้:
- Health
- Create User
- Get Users
- Get User By Id
- Delete User
แบบฝึกหัดท้ายบท
Section titled “แบบฝึกหัดท้ายบท”เพิ่ม request สำหรับ PUT /api/v1/users/{id} ถ้าคุณทำแบบฝึกหัดจากบทก่อนหน้าแล้ว