-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.go
More file actions
94 lines (87 loc) · 2.59 KB
/
api.go
File metadata and controls
94 lines (87 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// Copyright (c) 2020 Joshua Yoder
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE.txt file.
// Go wrapper for USDA NASS API
// See the USDA NASS QuickStats API docs for more usage details:
// https://quickstats.nass.usda.gov/api
package nass
import (
"strings"
"net/http"
"net/url"
"encoding/json"
"log"
)
// Represents a client to the USDA
type Client struct {
BaseURL string // Base URL for USDA NASS
Key string // API key
}
// Create a new client bearing a given key
func NewClient(key string) *Client {
baseURL := "http://quickstats.nass.usda.gov/api"
client := Client{
BaseURL: baseURL,
Key: key,
}
return &client
}
// Return all possible values of a given parameter
func (c Client) ParamValues(param string) []string {
resp, err := http.Get(c.BaseURL + "/get_param_values/" +
"?key=" + c.Key +
"¶m=" + param)
if err != nil {
log.Fatal(err)
}
var data map[string][]string
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&data)
if err != nil {
log.Fatal(err)
}
return data[param]
}
// Return number of records that will be retrieved by a given query
func (c Client) count_query(query Query) int {
var params strings.Builder
for k, v := range query.Params {
params.WriteString("&" + k + "=" + url.QueryEscape(v))
}
resp, err := http.Get(c.BaseURL + "/get_counts/" +
"?key=" + c.Key +
params.String())
if err != nil {
log.Fatal(err)
}
var data map[string]int
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&data)
if err != nil {
log.Fatal(err)
}
return data["count"]
}
// Return the result of the query
func (c Client) call_query(query Query) interface{} {
var params strings.Builder
for k, v := range query.Params {
params.WriteString("&" + k + "=" + url.QueryEscape(v))
}
resp, err := http.Get(c.BaseURL + "/api_GET/" +
"?key=" + c.Key +
params.String())
if err != nil {
log.Fatal(err)
}
var data map[string][]interface{}
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&data)
if err != nil {
log.Fatal(err)
}
if len(data["error"]) != 0 {
log.Fatal("API Error: " + data["error"][0].(string))
}
return data["data"]
}