RESTful
- การตั่งชื่อต้องใช้ nouns อย่าใช้ verbs
- อย่าใช้ GET ในการแก้ไขข้อมูลใดๆ ทั่งสิ้น หรือสร้างข้อมูลใหม่
- ให้ใช้คำ nouns แบบพหูพจน์ (plural nouns) (ใช้ /authors แทน /author)
- ใช้ Standard HTTP Method (GET: ดึงข้อมูล, POST: สร้างข้อมูล, PUT: อัพเดตข้อมูล, DELETE: ลบข้อมูล)
- เปิดใช้งาน overriding HTTP method
$.ajax({
url: "http://localhost/api/book/2",
type: "POST",
data: JSON.stringify(data),
headers: {
"Content-Type": "application/json",
"X-HTTP-Method-Override": "PUT" },
})- ใช้ sub name ในการเชื่อมความสัมพันธ์ของของมูล (GET /books/2/author/10 ดึงข้อมูลผู้แต่งหมายแลข 10 ที่หนังสือหมายเลข 2)
- ควรระบุ content-type ของการสื่อสารด้วยทั่ง clienกt และ server
- อย่าลืมระบุ version API ด้วย
- ใช้ HTTP Status Codes คู่ไปกับการใช้ Message ในการจัดการกับ Error ขอระบบ
- 200 OK – [GET]
- 201 CREATED – [POST/PUT/PATCH]
- 204 NO CONTENT – [DELETE]
- 304 NOT MODIFIED
- 400 INVALID REQUEST – [POST/PUT/PATCH]
- 401 UNAUTHORIZED
- 403 FORBIDDEN
- 404 NOT FOUND
- 500 INTERNAL SERVER ERROR- ในการดึงข้อมูลที่ซับซ้อน หรือมี state เยอะๆ ให้ทำ Query String ด้วย GET (GET /api/v1/books?fields=name,price,author,type,categories&sort=asc&page=1&limit=10)
credit
- HTTP GET
This retrieves a resource from the server. It is idempotent. Multiple identical requests return the same result.
- HTTP PUT
This updates or Creates a resource. It is idempotent. Multiple identical requests will update the same resource.
- HTTP POST
This is used to create new resources. It is not idempotent, making two identical POST will duplicate the resource creation.
- HTTP DELETE
This is used to delete a resource. It is idempotent. Multiple identical requests will delete the same resource.
- HTTP PATCH
The PATCH method applies partial modifications to a resource.
- HTTP HEAD
The HEAD method asks for a response identical to a GET request but without the response body.
- HTTP CONNECT
The CONNECT method establishes a tunnel to the server identified by the target resource.
- HTTP OPTIONS
This describes the communication options for the target resource.
- HTTP TRACE
This performs a message loop-back test along the path to the target resource.