URI Naming
URI คือชื่อของ resource การตั้งชื่อที่สอดคล้องกันทำให้ developer เดา endpoint ตัวถัดไปได้ถูกโดยไม่ต้องเปิด docs และนั่นคือคำชมสูงสุดที่ API หนึ่งตัวจะได้รับ
แนวปฏิบัติ
หัวข้อที่มีชื่อว่า “แนวปฏิบัติ”- คำนาม ไม่ใช่คำกริยา —
/articlesไม่ใช่/getArticlesตัว method คือคำกริยา - collection เป็นพหูพจน์ —
/articlesคือ collection ส่วน/articles/42คือหนึ่ง item ในนั้น เลือกใช้พหูพจน์แล้วยึดไว้ให้ตลอด - ตัวพิมพ์เล็กคั่นด้วยขีดกลาง —
/blog-postsไม่ใช่/blogPostsหรือ/Blog_Postspath นั้นโดยจิตวิญญาณแล้วแยกตัวพิมพ์เล็กใหญ่ จงเก็บให้เป็นตัวพิมพ์เล็กเพื่อเลี่ยงเรื่องเซอร์ไพรส์ - ID อยู่ใน path ไม่ใช่ใน query —
/articles/42ไม่ใช่/articles?id=42query string มีไว้สำหรับ filter collection ไม่ใช่ระบุตัว item - ไม่มีนามสกุลไฟล์ —
/articles/42ไม่ใช่/articles/42.jsonให้ใช้ headerAcceptในการเจรจารูปแบบ (format negotiation) - แนวปฏิบัติเรื่อง trailing slash — เลือกว่าจะมีหรือไม่มีและทำให้สอดคล้องกัน (API ส่วนใหญ่ละไว้)
ดีกับไม่ดี
หัวข้อที่มีชื่อว่า “ดีกับไม่ดี”GET /articles # collectionGET /articles/42 # one itemGET /articles/42/comments # that item's commentsGET /articles?status=draft # filtered collection
# Avoid:GET /getArticlesGET /article/42 # inconsistent singularGET /articles/42.jsonGET /articles?articleId=42 # identity belongs in the path| URI Convention | ดี | ไม่ดี |
|---|---|---|
| Plural noun | /users, /orders | /user, /getOrders |
| Lowercase + hyphen | /blog-posts, /line-items | /blogPosts, /Blog_Posts |
| Hierarchy แสดง ownership | /users/\{id\}/orders | /getUserOrders?userId=\{id\} |
| ไม่มี verb ใน URI | /orders/\{id\}/cancellation | /cancelOrder/\{id\} |
ข้อผิดพลาดที่พบบ่อย
หัวข้อที่มีชื่อว่า “ข้อผิดพลาดที่พบบ่อย”ผสม Naming Convention อาการ:
GET /userProfilesและGET /order-itemsใน API เดียวกัน- developer ต้องจำว่า endpoint ไหนใช้ convention ไหน
- กำหนด convention เดียวแล้วยึดตลอด — ส่วนมากใช้ plural lowercase
ใส่ Version ผิดที่ อาการ:
/users/v2— version อยู่ตรงกลาง URI/v1/users/v2/profile— version ซ้อนกัน- version อยู่ต้น URI เสมอ:
/v1/users/\{id\}/profile
💡 ตัวอย่างจากของจริง
GitHub API:
/repos(plural),/issues,/pulls,/commits— consistent plural/repos/\{owner\}/\{repo\}/git/refs— hierarchy ชัดเจนStripe API:
/payment_intents,/payment_methods,/setup_intents- ใช้ snake_case สม่ำเสมอทั้ง API