Search⌘ K
AI Features

Developing the Initial Client for the REST API

Explore building the initial Go client for a to-do REST API using Cobra. Learn how to structure the CLI app, handle HTTP requests, manage API responses, and implement subcommands such as list, add, and delete. Understand error handling and configure client timeouts for reliable communication.

Overview

With the to-do REST API server in place, we can now build a command-line application that uses the API to query, add, complete, and delete items.

First, we initialize a Cobra application in this directory:

Shell
cobra init --pkg-name todoClient

Note: This command assumes we have a Cobra configuration file in our home directory. We can also initialize the application without the configuration file. Cobra uses its default options, so the LICENSE and comments in our code will be different from these examples.

Then, we add a requirement to go.mod to ensure we’re using Cobra v1.1.3, which is what this course’s code uses. Again, we can use a later version, but we might need to change the code a bit. Run go mod tidy to download the required dependencies:

Shell
go mod edit --require github.com/spf13/cobra@v1.1.3
go mod tidy

This command-line application will have five subcommands:

  • add: Followed by a task string, adds a new task to the list.
  • list: Lists all items in the list.
  • complete: Completes item number n.
  • del: Deletes item number n from the list.
  • view: Views details about item number n.

Let’s develop the skeleton for the application and implement the first operation, list, to list all items. We’ll implement the other operations later.

Updating the cmd/root.go file

We ...