...

/

Developing a REST API Server

Developing a REST API Server

Learn how the REST API server can be developed step by step.

Overview

Web services that use the representational state transfer (REST) format provide a flexible and agnostic way of exchanging data between computers and different programming languages. Many applications and services on the internet use this clear and concise format to expose their data to other applications. Using Go to interact with REST APIs opens the door to a large number of services that provide many resources for our command-line tools. It allows us to create flexible tools that were previously challenging to develop by integrating information from multiple sources.

In this chapter, we’ll apply the concepts to design a command-line tool that connects to a REST API using Go’s net/http package. We’ll explore more advanced concepts such as the http.Client and http.Request types to fine-tune specific connection parameters like headers and timeouts, and we’ll use the encoding/json package to parse JSON response data.

We need access to a REST API to explore how to build a CLI that works with one. We could use one of the many web services available on the internet. But because these services can change, there’s no guarantee they’ll be available when you’re completing this course. Instead, we’ll design and develop our own REST API server so we have a local server to test. This is also a good opportunity to explore the concepts of dealing with network and HTTP requests using Go.

Finally, we’ll use several testing techniques to test our API server as well as our command-line client application, including local tests, simulated responses, mock servers, and integration tests.

Let’s begin by developing the REST API server.

Build an API

Let’s build an API for our command-line tool to talk to. To save some time, we’ll create a REST API server that exposes data from the to-do API. It will let users view, add, and modify to-do items using HTTP methods. We’ll reuse the code we developed before by importing the package todo from the module interacting/todo.

Then, we initialize the Go module for this project:

Press + to interact
cd usercode/apis/todoServer
$go mod init todoServer

Next, we need to add the usercode/interacting/todo module dependency to the go.mod file. In a normal workflow, with a module that’s available in a public repository, we don’t need to take additional actions. Go ...