REST API for User Struct in Go
Here's a REST API design for a User struct with CRUD operations, following REST conventions:
API Endpoints
Resource Naming
- Use plural nouns for collections (e.g.,
/users) - this is the more common convention
- Singular nouns are typically used only when referring to a singleton resource
Endpoints
-
Create a User
POST /users
- Request body:
{
"name": "John Doe",
"photo": "profile.jpg"
}
- Response (201 Created):
{
"id": 1,
"name": "John Doe",
"photo": "profile.jpg"
}
-
Retrieve a User
-
Retrieve All Users
GET /users
- Response (200 OK):
[
{
"id": 1,
"name": "John Doe",
"photo": "profile.jpg"
},
{
"id": 2,
"name": "Jane Smith",
"photo": "avatar.png"
}
]
-
Update a User (Full Update)
PUT /users/{id}
- Request body:
{
"name": "Johnathan Doe",
"photo": "new_profile.jpg"
}
- Response (200 OK):
{
"id": 1,
"name": "Johnathan Doe",
"photo": "new_profile.jpg"
}
-
Partial Update a User
PATCH /users/{id}
- Request body (update just name):
{
"name": "Johnny Doe"
}
- Or update just photo:
{
"photo": "updated.jpg"
}
- Response (200 OK):
{
"id": 1,
"name": "Johnny Doe",
"photo": "updated.jpg"
}
Go Implementation Example
package main
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Photo string `json:"photo"`
}
var users = make(map[int]User)
var lastID = 0
func main() {
http.HandleFunc("/users", handleUsers)
http.HandleFunc("/users/", handleUser)
http.ListenAndServe(":8080", nil)
}
func handleUsers(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
getAllUsers(w, r)
case "POST":
createUser(w, r)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
func handleUser(w http.ResponseWriter, r *http.Request) {
idStr := r.URL.Path[len("/users/"):]
id, err := strconv.Atoi(idStr)
if err != nil {
http.Error(w, "Invalid user ID", http.StatusBadRequest)
return
}
switch r.Method {
case "GET":
getUser(w, r, id)
case "PUT":
updateUser(w, r, id)
case "PATCH":
patchUser(w, r, id)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
// Handler implementations would go here...
Best Practices
-
Plural vs. Singular: As mentioned, use plural nouns (/users) for collections. This is the more widely adopted convention.
-
HTTP Status Codes:
- 200 OK for successful GET, PUT, PATCH
- 201 Created for successful POST
- 204 No Content for successful DELETE
- 400 Bad Request for invalid input
- 404 Not Found when resource doesn't exist
-
Content-Type: Always set Content-Type: application/json in responses
-
Error Responses: Provide consistent error responses with details when something goes wrong
Would you like me to expand on any particular part of this implementation?