Notes Creation API

Learn to implement an API to create a new record in the database on form submission.

The new note form page

We will start with creating an HTML form to enter the details of a new note.

Route

First, let’s create the route of the /notes/new page. In the routers/router.go file, create a new entry:

Press + to interact
package routers
import (
"beego_notes/controllers"
beego "github.com/beego/beego/v2/server/web"
)
func init() {
beego.Router("/", &controllers.MainController{})
beego.Router("/notes", &controllers.NotesController{}, "get:NotesIndex")
beego.Router("/notes/new", &controllers.NotesController{}, "get:NotesNewForm")
}

We define the route for the new note form in line 12. The route is /notes/new. The action for the route is get:NotesNewForm. This means that the NotesNewForm() method in the NotesController controller will be executed when the route is requested.

The notes form handler

Now, we will implement the handler function for the above route in the file controllers/notes.go.

Press + to interact
package controllers
import (
"beego_notes/models"
beego "github.com/beego/beego/v2/server/web"
)
// NotesController operations for Notes
type NotesController struct {
beego.Controller
}
func (c *NotesController) NotesIndex() {
// Get all notes
notes := models.NotesGetAll()
c.Data["notes"] = notes
c.TplName = "notes/index.tpl"
}
func (c *NotesController) NotesNewForm() {
c.TplName = "notes/new.tpl"
}

In this ...