Yes, it’s a good practice to define a type (struct) on your Go backend to encapsulate the response, even if you’re only returning the id. This makes your API response self-documenting and avoids ambiguity. Here’s why and how to do it:
Why Define a Struct for the Response?
- Clarity: A named struct (e.g.,
CreateGroupResponse) explicitly defines what the API returns, making it easier for frontend developers (and future you) to understand the response structure.
- Future-Proofing: If you later decide to return additional fields (e.g.,
name, createdAt), you can add them to the struct without breaking existing clients.
- Type Safety: Both your backend and frontend can enforce type constraints (e.g.,
id must be a string).
Backend Implementation (Go)
Define a struct for the response and encode it:
// Define the response struct
type CreateGroupResponse struct {
ID string `json:"id"` // Use JSON tag to specify the key name
}
// In your handler function:
func createGroupHandler(w http.ResponseWriter, r *http.Request) {
// ... (logic to create the group and get the new ID)
newGroupId := "group-123" // Replace with actual ID generation
response := CreateGroupResponse{
ID: newGroupId,
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated) // 201 Created
json.NewEncoder(w).Encode(response) // Encode the struct
}
Frontend TypeScript Type
Define a matching type on the frontend to mirror the backend response:
// Define a type for the response
type CreateGroupResponse = {
id: string; // Explicitly type the ID
};
// Update your API function to use this type:
createGroup: (groupData: CreateGroupInput): Promise<CreateGroupResponse> =>
apiRequest<CreateGroupResponse>('/api/groups', 'POST', groupData),
Alternative: Return Just the Raw ID (Not Recommended)
If you don’t define a struct and return the raw string directly:
Backend (Go):
newGroupId := "group-123"
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(newGroupId) // Encodes as the raw string "group-123"
Frontend (TypeScript):
createGroup: (groupData: CreateGroupInput): Promise<string> =>
apiRequest<string>('/api/groups', 'POST', groupData),