0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Go言語で kintone REST API から データを取得する

Posted at

Go言語からkintone REST API を叩いて、kintoneアプリのフィールド情報を取得するサンプルです。

APIは下記参照
https://developer.cybozu.io/hc/ja/articles/204783170#anchor_getform_fields

環境

  • go version go1.14.2 darwin/amd64
  • Mac

設定ファイル

GoDotEnvライブラリを利用。
.envファイルにkintone接続情報を設定します。
https://github.com/joho/godotenv

サンプルコード

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"

	"github.com/joho/godotenv"
)

func main() {
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file")
	}
	ba, _ := fetchFieldsJson(os.Getenv("APP"), os.Getenv("SUB_DOMAIN"), os.Getenv("API_TOKEN"))
	var out bytes.Buffer
	if err := json.Indent(&out, ba, "", "  "); err != nil {
		log.Fatal("Error json indent", err)
	}
	out.WriteTo(os.Stdout)
}


func fetchFieldsJson(appid string, subdomain string, apitoken string) ([]byte, error) {
	client := &http.Client{}
	type Body struct {
		App string `json:"app"`
	}
	data := Body{appid}
	body, err := json.Marshal(data)
	if err != nil {
		log.Fatal("Error JSON Encode")
	}
	req, err := http.NewRequest("GET", "https://"+subdomain+".cybozu.com/k/v1/app/form/fields.json", bytes.NewReader(body))
	if err != nil {
		log.Fatal("Error request")
	}
	req.Header.Add("X-Cybozu-API-Token", apitoken)
	req.Header.Add("Content-Type", "application/json")
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal("Error client")
	}
	defer resp.Body.Close()
	fmt.Println(resp.Status)
	ba, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal("Error read")
	}
	return ba, err
}

参考

Go言語からkintoneのレコード取得の方法は、下記記事が参考になります。
kintone REST API について (GET編)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?