Using Request Body of String JSON for Google APIs with googleapis of golang


This is a sample script for directly using the request body of the string JSON for Google APIs with googleapis of golang.

At googleapis for golang, when Google API is used, it is required to create the request body like this sample script. I have several contacts for creating about such request body. I thought that such script might be a bit difficult for users. I thought that when the string JSON object is directly used for this, it might be useful. So I would like to introduce about this. When this was useful for your situation, I’m glad.

Sample script

This is a sample script for changing the background color of a cell of “A1” on the Google Spreadsheet using the batchUpdate method in Sheets API.

spreadsheetId := "###"  // Please set the Spreadsheet ID.

// Please set the JSON object of the request body as the string.
str := `{
	"updateCells": {
	  "range": {
		"sheetId": 0,
		"startRowIndex": 0,
		"endRowIndex": 1,
		"startColumnIndex": 0,
		"endColumnIndex": 1
	  "rows": [
		  "values": [
			  "userEnteredFormat": {
				"backgroundColor": {
				  "red": 1,
				  "green": 0,
				  "blue": 0
	  "fields": "userEnteredFormat.backgroundColor"

var req sheets.Request
json.Unmarshal([]byte(str), &req)
requestBody := &sheets.BatchUpdateSpreadsheetRequest{
    Requests: []*sheets.Request{&req},
srv, _ := sheets.New(client)
res, err := srv.Spreadsheets.BatchUpdate(spreadsheetId, requestBody).Do()
if err != nil {
fmt.Printf("%#v\n", res)
  • When above script is used, the string JSON can be parsed and it can be used as the request body for srv.Spreadsheets.BatchUpdate().
  • In this case, all requests for the batchUpdate method in Sheets API can be parsed.
  • And also, this method can be used for other Google APIs.