Completing the REST API Server
Complete the REST API server and connect it with the to-do API.
We'll cover the following...
Structure of the API server
With the general structure of our API server ready, let’s add the CRUD operations for the to-do list.
Our to-do REST API supports these operations.
To-do REST API Operations
Method | URL | Description |
GET | /todo | Retrieve all to-do items |
GET | /todo/{number} | Retrieve a to-do item {number} |
POST | /todo | Create a to-do item |
PATCH | /todo/{number}?complete | Mark a to-do item {number} as completed |
DELETE | /todo/{number} | Delete a to-do item {number} |
The REST API serves all to-do-related content using the /todo
URL path. It
handles different operations based on the HTTP method, path, and parameters.
The path might include a number for operations that act on a single to-do item.
For example, to delete the third item from the list, the user sends a DELETE
request to the URL path /todo/3
.
REST API responds
The first two GET operations on the list retrieve items from the list. For this example, the REST API responds with JSON data. Besides the to-do items, we want to include additional information with the response, such as the current date and the number of results included. A sample response for multiple items looks like this:
{"results": [{"Task": "Task Number 1","Done": true,"CreatedAt": "2019-10-13T11:16:00.756817096-04:00","CompletedAt": "2019-10-13T21:25:30.008877148-04:00"},{"Task": "Task Number 2","Done": false,"CreatedAt": "2019-10-14T15:55:48.273514272-04:00","CompletedAt": "0001-01-01T00:00:00Z"}],"date": 1575922413,"total_results": 2}
Creating the todoResponse.go
file
The response includes the field results
that wraps the to-do list. Let’s create a
new type todoResponse
to wrap the list. In the same directory where we have
main.go
, we create a new file todoResponse.go
. We add the package
definition and the import
section.
For this file, we’re using the following packages:
encoding/json
to customize JSON output.time
to work with time functions.interacting/todo
.
package mainimport ("encoding/json""time""todo")
Then, we add the new struct
type todoResponse
to wrap the todo.List
type:
type todoResponse struct {Results todo.List `json:"results"`}
In this struct
type, the field name Results
is exported with the first character of
its name capitalized. This ensures that it’s exported as JSON when using
Go’s JSON encoding. We’re using a struct
tag to change the name to results
in
the resulting JSON as it’s common to have all fields in JSON spelled with
lowercase characters.
Using struct
tags is the best way to do simple JSON ...