API Handlers
In General, API handlers are the functions that handle incoming HTTP requests and return responses. A request can be a GET, POST, PUT, DELETE, or any other HTTP method. In this tutorial, we will focus on the GET and POST methods, which are the most commonly used methods for interacting with APIs.
Forms is a way of thinking about the way you're interacting your API, much similar to how you would think about forms in a web application.
Or even physical forms over the counter at a post office.
When you want to submit data over the counter, you fill out a form with the required information and submit it to the clerk.
In the same way, you can think of POST API forms as a way of submitting data to your API.
This is especially useful when you want to set required fields in complex scenarios.
In a similar way a counter would respond to with a standard receipt, your API should respond with a standard data format that can be
thought of as a form too, where certain fields may be hidden from the end user.
Creating a Contact Form
Coming Soon...
POST Handler
Post Contact Handler
func Post(c echo.Context) error {
f := &models.ContactForm{}
if err := c.Bind(f); err != nil {
return helpers.Error(c, constants.ERROR_BINDING_BODY, err)
}
if err := helpers.Validate(f); err != nil {
return c.JSON(http.StatusBadRequest, handlers.ValidationErrors(err))
}
m := f.MapToModel()
if err := m.Save(); err != nil {
return helpers.Error(c, err, nil)
}
return c.JSON(http.StatusOK, handlers.Success(m.MapToForm()))
}
GET Handler
Get Contacts Handler
func Index(c echo.Context) error {
ms, err := models.ContactModel().FindAll()
if err != nil {
return helpers.Error(c, err, nil)
}
var payload []*models.ContactForm
for _, m := range ms {
f := m.MapToForm()
payload = append(payload, f)
}
return c.JSON(http.StatusOK, handlers.Success(payload))
}