Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 39 ยท Projects and Practice

Project: A To-Do REST API

Build a complete to-do REST API with Gin and GORM: layout, models, validation, CRUD, filtering and pagination, token auth, tests and a runnable stand-in.

Time to put the chapters together. In this project you design a small but realistic REST API for personal to-do lists: users sign up, log in, and manage only their own tasks, with filtering, pagination, validation and tests. You will see how the pieces from earlier lessons fit into one program.

Gin and GORM do not run in the in-page runner. The project's Gin code is shown read-only, file by file, and a complete runnable stand-in built on net/http reproduces the same routes, status codes and JSON so you can watch the behaviour end to end.

Requirements

  • POST /api/register and POST /api/login return a token.
  • All /api/todos routes need Authorization: Bearer <token> and only touch the caller's own rows.
  • GET /api/todos?done=false&page=1&per_page=20 lists with filter and pagination.
  • POST, GET /:id, PATCH /:id, DELETE /:id complete the CRUD set.
  • Title is required (1 to 200 characters). Errors have one JSON shape: {"error": "message"}.

Project layout

TEXT
todo-api/
  cmd/server/main.go        # wiring, graceful shutdown
  internal/
    config/config.go        # env loading (see Docker and Deployment)
    model/model.go          # User, Todo
    store/store.go          # TodoStore interface + GORM implementation
    handler/todo.go         # handlers, DTOs
    middleware/auth.go      # Bearer token -> user ID
    router/router.go        # SetupRouter(deps)
  Dockerfile

This is the structure from Project Structure: main only wires things; everything testable lives under internal.

Models and DTOs

Never bind request JSON directly into database models: a client could set user_id or id. Use separate request structs (DTOs).

Go
// internal/model/model.go
type Todo struct {
	ID        uint      `gorm:"primaryKey" json:"id"`
	UserID    uint      `gorm:"index;not null" json:"-"`
	Title     string    `gorm:"size:200;not null" json:"title"`
	Done      bool      `gorm:"not null;default:false" json:"done"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

// internal/handler/todo.go
type createTodoRequest struct {
	Title string `json:"title" binding:"required,min=1,max=200"`
}

type updateTodoRequest struct {
	Title *string `json:"title" binding:"omitempty,min=1,max=200"`
	Done  *bool   `json:"done"`
}

Pointer fields in the update DTO distinguish "not sent" (nil) from "sent as false". That is what makes PATCH partial.

The handlers

Every query is scoped by the user ID from the token, so one user can never read or change another's data. When a row is not yours, answer 404, not 403, so IDs are not revealed.

Go
func (h *TodoHandler) List(c *gin.Context) {
	userID := c.GetUint("user_id")

	q := store.ListQuery{UserID: userID, Page: pageParam(c), PerPage: perPageParam(c)}
	if v := c.Query("done"); v != "" {
		done, err := strconv.ParseBool(v)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "done must be true or false"})
			return
		}
		q.Done = &done
	}

	todos, total, err := h.store.List(c.Request.Context(), q)
	if err != nil {
		slog.Error("list todos", "error", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"data": todos, "page": q.Page, "per_page": q.PerPage, "total": total})
}

func (h *TodoHandler) Update(c *gin.Context) {
	var req updateTodoRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	todo, err := h.store.Update(c.Request.Context(), c.GetUint("user_id"), idParam(c), req)
	switch {
	case errors.Is(err, store.ErrNotFound):
		c.JSON(http.StatusNotFound, gin.H{"error": "todo not found"})
	case err != nil:
		c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
	default:
		c.JSON(http.StatusOK, todo)
	}
}

The store applies the filter and paging with the GORM calls from Queries, Filtering and Pagination, always with Where("user_id = ?", userID). Authentication uses the middleware from JWT Authentication and puts user_id in the context. The router wires it all together:

Go
func SetupRouter(d Deps) *gin.Engine {
	r := gin.New()
	r.Use(gin.Recovery(), RequestLogger(d.Log))

	api := r.Group("/api")
	api.POST("/register", d.Auth.Register)
	api.POST("/login", RateLimit(rate.Every(6*time.Second), 5), d.Auth.Login)

	todos := api.Group("/todos", RequireAuth(d.Tokens))
	todos.GET("", d.Todos.List)
	todos.POST("", d.Todos.Create)
	todos.GET("/:id", d.Todos.Get)
	todos.PATCH("/:id", d.Todos.Update)
	todos.DELETE("/:id", d.Todos.Delete)
	return r
}

A runnable stand-in

The program below is the whole API in one file: in-memory storage, a toy token table instead of JWT, the same routes and the same status codes. Read the output as a transcript of a client session.

Go The to-do API end to end

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Look at three details. The anonymous call gets 401. Maya's attempt to modify task 3 (Omar's) gets 404, not 403. The list for Maya never shows Omar's task. Those are the authorization rules that a real test suite must pin down.

Testing the API

Reuse the techniques from Testing Gin Handlers. A good first suite for this project:

  • Auth: every /api/todos route returns 401 without a token and with a malformed token.
  • Ownership: user B cannot read, update or delete user A's todo (expect 404).
  • Validation: a table test over empty, too long and malformed titles.
  • Filtering and paging: seed 25 rows, request per_page=10&page=3 and expect 5 items and total=25.
  • PATCH semantics: sending only done leaves the title unchanged.

Extensions to try

  1. Add due_date and GET /api/todos?overdue=true.
  2. Add tags with a many-to-many relationship (see Relationships and Preloading).
  3. Soft delete with gorm.DeletedAt and a restore endpoint.
  4. Package it with the Dockerfile from Docker and Deploying a Gin App.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use separate request structs instead of binding JSON into the GORM model?

    DTOs expose only the fields a client may set (mass assignment protection).
  2. 2. Why does PATCH use pointer fields such as *bool?

    With a plain bool, an omitted field and false look the same.
  3. 3. User A requests user B's todo by ID. Which answer avoids leaking that the ID exists?

    Scoping every query by user ID and returning 404 reveals nothing about other users' data.
  4. 4. Where should user_id come from for every todo query?

    Only the verified credential can be trusted to identify the caller.

Summary

  • Layer the app: config, model, store interface, handlers, middleware, router; main only wires.
  • Use DTOs, pointer fields for partial updates, and one error JSON shape.
  • Scope every query by the authenticated user and answer 404 for rows that are not theirs.
  • Test auth, ownership, validation, paging and PATCH semantics.

Next: Project: A URL Shortener