How to Build a REST API with Fiber in Go

Web
Use Fiber to define routes with a lightweight router, bind JSON payloads to structs, and return responses using the built-in `c.JSON()` method.

Use Fiber to define routes with a lightweight router, bind JSON payloads to structs, and return responses using the built-in c.JSON() method. It handles middleware, error handling, and high-performance request processing out of the box, making it ideal for microservices.

Here is a minimal example of a user management API:

package main

import (
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/cors"
	"github.com/gofiber/fiber/v2/middleware/logger"
)

type User struct {
	Name  string `json:"name"`
	Email string `json:"email"`
}

func main() {
	app := fiber.New()

	// Middleware for logging and CORS
	app.Use(logger.New())
	app.Use(cors.New())

	// GET /users - Return a static list
	app.Get("/users", func(c *fiber.Ctx) error {
		users := []User{
			{Name: "Alice", Email: "alice@example.com"},
			{Name: "Bob", Email: "bob@example.com"},
		}
		return c.JSON(users)
	})

	// POST /users - Create a new user
	app.Post("/users", func(c *fiber.Ctx) error {
		var user User
		if err := c.BodyParser(&user); err != nil {
			return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Invalid input"})
		}
		return c.Status(fiber.StatusCreated).JSON(user)
	})

	// GET /users/:id - Get specific user (mock implementation)
	app.Get("/users/:id", func(c *fiber.Ctx) error {
		id := c.Params("id")
		return c.JSON(fiber.Map{"id": id, "message": "User details would be fetched here"})
	})

	// Start server on :3000
	app.Listen(":3000")
}

To run this, ensure you have the Fiber module installed:

go mod init my-api
go get github.com/gofiber/fiber/v2
go run main.go

Test the endpoints using curl:

# Get all users
curl http://localhost:3000/users

# Create a user
curl -X POST http://localhost:3000/users \
  -H "Content-Type: application/json" \
  -d '{"name": "Charlie", "email": "charlie@example.com"}'

# Get user by ID
curl http://localhost:3000/users/123

Fiber's context (c) provides methods like BodyParser for automatic JSON unmarshaling and Params for extracting route parameters. For production, add database integration within the handler functions and implement proper error middleware to centralize logging and error responses. The framework's non-blocking nature ensures it scales well under high concurrency compared to heavier alternatives.