Testing REST API
การทดสอบ REST API ของระบบ จะต้องรู้ก่อนว่า ระบบของเรา มีการเปิด API ะไรให้ใช้งานบ้าง แล้วการใช้งานของ API แต่ละตัวเป็นอย่างไร มีการรับส่งข้อมูลอย่างไร ถ้า API นั้นทำงานสำเร็จ จะต้องตอบกลับมาอย่างไร หรือ ถ้ามีความผิดพลาดเกิดขึ้น จะตอบกลับมาอย่างไร
ยกตัวอย่างเช่น เรากำลังเขียน API ให้กับตู้เย็น ซึ่ง API ของตู้เย็นที่มีการเปิดให้ใช้งาน มีดังนี้
- ดูรายชื่อของที่มีอยู่ในตู้
- ค้นหาของที่อยู่ในตู้จากชื่อ
- เพิ่มของเข้าไปในตู้
- นำของออกจากตู้
- แก้ไขรายละเอียดของที่อยู่ในตู้
ในแต่ละ API มีรายละเอียดการเรียกใช้งาน ดังนี้
ดูรายชื่อของที่มีอยู่ในตู้
Endpoint: /items Method: GET
Request:
- body: None
- header: Content-type=applcation/json
Response:
- success
- status code: 200
- body:
[ { "id": "1", "name": "Banana" }, { "id": "2", "name": "Watermelon" } ]
ค้นหาของที่อยู่ในตู้ จากชื่อ
Endpoint: /item/name/{name} Method: GET
Request:
- body: None
- header: Content-type=applcation/json
Response:
- success
- status code: 200
- body:
{ "id": "1", "name": "Banana" }
- fail case - Item not found
- status code: 404
- body:
{ "message": "Item with name 'banaba' not found" }
เพิ่มของเข้าตู้
Endpoint: /item/name/{name} Method: POST
Request:
- body:
{ "name": "Sushi" }
- header: Content-type=applcation/json
Response:
- success
- status code: 200
- body:
{ "id": "4", "name": "Sushi" }
นำของออกจากตู้
Endpoint: /item/id/{id} Method: DELETE
Request:
- body: None
- header: Content-type=applcation/json
Response:
- success
- status code: 200
- body: None
Fail - Item not found
- status code: 404
body:
{ "message": "Item with name 'id' not found" }
แก้ไขรายละเอียดของที่อยู่ในตู้
Endpoint: /item Method: PUT
Request:
- body:
{ "id": "1" "name": "Orange" }
- header: Content-type=applcation/json
Response:
- success
- status code: 200
- body: None