Go: how to create a REST API for a To-Do list from scratch

Go: how to create a REST API for a To-Do list from scratch

In this article, we will explore how to create a simple REST API in Go to manage a To-Do List We will use the Go programming language to create a web server that will allow users to add, edit, delete and get tasks from their list.

REST APIs (Application Programming Interfaces) provide a standardized way for applications to communicate with each other over the HTTP protocol. In this article, we will explore how to create a simple REST API in Go to manage a To-Do List We will use the Go programming language to create a web server that will allow users to add, edit, delete and get tasks from their list.

Prerequisites

To follow this tutorial, you need to be familiar with basic Go programming concepts and have Go installed on your system. If you are not familiar with the Go language, you can find useful resources in the official Go documentation.

Make sure you have a working Go development environment before proceeding.

Create a structure for the activities

To begin, let's define a structure that represents a task in our ToDo List. Open your code editor and create a file called main.go. Insert the following code:


package main

import (
	"encoding/json"
	"fmt"
	"net/http"
)

type Task struct {
	ID   int    `json:"id"`
	Text string `json:"text"`
}

var tasks []Task

func main() {
	http.HandleFunc("/tasks", tasksHandler)
	http.ListenAndServe(":8080", nil)
}

In this step, we created a Task struct that represents a task with an ID and descriptive text. We also created a tasks variable to store tasks.

Implement CRUD operations

Now, let's implement CRUD (Create, Read, Update, Delete) operations to manage the activity list. Add the following code to the main.go file:


func tasksHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == http.MethodGet {
		getTasksHandler(w, r)
	} else if r.Method == http.MethodPost {
		addTaskHandler(w, r)
	} else if r.Method == http.MethodPut {
		updateTaskHandler(w, r)
	} else if r.Method == http.MethodDelete {
		deleteTaskHandler(w, r)
	} else {
		w.WriteHeader(http.StatusMethodNotAllowed)
	}
}

func getTasksHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(tasks)
}

func addTaskHandler(w http.ResponseWriter, r *http.Request) {
	var newTask Task
	err := json.NewDecoder(r.Body).Decode(&newTask)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	newTask.ID = len(tasks) + 1
	tasks = append(tasks, newTask)
	w.WriteHeader(http.StatusCreated)
}

func updateTaskHandler(w http.ResponseWriter, r *http.Request) {
	var updatedTask Task
	err := json.NewDecoder(r.Body).Decode(&updatedTask)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	taskID := updatedTask.ID
	if taskID <= 0 || taskID > len(tasks) {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	tasks[taskID-1].Text = updatedTask.Text
	w.WriteHeader(http.StatusOK)
}

func deleteTaskHandler(w http.ResponseWriter, r *http.Request) {
	taskIDStr := r.URL.Query().Get("id")
	taskID, err := strconv.Atoi(taskIDStr)
	if err != nil || taskID <= 0 || taskID > len(tasks) {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	tasks = append(tasks[:taskID-1], tasks[taskID:]...)
	w.WriteHeader(http.StatusOK)
}

In this step, we have implemented the functions to get the activity list, add a new activity and handle HTTP requests.

In the implementation of the update operation (updateTaskHandler), we are decoding the data sent in the request to get the updated task. We then check that the activity ID is valid and then update the corresponding activity text in the activity list.

In the implementation of the delete operation (deleteTaskHandler), we are getting the task ID from the request query and converting it to an integer. Next, we remove the corresponding activity from the activity list.

Make sure you have imported the "strconv" package at the top of your main.go file to convert strings to integers.

Running the application

Now that we have the basic CRUD operations in place, we can run our application. Open the terminal in your project directory and type the following command:

go run main.go

The server should start on port 8080. You can now interact with the API using tools like curl or a user interface like Postman.

Conclusion

In this article, we learned how to create a simple REST API in Go to manage a ToDo List. We defined a structure to represent the activities, implemented basic CRUD operations and created a web server to handle HTTP requests. This tutorial only provides a starting point, but from here you can expand and enhance the API by adding features like user authentication, data persistence, and more task management operations.