Golang / GoLang Production Patterns and Web Standards Interview Questions
How do you document a Go REST API and maintain an OpenAPI specification?
Documentation is a first-class concern for production APIs. Go projects adopt either code-first (generate OpenAPI from code annotations) or design-first (write OpenAPI spec, generate server stubs) approaches.
// Approach 1: code-first with swaggo/swag annotations // go install github.com/swaggo/swag/cmd/swag@latest // swag init -g cmd/server/main.go â generates docs/swagger.json // @Summary Get user by ID // @Description Returns a single user by their unique identifier // @Tags users // @Accept json // @Produce json // @Param id path int true "User ID" // @Success 200 {object} User // @Failure 404 {object} ProblemDetail // @Failure 500 {object} ProblemDetail // @Router /users/{id} [get] func getUserHandler(w http.ResponseWriter, r *http.Request) { // handler implementation } // Approach 2: design-first with oapi-codegen // Write openapi.yaml first, then generate: // oapi-codegen -package api -generate types,server openapi.yaml > api/api.gen.go // Generated interface â implement this in your handler type StrictServerInterface interface { GetUser(ctx context.Context, request GetUserRequestObject) (GetUserResponseObject, error) CreateUser(ctx context.Context, request CreateUserRequestObject) (CreateUserResponseObject, error) } // Serve Swagger UI and spec mux.Handle("GET /docs/", http.StripPrefix("/docs/", swaggerui.Handler("openapi.yaml"))) mux.Handle("GET /openapi.yaml", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "openapi.yaml") })
Design-first advantages: the API contract is established before implementation — frontend and backend teams can work in parallel. Type safety is enforced by generated code. Breaking changes are visible in spec diffs before any code runs.
More Related questions...