Senior
Is it normal to use the same endpoint for adding friends and viewing friends, but with different methods? How will it work?
sobes.tech AI
Answer from AI
Yes, it is a common practice in REST API — to use the same endpoint with different HTTP methods for different operations. For example, for the resource /friends:
GET /friends— to get the list of friends of the user.POST /friends— to add a new friend.
This approach aligns with REST principles, where the method defines the action, and the URL defines the resource. The server distinguishes requests by method and performs the corresponding logic. This simplifies the API structure and makes it more predictable.
Example in Go using net/http:
func friendsHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
// Logic to get friends
w.Write([]byte("Friends list"))
case http.MethodPost:
// Logic to add a friend
w.Write([]byte("Friend added"))
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
func main() {
http.HandleFunc("/friends", friendsHandler)
http.ListenAndServe(":8080", nil)
}