π Building a REST API in Go: A Step-by-Step Guide
HARISHKUMAR N
Posted on October 5, 2024
Table Of Contents
- Introduction
- Setting Up the Project
- Creating the Todo Model
- Implementing the CRUD Operations
- Testing the API
- Conclusion
Introduction
Building a REST API can seem daunting, but with Go, itβs straightforward. In this guide, weβll create a simple Todo REST API that allows users to manage their tasks efficiently.
Setting Up the Project
To start, make sure you have Go installed on your machine. Create a new directory for your project and initialize a new Go module:
mkdir todorest
cd todorest
go mod init todorest
Install the required packages:
go get github.com/gin-gonic/gin
Creating the Todo Model
First, we need to define our Todo model. Create a new file called models.go
:
package models
type Todo struct {
ID int `json:"id"`
Title string `json:"title"`
Status string `json:"status"`
}
Implementing the CRUD Operations
Create Todo
To create a new todo item, add the following handler in your main file:
func CreateTodo(c *gin.Context) {
var todo models.Todo
if err := c.ShouldBindJSON(&todo); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
return
}
result, err := config.DB.Exec("INSERT INTO todos (title, status) VALUES (?, ?)", todo.Title, todo.Status)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Unable to create todo"})
return
}
id, _ := result.LastInsertId()
todo.ID = int(id)
c.JSON(http.StatusCreated, todo)
}
Get Todos
To fetch all todo items, implement the following handler:
func GetTodos(c *gin.Context) {
rows, err := config.DB.Query("SELECT id, title, status FROM todos")
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Unable to fetch todos"})
return
}
defer rows.Close()
var todos []models.Todo
for rows.Next() {
var todo models.Todo
if err := rows.Scan(&todo.ID, &todo.Title, &todo.Status); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error scanning todo"})
return
}
todos = append(todos, todo)
}
c.JSON(http.StatusOK, todos)
}
Update Todo
To update an existing todo item, you can use:
func UpdateTodo(c *gin.Context) {
id := c.Param("id")
var todo models.Todo
if err := c.ShouldBindJSON(&todo); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
return
}
_, err := config.DB.Exec("UPDATE todos SET title = ?, status = ? WHERE id = ?", todo.Title, todo.Status, id)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Unable to update todo"})
return
}
c.JSON(http.StatusOK, todo)
}
Delete Todo
To delete a todo item, implement the following function:
func DeleteTodo(c *gin.Context) {
id := c.Param("id")
_, err := config.DB.Exec("DELETE FROM todos WHERE id = ?", id)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Unable to delete todo"})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Todo deleted"})
}
Testing the API
To test your API, you can use tools like Postman or CURL. Make sure your server is running, and send requests to the appropriate endpoints.
View the Todo REST API on GitHub
Conclusion
You have successfully built a Todo REST API in Go! You can extend its functionality by adding more features like authentication, filtering, and pagination.
For further reading, check out the official Go documentation for more details on the Go language and its capabilities.
Posted on October 5, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.