REST vs GraphQL in Go

When to Use Which

Web
Use REST for simple, cacheable resources and GraphQL for flexible, complex data fetching where clients control the response shape.

Use REST for simple, cacheable resources and GraphQL for complex, nested data needs where clients control the response shape. REST uses standard HTTP methods and URL paths, while GraphQL uses a single endpoint with query strings to fetch exactly what you need.

// REST: Standard HTTP handler for a specific resource path
func getUserHandler(w http.ResponseWriter, r *http.Request) {
    userID := r.URL.Query().Get("id")
    user := db.FindUser(userID)
    json.NewEncoder(w).Encode(user)
}

// GraphQL: Single endpoint handling all queries via a schema
func graphqlHandler(w http.ResponseWriter, r *http.Request) {
    // Parse query string to determine fields and depth
    query := r.URL.Query().Get("query")
    result := executeQuery(query, db)
    json.NewEncoder(w).Encode(result)
}