Merge pull request #135 from brendandburns/lb

Add load balancing support to services.
This commit is contained in:
Daniel Smith 2014-06-17 18:40:42 -07:00
commit 246db91cb5
282 changed files with 380401 additions and 122 deletions

4
.gitignore vendored
View File

@ -15,3 +15,7 @@
# Go test binaries
*.test
# Mercurial files
**/.hg
**/.hg*

View File

@ -0,0 +1,8 @@
{
"id": "example",
"port": 8000,
"labels": {
"name": "nginx"
},
"createExternalLoadBalancer": true
}

View File

@ -1,5 +1,5 @@
{
"id": "example2",
"id": "example",
"port": 8000,
"labels": {
"name": "nginx"

View File

@ -75,7 +75,7 @@ gcutil addinstance ${MASTER_NAME}\
--image ${IMAGE} \
--tags ${MASTER_TAG} \
--network ${NETWORK} \
--service_account_scopes="storage-ro" \
--service_account_scopes="storage-ro,compute-rw" \
--automatic_restart \
--metadata_from_file startup-script:${KUBE_TEMP}/master-start.sh &

View File

@ -17,7 +17,7 @@ PATH=/sbin:/usr/sbin:/bin:/usr/bin
DESC="The Kubernetes API server"
NAME=apiserver
DAEMON=/usr/local/bin/apiserver
DAEMON_ARGS=""
DAEMON_ARGS="-cloud_provider gce "
DAEMON_LOG_FILE=/var/log/$NAME.log
PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME

View File

@ -24,6 +24,7 @@ import (
"net"
"strconv"
"github.com/GoogleCloudPlatform/kubernetes/pkg/cloudprovider"
"github.com/GoogleCloudPlatform/kubernetes/pkg/master"
"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
)
@ -32,6 +33,7 @@ var (
port = flag.Uint("port", 8080, "The port to listen on. Default 8080.")
address = flag.String("address", "127.0.0.1", "The address on the local server to listen to. Default 127.0.0.1")
apiPrefix = flag.String("api_prefix", "/api/v1beta1", "The prefix for API requests on the server. Default '/api/v1beta1'")
cloudProvider = flag.String("cloud_provider", "", "The provider for cloud services. Empty string for no provider.")
etcdServerList, machineList util.StringList
)
@ -47,12 +49,27 @@ func main() {
log.Fatal("No machines specified!")
}
var m *master.Master
var cloud cloudprovider.Interface
switch *cloudProvider {
case "gce":
var err error
cloud, err = cloudprovider.NewGCECloud()
if err != nil {
log.Fatal("Couldn't connect to GCE cloud: %#v", err)
}
default:
if len(*cloudProvider) > 0 {
log.Printf("Unknown cloud provider: %s", *cloudProvider)
} else {
log.Print("No cloud provider specified.")
}
}
var m *master.Master
if len(etcdServerList) > 0 {
m = master.New(etcdServerList, machineList)
m = master.New(etcdServerList, machineList, cloud)
} else {
m = master.NewMemoryServer(machineList)
m = master.NewMemoryServer(machineList, cloud)
}
log.Fatal(m.Run(net.JoinHostPort(*address, strconv.Itoa(int(*port))), *apiPrefix))

View File

@ -80,7 +80,7 @@ func fake_kubelet() {
// Starts api services (the master). Never returns.
func api_server() {
m := master.New([]string{*etcd_server}, []string{*kubelet_address})
m := master.New([]string{*etcd_server}, []string{*kubelet_address}, nil)
log.Fatal(m.Run(net.JoinHostPort(*master_address, strconv.Itoa(int(*master_port))), *apiPrefix))
}

View File

@ -1,7 +1,7 @@
{
"id": "frontendController",
"desiredState": {
"replicas": 3,
"replicas": 1,
"replicasInSet": {"name": "frontend"},
"podTemplate": {
"desiredState": {

View File

@ -140,9 +140,10 @@ type ServiceList struct {
// Defines a service abstraction by a name (for example, mysql) consisting of local port
// (for example 3306) that the proxy listens on, and the labels that define the service.
type Service struct {
JSONBase `json:",inline" yaml:",inline"`
Port int `json:"port,omitempty" yaml:"port,omitempty"`
Labels map[string]string `json:"labels,omitempty" yaml:"labels,omitempty"`
JSONBase `json:",inline" yaml:",inline"`
Port int `json:"port,omitempty" yaml:"port,omitempty"`
Labels map[string]string `json:"labels,omitempty" yaml:"labels,omitempty"`
CreateExternalLoadBalancer bool `json:"createExternalLoadBalancer,omitempty" yaml:"createExternalLoadBalancer,omitempty"`
}
// Defines the endpoints that implement the actual service, for example:

View File

@ -190,8 +190,12 @@ func (server *ApiServer) handleREST(parts []string, requestUrl *url.URL, req *ht
server.error(err, w)
return
}
storage.Create(obj)
server.write(200, obj, w)
err = storage.Create(obj)
if err != nil {
server.error(err, w)
} else {
server.write(200, obj, w)
}
return
case "DELETE":
if len(parts) != 2 {

View File

@ -0,0 +1,31 @@
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cloudprovider
// CloudInterface is an abstract, pluggable interface for cloud providers
type Interface interface {
// TCPLoadBalancer returns a balancer interface, or nil if none is supported. Returns an error if one occurs.
TCPLoadBalancer() (TCPLoadBalancer, error)
}
type TCPLoadBalancer interface {
// TODO: Break this up into different interfaces (LB, etc) when we have more than one type of service
TCPLoadBalancerExists(name, region string) (bool, error)
CreateTCPLoadBalancer(name, region string, port int, hosts []string) error
UpdateTCPLoadBalancer(name, region string, hosts []string) error
DeleteTCPLoadBalancer(name, region string) error
}

20
pkg/cloudprovider/doc.go Normal file
View File

@ -0,0 +1,20 @@
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package cloudprovider supplies interfaces and implementations for cloud service providers
package cloudprovider
import ()

164
pkg/cloudprovider/gce.go Normal file
View File

@ -0,0 +1,164 @@
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cloudprovider
import (
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"time"
"code.google.com/p/goauth2/compute/serviceaccount"
compute "code.google.com/p/google-api-go-client/compute/v1"
)
type GCECloud struct {
service *compute.Service
projectID string
zone string
}
func getProjectAndZone() (string, string, error) {
client := http.Client{}
url := "http://metadata/computeMetadata/v1/instance/zone"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return "", "", err
}
req.Header.Add("X-Google-Metadata-Request", "True")
res, err := client.Do(req)
if err != nil {
return "", "", err
}
defer res.Body.Close()
data, err := ioutil.ReadAll(res.Body)
if err != nil {
return "", "", err
}
parts := strings.Split(string(data), "/")
if len(parts) != 4 {
return "", "", fmt.Errorf("Unexpected response: %s", string(data))
}
return parts[1], parts[3], nil
}
func NewGCECloud() (*GCECloud, error) {
projectID, zone, err := getProjectAndZone()
if err != nil {
return nil, err
}
client, err := serviceaccount.NewClient(&serviceaccount.Options{})
if err != nil {
return nil, err
}
svc, err := compute.New(client)
if err != nil {
return nil, err
}
return &GCECloud{
service: svc,
projectID: projectID,
zone: zone,
}, nil
}
func (gce *GCECloud) TCPLoadBalancer() (TCPLoadBalancer, error) {
return gce, nil
}
func makeHostLink(projectID, zone, host string) string {
ix := strings.Index(host, ".")
if ix != -1 {
host = host[:ix]
}
return fmt.Sprintf("https://www.googleapis.com/compute/v1/projects/%s/zones/%s/instances/%s",
projectID, zone, host)
}
func (gce *GCECloud) makeTargetPool(name, region string, hosts []string) (string, error) {
var instances []string
for _, host := range hosts {
instances = append(instances, makeHostLink(gce.projectID, gce.zone, host))
}
pool := &compute.TargetPool{
Name: name,
Instances: instances,
}
_, err := gce.service.TargetPools.Insert(gce.projectID, region, pool).Do()
if err != nil {
return "", err
}
link := fmt.Sprintf("https://www.googleapis.com/compute/v1/projects/%s/regions/%s/targetPools/%s", gce.projectID, region, name)
return link, nil
}
func (gce *GCECloud) waitForRegionOp(op *compute.Operation, region string) error {
pollOp := op
for pollOp.Status != "DONE" {
var err error
time.Sleep(time.Second * 10)
pollOp, err = gce.service.RegionOperations.Get(gce.projectID, region, op.Name).Do()
if err != nil {
return err
}
}
return nil
}
func (gce *GCECloud) TCPLoadBalancerExists(name, region string) (bool, error) {
_, err := gce.service.ForwardingRules.Get(gce.projectID, region, name).Do()
return false, err
}
func (gce *GCECloud) CreateTCPLoadBalancer(name, region string, port int, hosts []string) error {
pool, err := gce.makeTargetPool(name, region, hosts)
if err != nil {
return err
}
req := &compute.ForwardingRule{
Name: name,
IPProtocol: "TCP",
PortRange: strconv.Itoa(port),
Target: pool,
}
_, err = gce.service.ForwardingRules.Insert(gce.projectID, region, req).Do()
return err
}
func (gce *GCECloud) UpdateTCPLoadBalancer(name, region string, hosts []string) error {
var refs []*compute.InstanceReference
for _, host := range hosts {
refs = append(refs, &compute.InstanceReference{host})
}
req := &compute.TargetPoolsAddInstanceRequest{
Instances: refs,
}
_, err := gce.service.TargetPools.AddInstance(gce.projectID, region, name, req).Do()
return err
}
func (gce *GCECloud) DeleteTCPLoadBalancer(name, region string) error {
_, err := gce.service.ForwardingRules.Delete(gce.projectID, region, name).Do()
if err != nil {
return err
}
_, err = gce.service.TargetPools.Delete(gce.projectID, region, name).Do()
return err
}

View File

@ -23,6 +23,7 @@ import (
"github.com/GoogleCloudPlatform/kubernetes/pkg/apiserver"
"github.com/GoogleCloudPlatform/kubernetes/pkg/client"
"github.com/GoogleCloudPlatform/kubernetes/pkg/cloudprovider"
"github.com/GoogleCloudPlatform/kubernetes/pkg/registry"
"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
"github.com/coreos/go-etcd/etcd"
@ -40,29 +41,29 @@ type Master struct {
}
// Returns a memory (not etcd) backed apiserver.
func NewMemoryServer(minions []string) *Master {
func NewMemoryServer(minions []string, cloud cloudprovider.Interface) *Master {
m := &Master{
podRegistry: registry.MakeMemoryRegistry(),
controllerRegistry: registry.MakeMemoryRegistry(),
serviceRegistry: registry.MakeMemoryRegistry(),
}
m.init(minions)
m.init(minions, cloud)
return m
}
// Returns a new apiserver.
func New(etcdServers, minions []string) *Master {
func New(etcdServers, minions []string, cloud cloudprovider.Interface) *Master {
etcdClient := etcd.NewClient(etcdServers)
m := &Master{
podRegistry: registry.MakeEtcdRegistry(etcdClient, minions),
controllerRegistry: registry.MakeEtcdRegistry(etcdClient, minions),
serviceRegistry: registry.MakeEtcdRegistry(etcdClient, minions),
}
m.init(minions)
m.init(minions, cloud)
return m
}
func (m *Master) init(minions []string) {
func (m *Master) init(minions []string, cloud cloudprovider.Interface) {
containerInfo := &client.HTTPContainerInfo{
Client: http.DefaultClient,
Port: 10250,
@ -73,7 +74,7 @@ func (m *Master) init(minions []string) {
m.storage = map[string]apiserver.RESTStorage{
"pods": registry.MakePodRegistryStorage(m.podRegistry, containerInfo, registry.MakeFirstFitScheduler(m.minions, m.podRegistry, m.random)),
"replicationControllers": registry.MakeControllerRegistryStorage(m.controllerRegistry),
"services": registry.MakeServiceRegistryStorage(m.serviceRegistry),
"services": registry.MakeServiceRegistryStorage(m.serviceRegistry, cloud, m.minions),
}
}

View File

@ -17,20 +17,28 @@ package registry
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
"github.com/GoogleCloudPlatform/kubernetes/pkg/apiserver"
"github.com/GoogleCloudPlatform/kubernetes/pkg/cloudprovider"
"github.com/GoogleCloudPlatform/kubernetes/pkg/labels"
)
type ServiceRegistryStorage struct {
registry ServiceRegistry
cloud cloudprovider.Interface
hosts []string
}
func MakeServiceRegistryStorage(registry ServiceRegistry) apiserver.RESTStorage {
return &ServiceRegistryStorage{registry: registry}
func MakeServiceRegistryStorage(registry ServiceRegistry, cloud cloudprovider.Interface, hosts []string) apiserver.RESTStorage {
return &ServiceRegistryStorage{
registry: registry,
cloud: cloud,
hosts: hosts,
}
}
// GetServiceEnvironmentVariables populates a list of environment variables that are use
@ -76,6 +84,25 @@ func (sr *ServiceRegistryStorage) Get(id string) (interface{}, error) {
}
func (sr *ServiceRegistryStorage) Delete(id string) error {
svc, err := sr.Get(id)
if err != nil {
return err
}
if svc.(api.Service).CreateExternalLoadBalancer {
var balancer cloudprovider.TCPLoadBalancer
if sr.cloud != nil {
balancer, err = sr.cloud.TCPLoadBalancer()
if err != nil {
return err
}
}
if balancer != nil {
err = balancer.DeleteTCPLoadBalancer(id, "us-central1")
if err != nil {
return err
}
}
}
return sr.registry.DeleteService(id)
}
@ -87,7 +114,26 @@ func (sr *ServiceRegistryStorage) Extract(body string) (interface{}, error) {
}
func (sr *ServiceRegistryStorage) Create(obj interface{}) error {
return sr.registry.CreateService(obj.(api.Service))
srv := obj.(api.Service)
if srv.CreateExternalLoadBalancer {
var balancer cloudprovider.TCPLoadBalancer
if sr.cloud != nil {
var err error
balancer, err = sr.cloud.TCPLoadBalancer()
if err != nil {
return err
}
}
if balancer != nil {
err := balancer.CreateTCPLoadBalancer(srv.ID, "us-central1", srv.Port, sr.hosts)
if err != nil {
return err
}
} else {
return fmt.Errorf("requested an external service, but no cloud provider supplied.")
}
}
return sr.registry.CreateService(srv)
}
func (sr *ServiceRegistryStorage) Update(obj interface{}) error {

4
third_party/deps.sh vendored
View File

@ -1,11 +1,15 @@
TOP_PACKAGES="
github.com/coreos/go-etcd/etcd
github.com/fsouza/go-dockerclient
code.google.com/p/goauth2/compute/serviceaccount
code.google.com/p/goauth2/oauth
code.google.com/p/google-api-go-client/compute/v1
"
DEP_PACKAGES="
gopkg.in/v1/yaml
bitbucket.org/kardianos/osext
code.google.com/p/google-api-go-client/googleapi
github.com/coreos/go-log/log
github.com/coreos/go-systemd/journal
"

View File

@ -0,0 +1,3 @@
# This source code refers to The Go Authors for copyright purposes.
# The master list of authors is in the main Go distribution,
# visible at http://tip.golang.org/AUTHORS.

View File

@ -0,0 +1,3 @@
# This source code was written by the Go contributors.
# The master list of contributors is in the main Go distribution,
# visible at http://tip.golang.org/CONTRIBUTORS.

View File

@ -0,0 +1,27 @@
Copyright (c) 2009 The goauth2 Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -0,0 +1,22 @@
Additional IP Rights Grant (Patents)
"This implementation" means the copyrightable works distributed by
Google as part of the goauth2 project.
Google hereby grants to You a perpetual, worldwide, non-exclusive,
no-charge, royalty-free, irrevocable (except as stated in this section)
patent license to make, have made, use, offer to sell, sell, import,
transfer and otherwise run, modify and propagate the contents of this
implementation of Go, where such license applies only to those patent
claims, both currently owned or controlled by Google and acquired in
the future, licensable by Google that are necessarily infringed by this
implementation of Go. This grant does not include claims that would be
infringed only as a consequence of further modification of this
implementation. If you or your agent or exclusive licensee institute or
order or agree to the institution of patent litigation against any
entity (including a cross-claim or counterclaim in a lawsuit) alleging
that this implementation of Go or any code incorporated within this
implementation of Go constitutes direct or contributory patent
infringement, or inducement of patent infringement, then any patent
rights granted to you under this License for this implementation of Go
shall terminate as of the date such litigation is filed.

View File

@ -0,0 +1,7 @@
This is the repository for goauth2; an OAuth 2.0 client library for Go.
To contribute, follow the Go Programming Language's contribution process:
http://golang.org/doc/contribute.html
Except use the goauth2 repository instead of the go repo.
Contact Andrew Gerrand <adg@golang.org> with any enquiries.

View File

@ -0,0 +1,42 @@
// Copyright 2013 The goauth2 Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build appengine
package serviceaccount
import (
"time"
"appengine"
"appengine/memcache"
"code.google.com/p/goauth2/oauth"
)
// cache implementss TokenCache using memcache to store AccessToken
// for the application service account.
type cache struct {
Context appengine.Context
Key string
}
func (m cache) Token() (*oauth.Token, error) {
item, err := memcache.Get(m.Context, m.Key)
if err != nil {
return nil, err
}
return &oauth.Token{
AccessToken: string(item.Value),
Expiry: time.Now().Add(item.Expiration),
}, nil
}
func (m cache) PutToken(tok *oauth.Token) error {
return memcache.Set(m.Context, &memcache.Item{
Key: m.Key,
Value: []byte(tok.AccessToken),
Expiration: tok.Expiry.Sub(time.Now()),
})
}

View File

@ -0,0 +1,133 @@
// Copyright 2013 The goauth2 Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build appengine
// The serviceaccount package provides support for making
// OAuth2-authorized HTTP requests from App Engine using service
// accounts.
//
// See: https://developers.google.com/appengine/docs/go/reference#AccessToken
//
// Example usage:
//
// c := appengine.NewContext()
// client, err := serviceaccount.NewClient(c, "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/bigquery")
// if err != nil {
// c.Errorf("failed to create service account client: %q", err)
// return err
// }
// client.Post("https://www.googleapis.com/compute/...", ...)
// client.Post("https://www.googleapis.com/bigquery/...", ...)
//
package serviceaccount
import (
"net/http"
"strings"
"appengine"
"appengine/urlfetch"
"code.google.com/p/goauth2/oauth"
)
// NewClient returns an *http.Client authorized for the
// given scopes with the service account owned by the application.
// Tokens are cached in memcache until they expire.
func NewClient(c appengine.Context, scopes ...string) (*http.Client, error) {
t := &transport{
Context: c,
Scopes: scopes,
Transport: &urlfetch.Transport{
Context: c,
Deadline: 0,
AllowInvalidServerCertificate: false,
},
TokenCache: &cache{
Context: c,
Key: "goauth2_serviceaccount_" + strings.Join(scopes, "_"),
},
}
// Get the initial access token.
if err := t.FetchToken(); err != nil {
return nil, err
}
return &http.Client{
Transport: t,
}, nil
}
// transport is an oauth.Transport with a custom Refresh and RoundTrip implementation.
type transport struct {
*oauth.Token
Context appengine.Context
Scopes []string
Transport http.RoundTripper
TokenCache oauth.Cache
}
func (t *transport) Refresh() error {
// Get a new access token for the application service account.
tok, expiry, err := appengine.AccessToken(t.Context, t.Scopes...)
if err != nil {
return err
}
t.Token = &oauth.Token{
AccessToken: tok,
Expiry: expiry,
}
if t.TokenCache != nil {
// Cache the token and ignore error (as we can always get a new one).
t.TokenCache.PutToken(t.Token)
}
return nil
}
// Fetch token from cache or generate a new one if cache miss or expired.
func (t *transport) FetchToken() error {
// Try to get the Token from the cache if enabled.
if t.Token == nil && t.TokenCache != nil {
// Ignore cache error as we can always get a new token with Refresh.
t.Token, _ = t.TokenCache.Token()
}
// Get a new token using Refresh in case of a cache miss of if it has expired.
if t.Token == nil || t.Expired() {
if err := t.Refresh(); err != nil {
return err
}
}
return nil
}
// cloneRequest returns a clone of the provided *http.Request.
// The clone is a shallow copy of the struct and its Header map.
func cloneRequest(r *http.Request) *http.Request {
// shallow copy of the struct
r2 := new(http.Request)
*r2 = *r
// deep copy of the Header
r2.Header = make(http.Header)
for k, s := range r.Header {
r2.Header[k] = s
}
return r2
}
// RoundTrip issues an authorized HTTP request and returns its response.
func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) {
if err := t.FetchToken(); err != nil {
return nil, err
}
// To set the Authorization header, we must make a copy of the Request
// so that we don't modify the Request we were given.
// This is required by the specification of http.RoundTripper.
newReq := cloneRequest(req)
newReq.Header.Set("Authorization", "Bearer "+t.AccessToken)
// Make the HTTP request.
return t.Transport.RoundTrip(newReq)
}

View File

@ -0,0 +1,172 @@
// Copyright 2013 The goauth2 Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package serviceaccount provides support for making OAuth2-authorized
// HTTP requests from Google Compute Engine instances using service accounts.
//
// See: https://developers.google.com/compute/docs/authentication
//
// Example usage:
//
// client, err := serviceaccount.NewClient(&serviceaccount.Options{})
// if err != nil {
// c.Errorf("failed to create service account client: %q", err)
// return err
// }
// client.Post("https://www.googleapis.com/compute/...", ...)
// client.Post("https://www.googleapis.com/bigquery/...", ...)
//
package serviceaccount
import (
"encoding/json"
"net/http"
"net/url"
"path"
"sync"
"time"
"code.google.com/p/goauth2/oauth"
)
const (
metadataServer = "metadata"
serviceAccountPath = "/computeMetadata/v1/instance/service-accounts"
)
// Options configures a service account Client.
type Options struct {
// Underlying transport of service account Client.
// If nil, http.DefaultTransport is used.
Transport http.RoundTripper
// Service account name.
// If empty, "default" is used.
Account string
}
// NewClient returns an *http.Client authorized with the service account
// configured in the Google Compute Engine instance.
func NewClient(opt *Options) (*http.Client, error) {
tr := http.DefaultTransport
account := "default"
if opt != nil {
if opt.Transport != nil {
tr = opt.Transport
}
if opt.Account != "" {
account = opt.Account
}
}
t := &transport{
Transport: tr,
Account: account,
}
// Get the initial access token.
if _, err := fetchToken(t); err != nil {
return nil, err
}
return &http.Client{
Transport: t,
}, nil
}
type tokenData struct {
AccessToken string `json:"access_token"`
ExpiresIn float64 `json:"expires_in"`
TokenType string `json:"token_type"`
}
// transport is an oauth.Transport with a custom Refresh and RoundTrip implementation.
type transport struct {
Transport http.RoundTripper
Account string
mu sync.Mutex
*oauth.Token
}
// Refresh renews the transport's AccessToken.
// t.mu sould be held when this is called.
func (t *transport) refresh() error {
// https://developers.google.com/compute/docs/metadata
// v1 requires "X-Google-Metadata-Request: True" header.
tokenURL := &url.URL{
Scheme: "http",
Host: metadataServer,
Path: path.Join(serviceAccountPath, t.Account, "token"),
}
req, err := http.NewRequest("GET", tokenURL.String(), nil)
if err != nil {
return err
}
req.Header.Add("X-Google-Metadata-Request", "True")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
d := json.NewDecoder(resp.Body)
var token tokenData
err = d.Decode(&token)
if err != nil {
return err
}
t.Token = &oauth.Token{
AccessToken: token.AccessToken,
Expiry: time.Now().Add(time.Duration(token.ExpiresIn) * time.Second),
}
return nil
}
// Refresh renews the transport's AccessToken.
func (t *transport) Refresh() error {
t.mu.Lock()
defer t.mu.Unlock()
return t.refresh()
}
// Fetch token from cache or generate a new one if cache miss or expired.
func fetchToken(t *transport) (*oauth.Token, error) {
// Get a new token using Refresh in case of a cache miss of if it has expired.
t.mu.Lock()
defer t.mu.Unlock()
if t.Token == nil || t.Expired() {
if err := t.refresh(); err != nil {
return nil, err
}
}
return t.Token, nil
}
// cloneRequest returns a clone of the provided *http.Request.
// The clone is a shallow copy of the struct and its Header map.
func cloneRequest(r *http.Request) *http.Request {
// shallow copy of the struct
r2 := new(http.Request)
*r2 = *r
// deep copy of the Header
r2.Header = make(http.Header)
for k, s := range r.Header {
r2.Header[k] = s
}
return r2
}
// RoundTrip issues an authorized HTTP request and returns its response.
func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) {
token, err := fetchToken(t)
if err != nil {
return nil, err
}
// To set the Authorization header, we must make a copy of the Request
// so that we don't modify the Request we were given.
// This is required by the specification of http.RoundTripper.
newReq := cloneRequest(req)
newReq.Header.Set("Authorization", "Bearer "+token.AccessToken)
// Make the HTTP request.
return t.Transport.RoundTrip(newReq)
}

View File

@ -0,0 +1,2 @@
defaultcc: golang-dev@googlegroups.com
contributors: http://go.googlecode.com/hg/CONTRIBUTORS

View File

@ -0,0 +1,100 @@
// Copyright 2011 The goauth2 Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This program makes a call to the specified API, authenticated with OAuth2.
// a list of example APIs can be found at https://code.google.com/oauthplayground/
package main
import (
"flag"
"fmt"
"io"
"log"
"os"
"code.google.com/p/goauth2/oauth"
)
var (
clientId = flag.String("id", "", "Client ID")
clientSecret = flag.String("secret", "", "Client Secret")
scope = flag.String("scope", "https://www.googleapis.com/auth/userinfo.profile", "OAuth scope")
redirectURL = flag.String("redirect_url", "oob", "Redirect URL")
authURL = flag.String("auth_url", "https://accounts.google.com/o/oauth2/auth", "Authentication URL")
tokenURL = flag.String("token_url", "https://accounts.google.com/o/oauth2/token", "Token URL")
requestURL = flag.String("request_url", "https://www.googleapis.com/oauth2/v1/userinfo", "API request")
code = flag.String("code", "", "Authorization Code")
cachefile = flag.String("cache", "cache.json", "Token cache file")
)
const usageMsg = `
To obtain a request token you must specify both -id and -secret.
To obtain Client ID and Secret, see the "OAuth 2 Credentials" section under
the "API Access" tab on this page: https://code.google.com/apis/console/
Once you have completed the OAuth flow, the credentials should be stored inside
the file specified by -cache and you may run without the -id and -secret flags.
`
func main() {
flag.Parse()
// Set up a configuration.
config := &oauth.Config{
ClientId: *clientId,
ClientSecret: *clientSecret,
RedirectURL: *redirectURL,
Scope: *scope,
AuthURL: *authURL,
TokenURL: *tokenURL,
TokenCache: oauth.CacheFile(*cachefile),
}
// Set up a Transport using the config.
transport := &oauth.Transport{Config: config}
// Try to pull the token from the cache; if this fails, we need to get one.
token, err := config.TokenCache.Token()
if err != nil {
if *clientId == "" || *clientSecret == "" {
flag.Usage()
fmt.Fprint(os.Stderr, usageMsg)
os.Exit(2)
}
if *code == "" {
// Get an authorization code from the data provider.
// ("Please ask the user if I can access this resource.")
url := config.AuthCodeURL("")
fmt.Println("Visit this URL to get a code, then run again with -code=YOUR_CODE\n")
fmt.Println(url)
return
}
// Exchange the authorization code for an access token.
// ("Here's the code you gave the user, now give me a token!")
token, err = transport.Exchange(*code)
if err != nil {
log.Fatal("Exchange:", err)
}
// (The Exchange method will automatically cache the token.)
fmt.Printf("Token is cached in %v\n", config.TokenCache)
}
// Make the actual request using the cached token to authenticate.
// ("Here's the token, let me in!")
transport.Token = token
// Make the request.
r, err := transport.Client().Get(*requestURL)
if err != nil {
log.Fatal("Get:", err)
}
defer r.Body.Close()
// Write the response to standard output.
io.Copy(os.Stdout, r.Body)
// Send final carriage return, just to be neat.
fmt.Println()
}

View File

@ -0,0 +1 @@
{"web":{"auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://accounts.google.com/o/oauth2/token","client_email":"XXXXXXXXXXXX@developer.gserviceaccount.com","client_x509_cert_url":"https://www.googleapis.com/robot/v1/metadata/x509/XXXXXXXXXXXX@developer.gserviceaccount.com","client_id":"XXXXXXXXXXXX.apps.googleusercontent.com","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs"}}

View File

@ -0,0 +1,20 @@
Bag Attributes
friendlyName: privatekey
localKeyID: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Key Attributes: <No Attributes>
-----BEGIN PRIVATE KEY-----
XXXXxyXXXXXXXxxyxxxX9y0XXYXXXXYXXxXyxxXxXxXXXyXXXXx4yx1xy1xyYxxY
1XxYy38YxXxxxyXxyyxx+xxxxyx1Y1xYx7yx2/Y1XyyXYYYxY5YXxX0xY/Y642yX
zYYxYXzXYxY0Y8y9YxyYXxxX40YyXxxXX4XXxx7XxXxxXyXxYYXxXyxX5XY0Yy2X
1YX0XXyy6YXyXx9XxXxyXX9XXYXxXxXXXXXXxYXYY3Y8Yy311XYYY81XyY14Xyyx
xXyx7xxXXXxxxxyyyX4YYYXyYyYXyxX4XYXYyxXYyx9xy23xXYyXyxYxXxx1XXXY
y98yX6yYxyyyX4Xyx1Xy/0yxxYxXxYYx2xx7yYXXXxYXXXxyXyyYYxx5XX2xxyxy
y6Yyyx0XX3YYYyx9YYXXXX7y0yxXXy+90XYz1y2xyx7yXxX+8X0xYxXXYxxyxYYy
YXx8Yy4yX0Xyxxx6yYX92yxy1YYYzyyyyxy55x/yyXXXYYXYXXzXXxYYxyXY8XXX
+y9+yXxX7XxxyYYxxXYxyY623xxXxYX59x5Y6yYyXYY4YxXXYXXXYxXYxXxXXx6x
YXX7XxXX2X0XY7YXyYy1XXxYXxXxYY1xXXxxxyy+07zXYxYxxXyyxxyxXx1XYy5X
5XYzyxYxXXYyX9XX7xX8xXxx+XXYyYXXXX5YY1x8Yxyx54Xy/1XXyyYXY5YxYyxY
XyyxXyX/YxxXXXxXXYXxyxx63xX/xxyYXXyYzx0XY+YxX5xyYyyxxxXXYX/94XXy
Xx63xYxXyXY3/XXxyyXX15XXXyz08XYY5YYXY/YXy/96x68XyyXXxYyXy4xYXx5x
7yxxyxxYxXxyx3y=
-----END PRIVATE KEY-----

View File

@ -0,0 +1,114 @@
// Copyright 2011 The goauth2 Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This program makes a read only call to the Google Cloud Storage API,
// authenticated with OAuth2. A list of example APIs can be found at
// https://code.google.com/oauthplayground/
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"code.google.com/p/goauth2/oauth/jwt"
)
const scope = "https://www.googleapis.com/auth/devstorage.read_only"
var (
secretsFile = flag.String("s", "", "JSON encoded secrets for the service account")
pemFile = flag.String("k", "", "private pem key file for the service account")
)
const usageMsg = `
You must specify -k and -s.
To obtain client secrets and pem, see the "OAuth 2 Credentials" section under
the "API Access" tab on this page: https://code.google.com/apis/console/
Google Cloud Storage must also be turned on in the API console.
`
func main() {
flag.Parse()
if *secretsFile == "" || *pemFile == "" {
flag.Usage()
fmt.Println(usageMsg)
return
}
// Read the secret file bytes into the config.
secretBytes, err := ioutil.ReadFile(*secretsFile)
if err != nil {
log.Fatal("error reading secerets file:", err)
}
var config struct {
Web struct {
ClientEmail string `json:"client_email"`
ClientID string `json:"client_id"`
TokenURI string `json:"token_uri"`
}
}
err = json.Unmarshal(secretBytes, &config)
if err != nil {
log.Fatal("error unmarshalling secerets:", err)
}
// Get the project ID from the client ID.
projectID := strings.SplitN(config.Web.ClientID, "-", 2)[0]
// Read the pem file bytes for the private key.
keyBytes, err := ioutil.ReadFile(*pemFile)
if err != nil {
log.Fatal("error reading private key file:", err)
}
// Craft the ClaimSet and JWT token.
t := jwt.NewToken(config.Web.ClientEmail, scope, keyBytes)
t.ClaimSet.Aud = config.Web.TokenURI
// We need to provide a client.
c := &http.Client{}
// Get the access token.
o, err := t.Assert(c)
if err != nil {
log.Fatal("assertion error:", err)
}
// Refresh token will be missing, but this access_token will be good
// for one hour.
fmt.Printf("access_token = %v\n", o.AccessToken)
fmt.Printf("refresh_token = %v\n", o.RefreshToken)
fmt.Printf("expires %v\n", o.Expiry)
// Form the request to list Google Cloud Storage buckets.
req, err := http.NewRequest("GET", "https://storage.googleapis.com/", nil)
if err != nil {
log.Fatal("http.NewRequest:", err)
}
req.Header.Set("Authorization", "OAuth "+o.AccessToken)
req.Header.Set("x-goog-api-version", "2")
req.Header.Set("x-goog-project-id", projectID)
// Make the request.
r, err := c.Do(req)
if err != nil {
log.Fatal("API request error:", err)
}
defer r.Body.Close()
// Write the response to standard output.
res, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Fatal("error reading API request results:", err)
}
fmt.Printf("\nRESULT:\n%s\n", res)
}

View File

@ -0,0 +1,511 @@
// Copyright 2012 The goauth2 Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The jwt package provides support for creating credentials for OAuth2 service
// account requests.
//
// For examples of the package usage please see jwt_test.go.
// Example usage (error handling omitted for brevity):
//
// // Craft the ClaimSet and JWT token.
// iss := "XXXXXXXXXXXX@developer.gserviceaccount.com"
// scope := "https://www.googleapis.com/auth/devstorage.read_only"
// t := jwt.NewToken(iss, scope, pemKeyBytes)
//
// // We need to provide a client.
// c := &http.Client{}
//
// // Get the access token.
// o, _ := t.Assert(c)
//
// // Form the request to the service.
// req, _ := http.NewRequest("GET", "https://storage.googleapis.com/", nil)
// req.Header.Set("Authorization", "OAuth "+o.AccessToken)
// req.Header.Set("x-goog-api-version", "2")
// req.Header.Set("x-goog-project-id", "XXXXXXXXXXXX")
//
// // Make the request.
// result, _ := c.Do(req)
//
// For info on OAuth2 service accounts please see the online documentation.
// https://developers.google.com/accounts/docs/OAuth2ServiceAccount
//
package jwt
import (
"bytes"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"code.google.com/p/goauth2/oauth"
)
// These are the default/standard values for this to work for Google service accounts.
const (
stdAlgorithm = "RS256"
stdType = "JWT"
stdAssertionType = "http://oauth.net/grant_type/jwt/1.0/bearer"
stdGrantType = "urn:ietf:params:oauth:grant-type:jwt-bearer"
stdAud = "https://accounts.google.com/o/oauth2/token"
)
var (
ErrInvalidKey = errors.New("Invalid Key")
)
// base64Encode returns and Base64url encoded version of the input string with any
// trailing "=" stripped.
func base64Encode(b []byte) string {
return strings.TrimRight(base64.URLEncoding.EncodeToString(b), "=")
}
// base64Decode decodes the Base64url encoded string
func base64Decode(s string) ([]byte, error) {
// add back missing padding
switch len(s) % 4 {
case 2:
s += "=="
case 3:
s += "="
}
return base64.URLEncoding.DecodeString(s)
}
// The JWT claim set contains information about the JWT including the
// permissions being requested (scopes), the target of the token, the issuer,
// the time the token was issued, and the lifetime of the token.
//
// Aud is usually https://accounts.google.com/o/oauth2/token
type ClaimSet struct {
Iss string `json:"iss"` // email address of the client_id of the application making the access token request
Scope string `json:"scope,omitempty"` // space-delimited list of the permissions the application requests
Aud string `json:"aud"` // descriptor of the intended target of the assertion (Optional).
Prn string `json:"prn,omitempty"` // email for which the application is requesting delegated access (Optional).
Exp int64 `json:"exp"`
Iat int64 `json:"iat"`
Typ string `json:"typ,omitempty"`
Sub string `json:"sub,omitempty"` // Add support for googleapi delegation support
// See http://tools.ietf.org/html/draft-jones-json-web-token-10#section-4.3
// This array is marshalled using custom code (see (c *ClaimSet) encode()).
PrivateClaims map[string]interface{} `json:"-"`
exp time.Time
iat time.Time
}
// setTimes sets iat and exp to time.Now() and iat.Add(time.Hour) respectively.
//
// Note that these times have nothing to do with the expiration time for the
// access_token returned by the server. These have to do with the lifetime of
// the encoded JWT.
//
// A JWT can be re-used for up to one hour after it was encoded. The access
// token that is granted will also be good for one hour so there is little point
// in trying to use the JWT a second time.
func (c *ClaimSet) setTimes(t time.Time) {
c.iat = t
c.exp = c.iat.Add(time.Hour)
}
var (
jsonStart = []byte{'{'}
jsonEnd = []byte{'}'}
)
// encode returns the Base64url encoded form of the Signature.
func (c *ClaimSet) encode() string {
if c.exp.IsZero() || c.iat.IsZero() {
c.setTimes(time.Now())
}
if c.Aud == "" {
c.Aud = stdAud
}
c.Exp = c.exp.Unix()
c.Iat = c.iat.Unix()
b, err := json.Marshal(c)
if err != nil {
panic(err)
}
if len(c.PrivateClaims) == 0 {
return base64Encode(b)
}
// Marshal private claim set and then append it to b.
prv, err := json.Marshal(c.PrivateClaims)
if err != nil {
panic(fmt.Errorf("Invalid map of private claims %v", c.PrivateClaims))
}
// Concatenate public and private claim JSON objects.
if !bytes.HasSuffix(b, jsonEnd) {
panic(fmt.Errorf("Invalid JSON %s", b))
}
if !bytes.HasPrefix(prv, jsonStart) {
panic(fmt.Errorf("Invalid JSON %s", prv))
}
b[len(b)-1] = ',' // Replace closing curly brace with a comma.
b = append(b, prv[1:]...) // Append private claims.
return base64Encode(b)
}
// Header describes the algorithm and type of token being generated,
// and optionally a KeyID describing additional parameters for the
// signature.
type Header struct {
Algorithm string `json:"alg"`
Type string `json:"typ"`
KeyId string `json:"kid,omitempty"`
}
func (h *Header) encode() string {
b, err := json.Marshal(h)
if err != nil {
panic(err)
}
return base64Encode(b)
}
// A JWT is composed of three parts: a header, a claim set, and a signature.
// The well formed and encoded JWT can then be exchanged for an access token.
//
// The Token is not a JWT, but is is encoded to produce a well formed JWT.
//
// When obtaining a key from the Google API console it will be downloaded in a
// PKCS12 encoding. To use this key you will need to convert it to a PEM file.
// This can be achieved with openssl.
//
// $ openssl pkcs12 -in <key.p12> -nocerts -passin pass:notasecret -nodes -out <key.pem>
//
// The contents of this file can then be used as the Key.
type Token struct {
ClaimSet *ClaimSet // claim set used to construct the JWT
Header *Header // header used to construct the JWT
Key []byte // PEM printable encoding of the private key
pKey *rsa.PrivateKey
header string
claim string
sig string
useExternalSigner bool
signer Signer
}
// NewToken returns a filled in *Token based on the standard header,
// and sets the Iat and Exp times based on when the call to Assert is
// made.
func NewToken(iss, scope string, key []byte) *Token {
c := &ClaimSet{
Iss: iss,
Scope: scope,
Aud: stdAud,
}
h := &Header{
Algorithm: stdAlgorithm,
Type: stdType,
}
t := &Token{
ClaimSet: c,
Header: h,
Key: key,
}
return t
}
// Signer is an interface that given a JWT token, returns the header &
// claim (serialized and urlEncoded to a byte slice), along with the
// signature and an error (if any occured). It could modify any data
// to sign (typically the KeyID).
//
// Example usage where a SHA256 hash of the original url-encoded token
// with an added KeyID and secret data is used as a signature:
//
// var privateData = "secret data added to hash, indexed by KeyID"
//
// type SigningService struct{}
//
// func (ss *SigningService) Sign(in *jwt.Token) (newTokenData, sig []byte, err error) {
// in.Header.KeyID = "signing service"
// newTokenData = in.EncodeWithoutSignature()
// dataToSign := fmt.Sprintf("%s.%s", newTokenData, privateData)
// h := sha256.New()
// _, err := h.Write([]byte(dataToSign))
// sig = h.Sum(nil)
// return
// }
type Signer interface {
Sign(in *Token) (tokenData, signature []byte, err error)
}
// NewSignerToken returns a *Token, using an external signer function
func NewSignerToken(iss, scope string, signer Signer) *Token {
t := NewToken(iss, scope, nil)
t.useExternalSigner = true
t.signer = signer
return t
}
// Expired returns a boolean value letting us know if the token has expired.
func (t *Token) Expired() bool {
return t.ClaimSet.exp.Before(time.Now())
}
// Encode constructs and signs a Token returning a JWT ready to use for
// requesting an access token.
func (t *Token) Encode() (string, error) {
var tok string
t.header = t.Header.encode()
t.claim = t.ClaimSet.encode()
err := t.sign()
if err != nil {
return tok, err
}
tok = fmt.Sprintf("%s.%s.%s", t.header, t.claim, t.sig)
return tok, nil
}
// EncodeWithoutSignature returns the url-encoded value of the Token
// before signing has occured (typically for use by external signers).
func (t *Token) EncodeWithoutSignature() string {
t.header = t.Header.encode()
t.claim = t.ClaimSet.encode()
return fmt.Sprintf("%s.%s", t.header, t.claim)
}
// sign computes the signature for a Token. The details for this can be found
// in the OAuth2 Service Account documentation.
// https://developers.google.com/accounts/docs/OAuth2ServiceAccount#computingsignature
func (t *Token) sign() error {
if t.useExternalSigner {
fulldata, sig, err := t.signer.Sign(t)
if err != nil {
return err
}
split := strings.Split(string(fulldata), ".")
if len(split) != 2 {
return errors.New("no token returned")
}
t.header = split[0]
t.claim = split[1]
t.sig = base64Encode(sig)
return err
}
ss := fmt.Sprintf("%s.%s", t.header, t.claim)
if t.pKey == nil {
err := t.parsePrivateKey()
if err != nil {
return err
}
}
h := sha256.New()
h.Write([]byte(ss))
b, err := rsa.SignPKCS1v15(rand.Reader, t.pKey, crypto.SHA256, h.Sum(nil))
t.sig = base64Encode(b)
return err
}
// parsePrivateKey converts the Token's Key ([]byte) into a parsed
// rsa.PrivateKey. If the key is not well formed this method will return an
// ErrInvalidKey error.
func (t *Token) parsePrivateKey() error {
block, _ := pem.Decode(t.Key)
if block == nil {
return ErrInvalidKey
}
parsedKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return err
}
}
var ok bool
t.pKey, ok = parsedKey.(*rsa.PrivateKey)
if !ok {
return ErrInvalidKey
}
return nil
}
// Assert obtains an *oauth.Token from the remote server by encoding and sending
// a JWT. The access_token will expire in one hour (3600 seconds) and cannot be
// refreshed (no refresh_token is returned with the response). Once this token
// expires call this method again to get a fresh one.
func (t *Token) Assert(c *http.Client) (*oauth.Token, error) {
var o *oauth.Token
t.ClaimSet.setTimes(time.Now())
u, v, err := t.buildRequest()
if err != nil {
return o, err
}
resp, err := c.PostForm(u, v)
if err != nil {
return o, err
}
o, err = handleResponse(resp)
return o, err
}
// buildRequest sets up the URL values and the proper URL string for making our
// access_token request.
func (t *Token) buildRequest() (string, url.Values, error) {
v := url.Values{}
j, err := t.Encode()
if err != nil {
return t.ClaimSet.Aud, v, err
}
v.Set("grant_type", stdGrantType)
v.Set("assertion", j)
return t.ClaimSet.Aud, v, nil
}
// Used for decoding the response body.
type respBody struct {
IdToken string `json:"id_token"`
Access string `json:"access_token"`
Type string `json:"token_type"`
ExpiresIn time.Duration `json:"expires_in"`
}
// handleResponse returns a filled in *oauth.Token given the *http.Response from
// a *http.Request created by buildRequest.
func handleResponse(r *http.Response) (*oauth.Token, error) {
o := &oauth.Token{}
defer r.Body.Close()
if r.StatusCode != 200 {
return o, errors.New("invalid response: " + r.Status)
}
b := &respBody{}
err := json.NewDecoder(r.Body).Decode(b)
if err != nil {
return o, err
}
o.AccessToken = b.Access
if b.IdToken != "" {
// decode returned id token to get expiry
o.AccessToken = b.IdToken
s := strings.Split(b.IdToken, ".")
if len(s) < 2 {
return nil, errors.New("invalid token received")
}
d, err := base64Decode(s[1])
if err != nil {
return o, err
}
c := &ClaimSet{}
err = json.NewDecoder(bytes.NewBuffer(d)).Decode(c)
if err != nil {
return o, err
}
o.Expiry = time.Unix(c.Exp, 0)
return o, nil
}
o.Expiry = time.Now().Add(b.ExpiresIn * time.Second)
return o, nil
}
// Transport implements http.RoundTripper. When configured with a valid
// JWT and OAuth tokens it can be used to make authenticated HTTP requests.
//
// t := &jwt.Transport{jwtToken, oauthToken}
// r, _, err := t.Client().Get("http://example.org/url/requiring/auth")
//
// It will automatically refresh the OAuth token if it can, updating in place.
type Transport struct {
JWTToken *Token
OAuthToken *oauth.Token
// Transport is the HTTP transport to use when making requests.
// It will default to http.DefaultTransport if nil.
Transport http.RoundTripper
}
// Creates a new authenticated transport.
func NewTransport(token *Token) (*Transport, error) {
oa, err := token.Assert(new(http.Client))
if err != nil {
return nil, err
}
return &Transport{
JWTToken: token,
OAuthToken: oa,
}, nil
}
// Client returns an *http.Client that makes OAuth-authenticated requests.
func (t *Transport) Client() *http.Client {
return &http.Client{Transport: t}
}
// Fetches the internal transport.
func (t *Transport) transport() http.RoundTripper {
if t.Transport != nil {
return t.Transport
}
return http.DefaultTransport
}
// RoundTrip executes a single HTTP transaction using the Transport's
// OAuthToken as authorization headers.
//
// This method will attempt to renew the token if it has expired and may return
// an error related to that token renewal before attempting the client request.
// If the token cannot be renewed a non-nil os.Error value will be returned.
// If the token is invalid callers should expect HTTP-level errors,
// as indicated by the Response's StatusCode.
func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
// Sanity check the two tokens
if t.JWTToken == nil {
return nil, fmt.Errorf("no JWT token supplied")
}
if t.OAuthToken == nil {
return nil, fmt.Errorf("no OAuth token supplied")
}
// Refresh the OAuth token if it has expired
if t.OAuthToken.Expired() {
if oa, err := t.JWTToken.Assert(new(http.Client)); err != nil {
return nil, err
} else {
t.OAuthToken = oa
}
}
// To set the Authorization header, we must make a copy of the Request
// so that we don't modify the Request we were given.
// This is required by the specification of http.RoundTripper.
req = cloneRequest(req)
req.Header.Set("Authorization", "Bearer "+t.OAuthToken.AccessToken)
// Make the HTTP request.
return t.transport().RoundTrip(req)
}
// cloneRequest returns a clone of the provided *http.Request.
// The clone is a shallow copy of the struct and its Header map.
func cloneRequest(r *http.Request) *http.Request {
// shallow copy of the struct
r2 := new(http.Request)
*r2 = *r
// deep copy of the Header
r2.Header = make(http.Header)
for k, s := range r.Header {
r2.Header[k] = s
}
return r2
}

View File

@ -0,0 +1,486 @@
// Copyright 2012 The goauth2 Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// For package documentation please see jwt.go.
//
package jwt
import (
"bytes"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/json"
"encoding/pem"
"io/ioutil"
"net/http"
"testing"
"time"
)
const (
stdHeaderStr = `{"alg":"RS256","typ":"JWT"}`
iss = "761326798069-r5mljlln1rd4lrbhg75efgigp36m78j5@developer.gserviceaccount.com"
scope = "https://www.googleapis.com/auth/prediction"
exp = 1328554385
iat = 1328550785 // exp + 1 hour
)
// Base64url encoded Header
const headerEnc = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9"
// Base64url encoded ClaimSet
const claimSetEnc = "eyJpc3MiOiI3NjEzMjY3OTgwNjktcjVtbGpsbG4xcmQ0bHJiaGc3NWVmZ2lncDM2bTc4ajVAZGV2ZWxvcGVyLmdzZXJ2aWNlYWNjb3VudC5jb20iLCJzY29wZSI6Imh0dHBzOi8vd3d3Lmdvb2dsZWFwaXMuY29tL2F1dGgvcHJlZGljdGlvbiIsImF1ZCI6Imh0dHBzOi8vYWNjb3VudHMuZ29vZ2xlLmNvbS9vL29hdXRoMi90b2tlbiIsImV4cCI6MTMyODU1NDM4NSwiaWF0IjoxMzI4NTUwNzg1fQ"
// Base64url encoded Signature
const sigEnc = "olukbHreNiYrgiGCTEmY3eWGeTvYDSUHYoE84Jz3BRPBSaMdZMNOn_0CYK7UHPO7OdvUofjwft1dH59UxE9GWS02pjFti1uAQoImaqjLZoTXr8qiF6O_kDa9JNoykklWlRAIwGIZkDupCS-8cTAnM_ksSymiH1coKJrLDUX_BM0x2f4iMFQzhL5vT1ll-ZipJ0lNlxb5QsyXxDYcxtHYguF12-vpv3ItgT0STfcXoWzIGQoEbhwB9SBp9JYcQ8Ygz6pYDjm0rWX9LrchmTyDArCodpKLFtutNgcIFUP9fWxvwd1C2dNw5GjLcKr9a_SAERyoJ2WnCR1_j9N0wD2o0g"
// Base64url encoded Token
const tokEnc = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiI3NjEzMjY3OTgwNjktcjVtbGpsbG4xcmQ0bHJiaGc3NWVmZ2lncDM2bTc4ajVAZGV2ZWxvcGVyLmdzZXJ2aWNlYWNjb3VudC5jb20iLCJzY29wZSI6Imh0dHBzOi8vd3d3Lmdvb2dsZWFwaXMuY29tL2F1dGgvcHJlZGljdGlvbiIsImF1ZCI6Imh0dHBzOi8vYWNjb3VudHMuZ29vZ2xlLmNvbS9vL29hdXRoMi90b2tlbiIsImV4cCI6MTMyODU1NDM4NSwiaWF0IjoxMzI4NTUwNzg1fQ.olukbHreNiYrgiGCTEmY3eWGeTvYDSUHYoE84Jz3BRPBSaMdZMNOn_0CYK7UHPO7OdvUofjwft1dH59UxE9GWS02pjFti1uAQoImaqjLZoTXr8qiF6O_kDa9JNoykklWlRAIwGIZkDupCS-8cTAnM_ksSymiH1coKJrLDUX_BM0x2f4iMFQzhL5vT1ll-ZipJ0lNlxb5QsyXxDYcxtHYguF12-vpv3ItgT0STfcXoWzIGQoEbhwB9SBp9JYcQ8Ygz6pYDjm0rWX9LrchmTyDArCodpKLFtutNgcIFUP9fWxvwd1C2dNw5GjLcKr9a_SAERyoJ2WnCR1_j9N0wD2o0g"
// Private key for testing
const privateKeyPem = `-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA4ej0p7bQ7L/r4rVGUz9RN4VQWoej1Bg1mYWIDYslvKrk1gpj
7wZgkdmM7oVK2OfgrSj/FCTkInKPqaCR0gD7K80q+mLBrN3PUkDrJQZpvRZIff3/
xmVU1WeruQLFJjnFb2dqu0s/FY/2kWiJtBCakXvXEOb7zfbINuayL+MSsCGSdVYs
SliS5qQpgyDap+8b5fpXZVJkq92hrcNtbkg7hCYUJczt8n9hcCTJCfUpApvaFQ18
pe+zpyl4+WzkP66I28hniMQyUlA1hBiskT7qiouq0m8IOodhv2fagSZKjOTTU2xk
SBc//fy3ZpsL7WqgsZS7Q+0VRK8gKfqkxg5OYQIDAQABAoIBAQDGGHzQxGKX+ANk
nQi53v/c6632dJKYXVJC+PDAz4+bzU800Y+n/bOYsWf/kCp94XcG4Lgsdd0Gx+Zq
HD9CI1IcqqBRR2AFscsmmX6YzPLTuEKBGMW8twaYy3utlFxElMwoUEsrSWRcCA1y
nHSDzTt871c7nxCXHxuZ6Nm/XCL7Bg8uidRTSC1sQrQyKgTPhtQdYrPQ4WZ1A4J9
IisyDYmZodSNZe5P+LTJ6M1SCgH8KH9ZGIxv3diMwzNNpk3kxJc9yCnja4mjiGE2
YCNusSycU5IhZwVeCTlhQGcNeV/skfg64xkiJE34c2y2ttFbdwBTPixStGaF09nU
Z422D40BAoGBAPvVyRRsC3BF+qZdaSMFwI1yiXY7vQw5+JZh01tD28NuYdRFzjcJ
vzT2n8LFpj5ZfZFvSMLMVEFVMgQvWnN0O6xdXvGov6qlRUSGaH9u+TCPNnIldjMP
B8+xTwFMqI7uQr54wBB+Poq7dVRP+0oHb0NYAwUBXoEuvYo3c/nDoRcZAoGBAOWl
aLHjMv4CJbArzT8sPfic/8waSiLV9Ixs3Re5YREUTtnLq7LoymqB57UXJB3BNz/2
eCueuW71avlWlRtE/wXASj5jx6y5mIrlV4nZbVuyYff0QlcG+fgb6pcJQuO9DxMI
aqFGrWP3zye+LK87a6iR76dS9vRU+bHZpSVvGMKJAoGAFGt3TIKeQtJJyqeUWNSk
klORNdcOMymYMIlqG+JatXQD1rR6ThgqOt8sgRyJqFCVT++YFMOAqXOBBLnaObZZ
CFbh1fJ66BlSjoXff0W+SuOx5HuJJAa5+WtFHrPajwxeuRcNa8jwxUsB7n41wADu
UqWWSRedVBg4Ijbw3nWwYDECgYB0pLew4z4bVuvdt+HgnJA9n0EuYowVdadpTEJg
soBjNHV4msLzdNqbjrAqgz6M/n8Ztg8D2PNHMNDNJPVHjJwcR7duSTA6w2p/4k28
bvvk/45Ta3XmzlxZcZSOct3O31Cw0i2XDVc018IY5be8qendDYM08icNo7vQYkRH
504kQQKBgQDjx60zpz8ozvm1XAj0wVhi7GwXe+5lTxiLi9Fxq721WDxPMiHDW2XL
YXfFVy/9/GIMvEiGYdmarK1NW+VhWl1DC5xhDg0kvMfxplt4tynoq1uTsQTY31Mx
BeF5CT/JuNYk3bEBF0H/Q3VGO1/ggVS+YezdFbLWIRoMnLj6XCFEGg==
-----END RSA PRIVATE KEY-----`
// Public key to go with the private key for testing
const publicKeyPem = `-----BEGIN CERTIFICATE-----
MIIDIzCCAgugAwIBAgIJAMfISuBQ5m+5MA0GCSqGSIb3DQEBBQUAMBUxEzARBgNV
BAMTCnVuaXQtdGVzdHMwHhcNMTExMjA2MTYyNjAyWhcNMjExMjAzMTYyNjAyWjAV
MRMwEQYDVQQDEwp1bml0LXRlc3RzMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
CgKCAQEA4ej0p7bQ7L/r4rVGUz9RN4VQWoej1Bg1mYWIDYslvKrk1gpj7wZgkdmM
7oVK2OfgrSj/FCTkInKPqaCR0gD7K80q+mLBrN3PUkDrJQZpvRZIff3/xmVU1Wer
uQLFJjnFb2dqu0s/FY/2kWiJtBCakXvXEOb7zfbINuayL+MSsCGSdVYsSliS5qQp
gyDap+8b5fpXZVJkq92hrcNtbkg7hCYUJczt8n9hcCTJCfUpApvaFQ18pe+zpyl4
+WzkP66I28hniMQyUlA1hBiskT7qiouq0m8IOodhv2fagSZKjOTTU2xkSBc//fy3
ZpsL7WqgsZS7Q+0VRK8gKfqkxg5OYQIDAQABo3YwdDAdBgNVHQ4EFgQU2RQ8yO+O
gN8oVW2SW7RLrfYd9jEwRQYDVR0jBD4wPIAU2RQ8yO+OgN8oVW2SW7RLrfYd9jGh
GaQXMBUxEzARBgNVBAMTCnVuaXQtdGVzdHOCCQDHyErgUOZvuTAMBgNVHRMEBTAD
AQH/MA0GCSqGSIb3DQEBBQUAA4IBAQBRv+M/6+FiVu7KXNjFI5pSN17OcW5QUtPr
odJMlWrJBtynn/TA1oJlYu3yV5clc/71Vr/AxuX5xGP+IXL32YDF9lTUJXG/uUGk
+JETpKmQviPbRsvzYhz4pf6ZIOZMc3/GIcNq92ECbseGO+yAgyWUVKMmZM0HqXC9
ovNslqe0M8C1sLm1zAR5z/h/litE7/8O2ietija3Q/qtl2TOXJdCA6sgjJX2WUql
ybrC55ct18NKf3qhpcEkGQvFU40rVYApJpi98DiZPYFdx1oBDp/f4uZ3ojpxRVFT
cDwcJLfNRCPUhormsY7fDS9xSyThiHsW9mjJYdcaKQkwYZ0F11yB
-----END CERTIFICATE-----`
var (
privateKeyPemBytes = []byte(privateKeyPem)
publicKeyPemBytes = []byte(publicKeyPem)
stdHeader = &Header{Algorithm: stdAlgorithm, Type: stdType}
)
// Testing the urlEncode function.
func TestUrlEncode(t *testing.T) {
enc := base64Encode([]byte(stdHeaderStr))
b := []byte(enc)
if b[len(b)-1] == 61 {
t.Error("TestUrlEncode: last chat == \"=\"")
}
if enc != headerEnc {
t.Error("TestUrlEncode: enc != headerEnc")
t.Errorf(" enc = %s", enc)
t.Errorf(" headerEnc = %s", headerEnc)
}
}
// Test that the times are set properly.
func TestClaimSetSetTimes(t *testing.T) {
c := &ClaimSet{
Iss: iss,
Scope: scope,
}
iat := time.Unix(iat, 0)
c.setTimes(iat)
if c.exp.Unix() != exp {
t.Error("TestClaimSetSetTimes: c.exp != exp")
t.Errorf(" c.Exp = %d", c.exp.Unix())
t.Errorf(" exp = %d", exp)
}
}
// Given a well formed ClaimSet, test for proper encoding.
func TestClaimSetEncode(t *testing.T) {
c := &ClaimSet{
Iss: iss,
Scope: scope,
exp: time.Unix(exp, 0),
iat: time.Unix(iat, 0),
}
enc := c.encode()
re, err := base64Decode(enc)
if err != nil {
t.Fatalf("error decoding encoded claim set: %v", err)
}
wa, err := base64Decode(claimSetEnc)
if err != nil {
t.Fatalf("error decoding encoded expected claim set: %v", err)
}
if enc != claimSetEnc {
t.Error("TestClaimSetEncode: enc != claimSetEnc")
t.Errorf(" enc = %s", string(re))
t.Errorf(" claimSetEnc = %s", string(wa))
}
}
// Test that claim sets with private claim names are encoded correctly.
func TestClaimSetWithPrivateNameEncode(t *testing.T) {
iatT := time.Unix(iat, 0)
expT := time.Unix(exp, 0)
i, err := json.Marshal(iatT.Unix())
if err != nil {
t.Fatalf("error marshaling iatT value of %v: %v", iatT.Unix(), err)
}
iatStr := string(i)
e, err := json.Marshal(expT.Unix())
if err != nil {
t.Fatalf("error marshaling expT value of %v: %v", expT.Unix(), err)
}
expStr := string(e)
testCases := []struct {
desc string
input map[string]interface{}
want string
}{
// Test a simple int field.
{
"single simple field",
map[string]interface{}{"amount": 22},
`{` +
`"iss":"` + iss + `",` +
`"scope":"` + scope + `",` +
`"aud":"` + stdAud + `",` +
`"exp":` + expStr + `,` +
`"iat":` + iatStr + `,` +
`"amount":22` +
`}`,
},
{
"multiple simple fields",
map[string]interface{}{"tracking_code": "axZf", "amount": 22},
`{` +
`"iss":"` + iss + `",` +
`"scope":"` + scope + `",` +
`"aud":"` + stdAud + `",` +
`"exp":` + expStr + `,` +
`"iat":` + iatStr + `,` +
`"amount":22,` +
`"tracking_code":"axZf"` +
`}`,
},
{
"nested struct fields",
map[string]interface{}{
"tracking_code": "axZf",
"purchase": struct {
Description string `json:"desc"`
Quantity int32 `json:"q"`
Time int64 `json:"t"`
}{
"toaster",
5,
iat,
},
},
`{` +
`"iss":"` + iss + `",` +
`"scope":"` + scope + `",` +
`"aud":"` + stdAud + `",` +
`"exp":` + expStr + `,` +
`"iat":` + iatStr + `,` +
`"purchase":{"desc":"toaster","q":5,"t":` + iatStr + `},` +
`"tracking_code":"axZf"` +
`}`,
},
}
for _, testCase := range testCases {
c := &ClaimSet{
Iss: iss,
Scope: scope,
Aud: stdAud,
iat: iatT,
exp: expT,
PrivateClaims: testCase.input,
}
cJSON, err := base64Decode(c.encode())
if err != nil {
t.Fatalf("error decoding claim set: %v", err)
}
if string(cJSON) != testCase.want {
t.Errorf("TestClaimSetWithPrivateNameEncode: enc != want in case %s", testCase.desc)
t.Errorf(" enc = %s", cJSON)
t.Errorf(" want = %s", testCase.want)
}
}
}
// Test the NewToken constructor.
func TestNewToken(t *testing.T) {
tok := NewToken(iss, scope, privateKeyPemBytes)
if tok.ClaimSet.Iss != iss {
t.Error("TestNewToken: tok.ClaimSet.Iss != iss")
t.Errorf(" tok.ClaimSet.Iss = %s", tok.ClaimSet.Iss)
t.Errorf(" iss = %s", iss)
}
if tok.ClaimSet.Scope != scope {
t.Error("TestNewToken: tok.ClaimSet.Scope != scope")
t.Errorf(" tok.ClaimSet.Scope = %s", tok.ClaimSet.Scope)
t.Errorf(" scope = %s", scope)
}
if tok.ClaimSet.Aud != stdAud {
t.Error("TestNewToken: tok.ClaimSet.Aud != stdAud")
t.Errorf(" tok.ClaimSet.Aud = %s", tok.ClaimSet.Aud)
t.Errorf(" stdAud = %s", stdAud)
}
if !bytes.Equal(tok.Key, privateKeyPemBytes) {
t.Error("TestNewToken: tok.Key != privateKeyPemBytes")
t.Errorf(" tok.Key = %s", tok.Key)
t.Errorf(" privateKeyPemBytes = %s", privateKeyPemBytes)
}
}
// Make sure the private key parsing functions work.
func TestParsePrivateKey(t *testing.T) {
tok := &Token{
Key: privateKeyPemBytes,
}
err := tok.parsePrivateKey()
if err != nil {
t.Errorf("TestParsePrivateKey:tok.parsePrivateKey: %v", err)
}
}
// Test that the token signature generated matches the golden standard.
func TestTokenSign(t *testing.T) {
tok := &Token{
Key: privateKeyPemBytes,
claim: claimSetEnc,
header: headerEnc,
}
err := tok.parsePrivateKey()
if err != nil {
t.Errorf("TestTokenSign:tok.parsePrivateKey: %v", err)
}
err = tok.sign()
if err != nil {
t.Errorf("TestTokenSign:tok.sign: %v", err)
}
if tok.sig != sigEnc {
t.Error("TestTokenSign: tok.sig != sigEnc")
t.Errorf(" tok.sig = %s", tok.sig)
t.Errorf(" sigEnc = %s", sigEnc)
}
}
// Test that the token expiration function is working.
func TestTokenExpired(t *testing.T) {
c := &ClaimSet{}
tok := &Token{
ClaimSet: c,
}
now := time.Now()
c.setTimes(now)
if tok.Expired() != false {
t.Error("TestTokenExpired: tok.Expired != false")
}
// Set the times as if they were set 2 hours ago.
c.setTimes(now.Add(-2 * time.Hour))
if tok.Expired() != true {
t.Error("TestTokenExpired: tok.Expired != true")
}
}
// Given a well formed Token, test for proper encoding.
func TestTokenEncode(t *testing.T) {
c := &ClaimSet{
Iss: iss,
Scope: scope,
exp: time.Unix(exp, 0),
iat: time.Unix(iat, 0),
}
tok := &Token{
ClaimSet: c,
Header: stdHeader,
Key: privateKeyPemBytes,
}
enc, err := tok.Encode()
if err != nil {
t.Errorf("TestTokenEncode:tok.Assertion: %v", err)
}
if enc != tokEnc {
t.Error("TestTokenEncode: enc != tokEnc")
t.Errorf(" enc = %s", enc)
t.Errorf(" tokEnc = %s", tokEnc)
}
}
// Given a well formed Token we should get back a well formed request.
func TestBuildRequest(t *testing.T) {
c := &ClaimSet{
Iss: iss,
Scope: scope,
exp: time.Unix(exp, 0),
iat: time.Unix(iat, 0),
}
tok := &Token{
ClaimSet: c,
Header: stdHeader,
Key: privateKeyPemBytes,
}
u, v, err := tok.buildRequest()
if err != nil {
t.Errorf("TestBuildRequest:BuildRequest: %v", err)
}
if u != c.Aud {
t.Error("TestBuildRequest: u != c.Aud")
t.Errorf(" u = %s", u)
t.Errorf(" c.Aud = %s", c.Aud)
}
if v.Get("grant_type") != stdGrantType {
t.Error("TestBuildRequest: grant_type != stdGrantType")
t.Errorf(" grant_type = %s", v.Get("grant_type"))
t.Errorf(" stdGrantType = %s", stdGrantType)
}
if v.Get("assertion") != tokEnc {
t.Error("TestBuildRequest: assertion != tokEnc")
t.Errorf(" assertion = %s", v.Get("assertion"))
t.Errorf(" tokEnc = %s", tokEnc)
}
}
// Given a well formed access request response we should get back a oauth.Token.
func TestHandleResponse(t *testing.T) {
rb := &respBody{
Access: "1/8xbJqaOZXSUZbHLl5EOtu1pxz3fmmetKx9W8CV4t79M",
Type: "Bearer",
ExpiresIn: 3600,
}
b, err := json.Marshal(rb)
if err != nil {
t.Errorf("TestHandleResponse:json.Marshal: %v", err)
}
r := &http.Response{
Status: "200 OK",
StatusCode: 200,
Body: ioutil.NopCloser(bytes.NewReader(b)),
}
o, err := handleResponse(r)
if err != nil {
t.Errorf("TestHandleResponse:handleResponse: %v", err)
}
if o.AccessToken != rb.Access {
t.Error("TestHandleResponse: o.AccessToken != rb.Access")
t.Errorf(" o.AccessToken = %s", o.AccessToken)
t.Errorf(" rb.Access = %s", rb.Access)
}
if o.Expired() {
t.Error("TestHandleResponse: o.Expired == true")
}
}
// passthrough signature for test
type FakeSigner struct{}
func (f FakeSigner) Sign(tok *Token) ([]byte, []byte, error) {
block, _ := pem.Decode(privateKeyPemBytes)
pKey, _ := x509.ParsePKCS1PrivateKey(block.Bytes)
ss := headerEnc + "." + claimSetEnc
h := sha256.New()
h.Write([]byte(ss))
b, _ := rsa.SignPKCS1v15(rand.Reader, pKey, crypto.SHA256, h.Sum(nil))
return []byte(ss), b, nil
}
// Given an external signer, get back a valid and signed JWT
func TestExternalSigner(t *testing.T) {
tok := NewSignerToken(iss, scope, FakeSigner{})
enc, _ := tok.Encode()
if enc != tokEnc {
t.Errorf("TestExternalSigner: enc != tokEnc")
t.Errorf(" enc = %s", enc)
t.Errorf(" tokEnc = %s", tokEnc)
}
}
func TestHandleResponseWithNewExpiry(t *testing.T) {
rb := &respBody{
IdToken: tokEnc,
}
b, err := json.Marshal(rb)
if err != nil {
t.Errorf("TestHandleResponse:json.Marshal: %v", err)
}
r := &http.Response{
Status: "200 OK",
StatusCode: 200,
Body: ioutil.NopCloser(bytes.NewReader(b)),
}
o, err := handleResponse(r)
if err != nil {
t.Errorf("TestHandleResponse:handleResponse: %v", err)
}
if o.Expiry != time.Unix(exp, 0) {
t.Error("TestHandleResponse: o.Expiry != exp")
t.Errorf(" o.Expiry = %s", o.Expiry)
t.Errorf(" exp = %s", time.Unix(exp, 0))
}
}
// Placeholder for future Assert tests.
func TestAssert(t *testing.T) {
// Since this method makes a call to BuildRequest, an htttp.Client, and
// finally HandleResponse there is not much more to test. This is here
// as a placeholder if that changes.
}
// Benchmark for the end-to-end encoding of a well formed token.
func BenchmarkTokenEncode(b *testing.B) {
b.StopTimer()
c := &ClaimSet{
Iss: iss,
Scope: scope,
exp: time.Unix(exp, 0),
iat: time.Unix(iat, 0),
}
tok := &Token{
ClaimSet: c,
Key: privateKeyPemBytes,
}
b.StartTimer()
for i := 0; i < b.N; i++ {
tok.Encode()
}
}

View File

@ -0,0 +1,386 @@
// Copyright 2011 The goauth2 Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The oauth package provides support for making
// OAuth2-authenticated HTTP requests.
//
// Example usage:
//
// // Specify your configuration. (typically as a global variable)
// var config = &oauth.Config{
// ClientId: YOUR_CLIENT_ID,
// ClientSecret: YOUR_CLIENT_SECRET,
// Scope: "https://www.googleapis.com/auth/buzz",
// AuthURL: "https://accounts.google.com/o/oauth2/auth",
// TokenURL: "https://accounts.google.com/o/oauth2/token",
// RedirectURL: "http://you.example.org/handler",
// }
//
// // A landing page redirects to the OAuth provider to get the auth code.
// func landing(w http.ResponseWriter, r *http.Request) {
// http.Redirect(w, r, config.AuthCodeURL("foo"), http.StatusFound)
// }
//
// // The user will be redirected back to this handler, that takes the
// // "code" query parameter and Exchanges it for an access token.
// func handler(w http.ResponseWriter, r *http.Request) {
// t := &oauth.Transport{Config: config}
// t.Exchange(r.FormValue("code"))
// // The Transport now has a valid Token. Create an *http.Client
// // with which we can make authenticated API requests.
// c := t.Client()
// c.Post(...)
// // ...
// // btw, r.FormValue("state") == "foo"
// }
//
package oauth
import (
"encoding/json"
"io/ioutil"
"mime"
"net/http"
"net/url"
"os"
"strings"
"time"
)
type OAuthError struct {
prefix string
msg string
}
func (oe OAuthError) Error() string {
return "OAuthError: " + oe.prefix + ": " + oe.msg
}
// Cache specifies the methods that implement a Token cache.
type Cache interface {
Token() (*Token, error)
PutToken(*Token) error
}
// CacheFile implements Cache. Its value is the name of the file in which
// the Token is stored in JSON format.
type CacheFile string
func (f CacheFile) Token() (*Token, error) {
file, err := os.Open(string(f))
if err != nil {
return nil, OAuthError{"CacheFile.Token", err.Error()}
}
defer file.Close()
tok := &Token{}
if err := json.NewDecoder(file).Decode(tok); err != nil {
return nil, OAuthError{"CacheFile.Token", err.Error()}
}
return tok, nil
}
func (f CacheFile) PutToken(tok *Token) error {
file, err := os.OpenFile(string(f), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return OAuthError{"CacheFile.PutToken", err.Error()}
}
if err := json.NewEncoder(file).Encode(tok); err != nil {
file.Close()
return OAuthError{"CacheFile.PutToken", err.Error()}
}
if err := file.Close(); err != nil {
return OAuthError{"CacheFile.PutToken", err.Error()}
}
return nil
}
// Config is the configuration of an OAuth consumer.
type Config struct {
// ClientId is the OAuth client identifier used when communicating with
// the configured OAuth provider.
ClientId string
// ClientSecret is the OAuth client secret used when communicating with
// the configured OAuth provider.
ClientSecret string
// Scope identifies the level of access being requested. Multiple scope
// values should be provided as a space-delimited string.
Scope string
// AuthURL is the URL the user will be directed to in order to grant
// access.
AuthURL string
// TokenURL is the URL used to retrieve OAuth tokens.
TokenURL string
// RedirectURL is the URL to which the user will be returned after
// granting (or denying) access.
RedirectURL string
// TokenCache allows tokens to be cached for subsequent requests.
TokenCache Cache
AccessType string // Optional, "online" (default) or "offline", no refresh token if "online"
// ApprovalPrompt indicates whether the user should be
// re-prompted for consent. If set to "auto" (default) the
// user will be prompted only if they haven't previously
// granted consent and the code can only be exchanged for an
// access token.
// If set to "force" the user will always be prompted, and the
// code can be exchanged for a refresh token.
ApprovalPrompt string
}
// Token contains an end-user's tokens.
// This is the data you must store to persist authentication.
type Token struct {
AccessToken string
RefreshToken string
Expiry time.Time // If zero the token has no (known) expiry time.
Extra map[string]string // May be nil.
}
func (t *Token) Expired() bool {
if t.Expiry.IsZero() {
return false
}
return t.Expiry.Before(time.Now())
}
// Transport implements http.RoundTripper. When configured with a valid
// Config and Token it can be used to make authenticated HTTP requests.
//
// t := &oauth.Transport{config}
// t.Exchange(code)
// // t now contains a valid Token
// r, _, err := t.Client().Get("http://example.org/url/requiring/auth")
//
// It will automatically refresh the Token if it can,
// updating the supplied Token in place.
type Transport struct {
*Config
*Token
// Transport is the HTTP transport to use when making requests.
// It will default to http.DefaultTransport if nil.
// (It should never be an oauth.Transport.)
Transport http.RoundTripper
}
// Client returns an *http.Client that makes OAuth-authenticated requests.
func (t *Transport) Client() *http.Client {
return &http.Client{Transport: t}
}
func (t *Transport) transport() http.RoundTripper {
if t.Transport != nil {
return t.Transport
}
return http.DefaultTransport
}
// AuthCodeURL returns a URL that the end-user should be redirected to,
// so that they may obtain an authorization code.
func (c *Config) AuthCodeURL(state string) string {
url_, err := url.Parse(c.AuthURL)
if err != nil {
panic("AuthURL malformed: " + err.Error())
}
q := url.Values{
"response_type": {"code"},
"client_id": {c.ClientId},
"redirect_uri": {c.RedirectURL},
"scope": {c.Scope},
"state": {state},
"access_type": {c.AccessType},
"approval_prompt": {c.ApprovalPrompt},
}.Encode()
if url_.RawQuery == "" {
url_.RawQuery = q
} else {
url_.RawQuery += "&" + q
}
return url_.String()
}
// Exchange takes a code and gets access Token from the remote server.
func (t *Transport) Exchange(code string) (*Token, error) {
if t.Config == nil {
return nil, OAuthError{"Exchange", "no Config supplied"}
}
// If the transport or the cache already has a token, it is
// passed to `updateToken` to preserve existing refresh token.
tok := t.Token
if tok == nil && t.TokenCache != nil {
tok, _ = t.TokenCache.Token()
}
if tok == nil {
tok = new(Token)
}
err := t.updateToken(tok, url.Values{
"grant_type": {"authorization_code"},
"redirect_uri": {t.RedirectURL},
"scope": {t.Scope},
"code": {code},
})
if err != nil {
return nil, err
}
t.Token = tok
if t.TokenCache != nil {
return tok, t.TokenCache.PutToken(tok)
}
return tok, nil
}
// RoundTrip executes a single HTTP transaction using the Transport's
// Token as authorization headers.
//
// This method will attempt to renew the Token if it has expired and may return
// an error related to that Token renewal before attempting the client request.
// If the Token cannot be renewed a non-nil os.Error value will be returned.
// If the Token is invalid callers should expect HTTP-level errors,
// as indicated by the Response's StatusCode.
func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
if t.Token == nil {
if t.Config == nil {
return nil, OAuthError{"RoundTrip", "no Config supplied"}
}
if t.TokenCache == nil {
return nil, OAuthError{"RoundTrip", "no Token supplied"}
}
var err error
t.Token, err = t.TokenCache.Token()
if err != nil {
return nil, err
}
}
// Refresh the Token if it has expired.
if t.Expired() {
if err := t.Refresh(); err != nil {
return nil, err
}
}
// To set the Authorization header, we must make a copy of the Request
// so that we don't modify the Request we were given.
// This is required by the specification of http.RoundTripper.
req = cloneRequest(req)
req.Header.Set("Authorization", "Bearer "+t.AccessToken)
// Make the HTTP request.
return t.transport().RoundTrip(req)
}
// cloneRequest returns a clone of the provided *http.Request.
// The clone is a shallow copy of the struct and its Header map.
func cloneRequest(r *http.Request) *http.Request {
// shallow copy of the struct
r2 := new(http.Request)
*r2 = *r
// deep copy of the Header
r2.Header = make(http.Header)
for k, s := range r.Header {
r2.Header[k] = s
}
return r2
}
// Refresh renews the Transport's AccessToken using its RefreshToken.
func (t *Transport) Refresh() error {
if t.Token == nil {
return OAuthError{"Refresh", "no existing Token"}
}
if t.RefreshToken == "" {
return OAuthError{"Refresh", "Token expired; no Refresh Token"}
}
if t.Config == nil {
return OAuthError{"Refresh", "no Config supplied"}
}
err := t.updateToken(t.Token, url.Values{
"grant_type": {"refresh_token"},
"refresh_token": {t.RefreshToken},
})
if err != nil {
return err
}
if t.TokenCache != nil {
return t.TokenCache.PutToken(t.Token)
}
return nil
}
func (t *Transport) updateToken(tok *Token, v url.Values) error {
v.Set("client_id", t.ClientId)
v.Set("client_secret", t.ClientSecret)
client := &http.Client{Transport: t.transport()}
req, err := http.NewRequest("POST", t.TokenURL, strings.NewReader(v.Encode()))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.SetBasicAuth(t.ClientId, t.ClientSecret)
r, err := client.Do(req)
if err != nil {
return err
}
defer r.Body.Close()
if r.StatusCode != 200 {
return OAuthError{"updateToken", r.Status}
}
var b struct {
Access string `json:"access_token"`
Refresh string `json:"refresh_token"`
ExpiresIn time.Duration `json:"expires_in"`
Id string `json:"id_token"`
}
content, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
switch content {
case "application/x-www-form-urlencoded", "text/plain":
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return err
}
vals, err := url.ParseQuery(string(body))
if err != nil {
return err
}
b.Access = vals.Get("access_token")
b.Refresh = vals.Get("refresh_token")
b.ExpiresIn, _ = time.ParseDuration(vals.Get("expires_in") + "s")
b.Id = vals.Get("id_token")
default:
if err = json.NewDecoder(r.Body).Decode(&b); err != nil {
return err
}
// The JSON parser treats the unitless ExpiresIn like 'ns' instead of 's' as above,
// so compensate here.
b.ExpiresIn *= time.Second
}
tok.AccessToken = b.Access
// Don't overwrite `RefreshToken` with an empty value
if len(b.Refresh) > 0 {
tok.RefreshToken = b.Refresh
}
if b.ExpiresIn == 0 {
tok.Expiry = time.Time{}
} else {
tok.Expiry = time.Now().Add(b.ExpiresIn)
}
if b.Id != "" {
if tok.Extra == nil {
tok.Extra = make(map[string]string)
}
tok.Extra["id_token"] = b.Id
}
return nil
}

View File

@ -0,0 +1,189 @@
// Copyright 2011 The goauth2 Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package oauth
import (
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"runtime"
"testing"
"time"
)
var requests = []struct {
path, query, auth string // request
contenttype, body string // response
}{
{
path: "/token",
query: "grant_type=authorization_code&code=c0d3&client_id=cl13nt1d&client_secret=s3cr3t",
contenttype: "application/json",
auth: "Basic Y2wxM250MWQ6czNjcjN0",
body: `
{
"access_token":"token1",
"refresh_token":"refreshtoken1",
"id_token":"idtoken1",
"expires_in":3600
}
`,
},
{path: "/secure", auth: "Bearer token1", body: "first payload"},
{
path: "/token",
query: "grant_type=refresh_token&refresh_token=refreshtoken1&client_id=cl13nt1d&client_secret=s3cr3t",
contenttype: "application/json",
auth: "Basic Y2wxM250MWQ6czNjcjN0",
body: `
{
"access_token":"token2",
"refresh_token":"refreshtoken2",
"id_token":"idtoken2",
"expires_in":3600
}
`,
},
{path: "/secure", auth: "Bearer token2", body: "second payload"},
{
path: "/token",
query: "grant_type=refresh_token&refresh_token=refreshtoken2&client_id=cl13nt1d&client_secret=s3cr3t",
contenttype: "application/x-www-form-urlencoded",
body: "access_token=token3&refresh_token=refreshtoken3&id_token=idtoken3&expires_in=3600",
auth: "Basic Y2wxM250MWQ6czNjcjN0",
},
{path: "/secure", auth: "Bearer token3", body: "third payload"},
}
func TestOAuth(t *testing.T) {
// Set up test server.
n := 0
handler := func(w http.ResponseWriter, r *http.Request) {
if n >= len(requests) {
t.Errorf("too many requests: %d", n)
return
}
req := requests[n]
n++
// Check request.
if g, w := r.URL.Path, req.path; g != w {
t.Errorf("request[%d] got path %s, want %s", n, g, w)
}
want, _ := url.ParseQuery(req.query)
for k := range want {
if g, w := r.FormValue(k), want.Get(k); g != w {
t.Errorf("query[%s] = %s, want %s", k, g, w)
}
}
if g, w := r.Header.Get("Authorization"), req.auth; w != "" && g != w {
t.Errorf("Authorization: %v, want %v", g, w)
}
// Send response.
w.Header().Set("Content-Type", req.contenttype)
io.WriteString(w, req.body)
}
server := httptest.NewServer(http.HandlerFunc(handler))
defer server.Close()
config := &Config{
ClientId: "cl13nt1d",
ClientSecret: "s3cr3t",
Scope: "https://example.net/scope",
AuthURL: server.URL + "/auth",
TokenURL: server.URL + "/token",
}
// TODO(adg): test AuthCodeURL
transport := &Transport{Config: config}
_, err := transport.Exchange("c0d3")
if err != nil {
t.Fatalf("Exchange: %v", err)
}
checkToken(t, transport.Token, "token1", "refreshtoken1", "idtoken1")
c := transport.Client()
resp, err := c.Get(server.URL + "/secure")
if err != nil {
t.Fatalf("Get: %v", err)
}
checkBody(t, resp, "first payload")
// test automatic refresh
transport.Expiry = time.Now().Add(-time.Hour)
resp, err = c.Get(server.URL + "/secure")
if err != nil {
t.Fatalf("Get: %v", err)
}
checkBody(t, resp, "second payload")
checkToken(t, transport.Token, "token2", "refreshtoken2", "idtoken2")
// refresh one more time, but get URL-encoded token instead of JSON
transport.Expiry = time.Now().Add(-time.Hour)
resp, err = c.Get(server.URL + "/secure")
if err != nil {
t.Fatalf("Get: %v", err)
}
checkBody(t, resp, "third payload")
checkToken(t, transport.Token, "token3", "refreshtoken3", "idtoken3")
}
func checkToken(t *testing.T, tok *Token, access, refresh, id string) {
if g, w := tok.AccessToken, access; g != w {
t.Errorf("AccessToken = %q, want %q", g, w)
}
if g, w := tok.RefreshToken, refresh; g != w {
t.Errorf("RefreshToken = %q, want %q", g, w)
}
if g, w := tok.Extra["id_token"], id; g != w {
t.Errorf("Extra['id_token'] = %q, want %q", g, w)
}
exp := tok.Expiry.Sub(time.Now())
if (time.Hour-time.Second) > exp || exp > time.Hour {
t.Errorf("Expiry = %v, want ~1 hour", exp)
}
}
func checkBody(t *testing.T, r *http.Response, body string) {
b, err := ioutil.ReadAll(r.Body)
if err != nil {
t.Error("reading reponse body: %v, want %q", err, body)
}
if g, w := string(b), body; g != w {
t.Errorf("request body mismatch: got %q, want %q", g, w)
}
}
func TestCachePermissions(t *testing.T) {
if runtime.GOOS == "windows" {
// Windows doesn't support file mode bits.
return
}
td, err := ioutil.TempDir("", "oauth-test")
if err != nil {
t.Fatalf("ioutil.TempDir: %v", err)
}
defer os.RemoveAll(td)
tempFile := filepath.Join(td, "cache-file")
cf := CacheFile(tempFile)
if err := cf.PutToken(new(Token)); err != nil {
t.Fatalf("PutToken: %v", err)
}
fi, err := os.Stat(tempFile)
if err != nil {
t.Fatalf("os.Stat: %v", err)
}
if fi.Mode()&0077 != 0 {
t.Errorf("Created cache file has mode %#o, want non-accessible to group+other", fi.Mode())
}
}

View File

@ -0,0 +1,10 @@
# This is the official list of authors for copyright purposes.
# This file is distinct from the CONTRIBUTORS files.
# See the latter for an explanation.
# Names should be added to this file as
# Name or Organization <email address>
# The email address is not required for organizations.
# Please keep the list sorted.
Google Inc.

View File

@ -0,0 +1,44 @@
# This is the official list of people who can contribute
# (and typically have contributed) code to the repository.
# The AUTHORS file lists the copyright holders; this file
# lists people. For example, Google employees are listed here
# but not in AUTHORS, because Google holds the copyright.
#
# The submission process automatically checks to make sure
# that people submitting code are listed in this file (by email address).
#
# Names should be added to this file only after verifying that
# the individual or the individual's organization has agreed to
# the appropriate Contributor License Agreement, found here:
#
# http://code.google.com/legal/individual-cla-v1.0.html
# http://code.google.com/legal/corporate-cla-v1.0.html
#
# The agreement for individuals can be filled out on the web.
#
# When adding J Random Contributor's name to this file,
# either J's name or J's organization's name should be
# added to the AUTHORS file, depending on whether the
# individual or corporate CLA was used.
# Names should be added to this file like so:
# Name <email address>
#
# An entry with two email addresses specifies that the
# first address should be used in the submit logs and
# that the second address should be recognized as the
# same person when interacting with Rietveld.
# Please keep the list sorted.
Alain Vongsouvanhalainv <alainv@google.com>
Andrew Gerrand <adg@golang.org>
Brad Fitzpatrick <bradfitz@golang.org>
Francesc Campoy <campoy@golang.org>
Garrick Evans <garrick@google.com>
Glenn Lewis <gmlewis@google.com>
Jason Hall <jasonhall@google.com>
Johan Euphrosine <proppy@google.com>
Kostik Shtoyk <kostik@google.com>
Nick Craig-Wood <nickcw@gmail.com>
Scott Van Woudenberg <scottvw@google.com>

View File

@ -0,0 +1,27 @@
Copyright (c) 2011 Google Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -0,0 +1,9 @@
all:
go install code.google.com/p/google-api-go-client/googleapi
go install code.google.com/p/google-api-go-client/google-api-go-generator
$(GOPATH)/bin/google-api-go-generator -cache=false -install -api=*
cached:
go install code.google.com/p/google-api-go-client/googleapi
go install code.google.com/p/google-api-go-client/google-api-go-generator
$(GOPATH)/bin/google-api-go-generator -cache=true -install -api=*

View File

@ -0,0 +1,13 @@
Discovery Service:
http://code.google.com/apis/discovery/
http://code.google.com/apis/discovery/v1/reference.html
The "type" key:
http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.1
The "format" key:
http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.23
http://code.google.com/apis/discovery/v1/reference.html#parameter-format-summary
Google JSON format docs:
http://google-styleguide.googlecode.com/svn/trunk/jsoncstyleguide.xml

View File

@ -0,0 +1,10 @@
Most of this project is auto-generated.
The notable directories which are not auto-generated:
google-api-go-generator/ -- the generator itself
google-api/ -- shared common code, used by auto-generated code
examples/ -- sample code
When changing the generator, re-compile all APIs and submit the
modified APIs in the same CL as the generator changes itself.

View File

@ -0,0 +1,2 @@
Moved to:
http://code.google.com/p/google-api-go-client/issues/

View File

@ -0,0 +1,613 @@
{
"kind": "discovery#restDescription",
"etag": "\"kEk3sFj6Ef5_yR1-H3bAO6qw9mI/sSrTRK5rT30gpj08DDODwXhxRak\"",
"discoveryVersion": "v1",
"id": "adexchangebuyer:v1.1",
"name": "adexchangebuyer",
"canonicalName": "Ad Exchange Buyer",
"version": "v1.1",
"title": "Ad Exchange Buyer API",
"description": "Lets you manage your Ad Exchange Buyer account.",
"ownerDomain": "google.com",
"ownerName": "Google",
"icons": {
"x16": "http://www.google.com/images/icons/product/doubleclick-16.gif",
"x32": "http://www.google.com/images/icons/product/doubleclick-32.gif"
},
"documentationLink": "https://developers.google.com/ad-exchange/buyer-rest",
"protocol": "rest",
"baseUrl": "https://www.googleapis.com/adexchangebuyer/v1.1/",
"basePath": "/adexchangebuyer/v1.1/",
"rootUrl": "https://www.googleapis.com/",
"servicePath": "adexchangebuyer/v1.1/",
"batchPath": "batch",
"parameters": {
"alt": {
"type": "string",
"description": "Data format for the response.",
"default": "json",
"enum": [
"json"
],
"enumDescriptions": [
"Responses with Content-Type of application/json"
],
"location": "query"
},
"fields": {
"type": "string",
"description": "Selector specifying which fields to include in a partial response.",
"location": "query"
},
"key": {
"type": "string",
"description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.",
"location": "query"
},
"oauth_token": {
"type": "string",
"description": "OAuth 2.0 token for the current user.",
"location": "query"
},
"prettyPrint": {
"type": "boolean",
"description": "Returns response with indentations and line breaks.",
"default": "true",
"location": "query"
},
"quotaUser": {
"type": "string",
"description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.",
"location": "query"
},
"userIp": {
"type": "string",
"description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.",
"location": "query"
}
},
"auth": {
"oauth2": {
"scopes": {
"https://www.googleapis.com/auth/adexchange.buyer": {
"description": "Manage your Ad Exchange buyer account configuration"
}
}
}
},
"schemas": {
"Account": {
"id": "Account",
"type": "object",
"description": "Configuration data for an Ad Exchange buyer account.",
"properties": {
"bidderLocation": {
"type": "array",
"description": "Your bidder locations that have distinct URLs.",
"items": {
"type": "object",
"properties": {
"maximumQps": {
"type": "integer",
"description": "The maximum queries per second the Ad Exchange will send.",
"format": "int32"
},
"region": {
"type": "string",
"description": "The geographical region the Ad Exchange should send requests from. Only used by some quota systems, but always setting the value is recommended. Allowed values: \n- ASIA \n- EUROPE \n- US_EAST \n- US_WEST"
},
"url": {
"type": "string",
"description": "The URL to which the Ad Exchange will send bid requests."
}
}
}
},
"cookieMatchingNid": {
"type": "string",
"description": "The nid parameter value used in cookie match requests. Please contact your technical account manager if you need to change this."
},
"cookieMatchingUrl": {
"type": "string",
"description": "The base URL used in cookie match requests."
},
"id": {
"type": "integer",
"description": "Account id.",
"format": "int32"
},
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#account"
},
"maximumTotalQps": {
"type": "integer",
"description": "The sum of all bidderLocation.maximumQps values cannot exceed this. Please contact your technical account manager if you need to change this.",
"format": "int32"
}
}
},
"AccountsList": {
"id": "AccountsList",
"type": "object",
"description": "An account feed lists Ad Exchange buyer accounts that the user has access to. Each entry in the feed corresponds to a single buyer account.",
"properties": {
"items": {
"type": "array",
"description": "A list of accounts.",
"items": {
"$ref": "Account"
}
},
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#accountsList"
}
}
},
"Creative": {
"id": "Creative",
"type": "object",
"description": "A creative and its classification data.",
"properties": {
"HTMLSnippet": {
"type": "string",
"description": "The HTML snippet that displays the ad when inserted in the web page. If set, videoURL should not be set."
},
"accountId": {
"type": "integer",
"description": "Account id.",
"format": "int32",
"annotations": {
"required": [
"adexchangebuyer.creatives.insert"
]
}
},
"advertiserId": {
"type": "array",
"description": "Detected advertiser id, if any. Read-only. This field should not be set in requests.",
"items": {
"type": "string",
"format": "int64"
}
},
"advertiserName": {
"type": "string",
"description": "The name of the company being advertised in the creative.",
"annotations": {
"required": [
"adexchangebuyer.creatives.insert"
]
}
},
"attribute": {
"type": "array",
"description": "All attributes for the ads that may be shown from this snippet.",
"items": {
"type": "integer",
"format": "int32"
}
},
"buyerCreativeId": {
"type": "string",
"description": "A buyer-specific id identifying the creative in this ad.",
"annotations": {
"required": [
"adexchangebuyer.creatives.insert"
]
}
},
"clickThroughUrl": {
"type": "array",
"description": "The set of destination urls for the snippet.",
"items": {
"type": "string"
},
"annotations": {
"required": [
"adexchangebuyer.creatives.insert"
]
}
},
"disapprovalReasons": {
"type": "array",
"description": "The reason for disapproval, if any. Note that not all disapproval reasons may be categorized, so it is possible for the creative to have a status of DISAPPROVED with an empty list for disapproval_reasons. In this case, please reach out to your TAM to help debug the issue. Read-only. This field should not be set in requests.",
"items": {
"type": "string"
}
},
"height": {
"type": "integer",
"description": "Ad height.",
"format": "int32",
"annotations": {
"required": [
"adexchangebuyer.creatives.insert"
]
}
},
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#creative"
},
"productCategories": {
"type": "array",
"description": "Detected product categories, if any. Read-only. This field should not be set in requests.",
"items": {
"type": "integer",
"format": "int32"
}
},
"restrictedCategories": {
"type": "array",
"description": "All restricted categories for the ads that may be shown from this snippet.",
"items": {
"type": "integer",
"format": "int32"
}
},
"sensitiveCategories": {
"type": "array",
"description": "Detected sensitive categories, if any. Read-only. This field should not be set in requests.",
"items": {
"type": "integer",
"format": "int32"
}
},
"status": {
"type": "string",
"description": "Creative serving status. Read-only. This field should not be set in requests."
},
"vendorType": {
"type": "array",
"description": "All vendor types for the ads that may be shown from this snippet.",
"items": {
"type": "integer",
"format": "int32"
}
},
"videoURL": {
"type": "string",
"description": "The url to fetch a video ad. If set, HTMLSnippet should not be set."
},
"width": {
"type": "integer",
"description": "Ad width.",
"format": "int32",
"annotations": {
"required": [
"adexchangebuyer.creatives.insert"
]
}
}
}
},
"CreativesList": {
"id": "CreativesList",
"type": "object",
"description": "The creatives feed lists the active creatives for the Ad Exchange buyer accounts that the user has access to. Each entry in the feed corresponds to a single creative.",
"properties": {
"items": {
"type": "array",
"description": "A list of creatives.",
"items": {
"$ref": "Creative"
}
},
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#creativesList"
},
"nextPageToken": {
"type": "string",
"description": "Continuation token used to page through creatives. To retrieve the next page of results, set the next request's \"pageToken\" value to this."
}
}
},
"DirectDeal": {
"id": "DirectDeal",
"type": "object",
"description": "The configuration data for an Ad Exchange direct deal.",
"properties": {
"accountId": {
"type": "integer",
"description": "The account id of the buyer this deal is for.",
"format": "int32"
},
"advertiser": {
"type": "string",
"description": "The name of the advertiser this deal is for."
},
"currencyCode": {
"type": "string",
"description": "The currency code that applies to the fixed_cpm value. If not set then assumed to be USD."
},
"endTime": {
"type": "string",
"description": "End time for when this deal stops being active. If not set then this deal is valid until manually disabled by the publisher. In seconds since the epoch.",
"format": "int64"
},
"fixedCpm": {
"type": "string",
"description": "The fixed price for this direct deal. In cpm micros of currency according to currency_code.",
"format": "int64"
},
"id": {
"type": "string",
"description": "Deal id.",
"format": "int64"
},
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#directDeal"
},
"name": {
"type": "string",
"description": "Deal name."
},
"sellerNetwork": {
"type": "string",
"description": "The name of the publisher offering this direct deal."
},
"startTime": {
"type": "string",
"description": "Start time for when this deal becomes active. If not set then this deal is active immediately upon creation. In seconds since the epoch.",
"format": "int64"
}
}
},
"DirectDealsList": {
"id": "DirectDealsList",
"type": "object",
"description": "A direct deals feed lists Direct Deals the Ad Exchange buyer account has access to. This includes direct deals set up for the buyer account as well as its merged stream seats.",
"properties": {
"directDeals": {
"type": "array",
"description": "A list of direct deals relevant for your account.",
"items": {
"$ref": "DirectDeal"
}
},
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#directDealsList"
}
}
}
},
"resources": {
"accounts": {
"methods": {
"get": {
"id": "adexchangebuyer.accounts.get",
"path": "accounts/{id}",
"httpMethod": "GET",
"description": "Gets one account by ID.",
"parameters": {
"id": {
"type": "integer",
"description": "The account id",
"required": true,
"format": "int32",
"location": "path"
}
},
"parameterOrder": [
"id"
],
"response": {
"$ref": "Account"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
},
"list": {
"id": "adexchangebuyer.accounts.list",
"path": "accounts",
"httpMethod": "GET",
"description": "Retrieves the authenticated user's list of accounts.",
"response": {
"$ref": "AccountsList"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
},
"patch": {
"id": "adexchangebuyer.accounts.patch",
"path": "accounts/{id}",
"httpMethod": "PATCH",
"description": "Updates an existing account. This method supports patch semantics.",
"parameters": {
"id": {
"type": "integer",
"description": "The account id",
"required": true,
"format": "int32",
"location": "path"
}
},
"parameterOrder": [
"id"
],
"request": {
"$ref": "Account"
},
"response": {
"$ref": "Account"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
},
"update": {
"id": "adexchangebuyer.accounts.update",
"path": "accounts/{id}",
"httpMethod": "PUT",
"description": "Updates an existing account.",
"parameters": {
"id": {
"type": "integer",
"description": "The account id",
"required": true,
"format": "int32",
"location": "path"
}
},
"parameterOrder": [
"id"
],
"request": {
"$ref": "Account"
},
"response": {
"$ref": "Account"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
}
}
},
"creatives": {
"methods": {
"get": {
"id": "adexchangebuyer.creatives.get",
"path": "creatives/{accountId}/{buyerCreativeId}",
"httpMethod": "GET",
"description": "Gets the status for a single creative. A creative will be available 30-40 minutes after submission.",
"parameters": {
"accountId": {
"type": "integer",
"description": "The id for the account that will serve this creative.",
"required": true,
"format": "int32",
"location": "path"
},
"buyerCreativeId": {
"type": "string",
"description": "The buyer-specific id for this creative.",
"required": true,
"location": "path"
}
},
"parameterOrder": [
"accountId",
"buyerCreativeId"
],
"response": {
"$ref": "Creative"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
},
"insert": {
"id": "adexchangebuyer.creatives.insert",
"path": "creatives",
"httpMethod": "POST",
"description": "Submit a new creative.",
"request": {
"$ref": "Creative"
},
"response": {
"$ref": "Creative"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
},
"list": {
"id": "adexchangebuyer.creatives.list",
"path": "creatives",
"httpMethod": "GET",
"description": "Retrieves a list of the authenticated user's active creatives. A creative will be available 30-40 minutes after submission.",
"parameters": {
"maxResults": {
"type": "integer",
"description": "Maximum number of entries returned on one result page. If not set, the default is 100. Optional.",
"format": "uint32",
"minimum": "1",
"maximum": "1000",
"location": "query"
},
"pageToken": {
"type": "string",
"description": "A continuation token, used to page through ad clients. To retrieve the next page, set this parameter to the value of \"nextPageToken\" from the previous response. Optional.",
"location": "query"
},
"statusFilter": {
"type": "string",
"description": "When specified, only creatives having the given status are returned.",
"enum": [
"approved",
"disapproved",
"not_checked"
],
"enumDescriptions": [
"Creatives which have been approved.",
"Creatives which have been disapproved.",
"Creatives whose status is not yet checked."
],
"location": "query"
}
},
"response": {
"$ref": "CreativesList"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
}
}
},
"directDeals": {
"methods": {
"get": {
"id": "adexchangebuyer.directDeals.get",
"path": "directdeals/{id}",
"httpMethod": "GET",
"description": "Gets one direct deal by ID.",
"parameters": {
"id": {
"type": "string",
"description": "The direct deal id",
"required": true,
"format": "int64",
"location": "path"
}
},
"parameterOrder": [
"id"
],
"response": {
"$ref": "DirectDeal"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
},
"list": {
"id": "adexchangebuyer.directDeals.list",
"path": "directdeals",
"httpMethod": "GET",
"description": "Retrieves the authenticated user's list of direct deals.",
"response": {
"$ref": "DirectDealsList"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
}
}
}
}
}

View File

@ -0,0 +1,907 @@
// Package adexchangebuyer provides access to the Ad Exchange Buyer API.
//
// See https://developers.google.com/ad-exchange/buyer-rest
//
// Usage example:
//
// import "code.google.com/p/google-api-go-client/adexchangebuyer/v1.1"
// ...
// adexchangebuyerService, err := adexchangebuyer.New(oauthHttpClient)
package adexchangebuyer
import (
"bytes"
"code.google.com/p/google-api-go-client/googleapi"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
)
// Always reference these packages, just in case the auto-generated code
// below doesn't.
var _ = bytes.NewBuffer
var _ = strconv.Itoa
var _ = fmt.Sprintf
var _ = json.NewDecoder
var _ = io.Copy
var _ = url.Parse
var _ = googleapi.Version
var _ = errors.New
var _ = strings.Replace
const apiId = "adexchangebuyer:v1.1"
const apiName = "adexchangebuyer"
const apiVersion = "v1.1"
const basePath = "https://www.googleapis.com/adexchangebuyer/v1.1/"
// OAuth2 scopes used by this API.
const (
// Manage your Ad Exchange buyer account configuration
AdexchangeBuyerScope = "https://www.googleapis.com/auth/adexchange.buyer"
)
func New(client *http.Client) (*Service, error) {
if client == nil {
return nil, errors.New("client is nil")
}
s := &Service{client: client, BasePath: basePath}
s.Accounts = NewAccountsService(s)
s.Creatives = NewCreativesService(s)
s.DirectDeals = NewDirectDealsService(s)
return s, nil
}
type Service struct {
client *http.Client
BasePath string // API endpoint base URL
Accounts *AccountsService
Creatives *CreativesService
DirectDeals *DirectDealsService
}
func NewAccountsService(s *Service) *AccountsService {
rs := &AccountsService{s: s}
return rs
}
type AccountsService struct {
s *Service
}
func NewCreativesService(s *Service) *CreativesService {
rs := &CreativesService{s: s}
return rs
}
type CreativesService struct {
s *Service
}
func NewDirectDealsService(s *Service) *DirectDealsService {
rs := &DirectDealsService{s: s}
return rs
}
type DirectDealsService struct {
s *Service
}
type Account struct {
// BidderLocation: Your bidder locations that have distinct URLs.
BidderLocation []*AccountBidderLocation `json:"bidderLocation,omitempty"`
// CookieMatchingNid: The nid parameter value used in cookie match
// requests. Please contact your technical account manager if you need
// to change this.
CookieMatchingNid string `json:"cookieMatchingNid,omitempty"`
// CookieMatchingUrl: The base URL used in cookie match requests.
CookieMatchingUrl string `json:"cookieMatchingUrl,omitempty"`
// Id: Account id.
Id int64 `json:"id,omitempty"`
// Kind: Resource type.
Kind string `json:"kind,omitempty"`
// MaximumTotalQps: The sum of all bidderLocation.maximumQps values
// cannot exceed this. Please contact your technical account manager if
// you need to change this.
MaximumTotalQps int64 `json:"maximumTotalQps,omitempty"`
}
type AccountBidderLocation struct {
// MaximumQps: The maximum queries per second the Ad Exchange will send.
MaximumQps int64 `json:"maximumQps,omitempty"`
// Region: The geographical region the Ad Exchange should send requests
// from. Only used by some quota systems, but always setting the value
// is recommended. Allowed values:
// - ASIA
// - EUROPE
// - US_EAST
// -
// US_WEST
Region string `json:"region,omitempty"`
// Url: The URL to which the Ad Exchange will send bid requests.
Url string `json:"url,omitempty"`
}
type AccountsList struct {
// Items: A list of accounts.
Items []*Account `json:"items,omitempty"`
// Kind: Resource type.
Kind string `json:"kind,omitempty"`
}
type Creative struct {
// HTMLSnippet: The HTML snippet that displays the ad when inserted in
// the web page. If set, videoURL should not be set.
HTMLSnippet string `json:"HTMLSnippet,omitempty"`
// AccountId: Account id.
AccountId int64 `json:"accountId,omitempty"`
// AdvertiserId: Detected advertiser id, if any. Read-only. This field
// should not be set in requests.
AdvertiserId googleapi.Int64s `json:"advertiserId,omitempty"`
// AdvertiserName: The name of the company being advertised in the
// creative.
AdvertiserName string `json:"advertiserName,omitempty"`
// Attribute: All attributes for the ads that may be shown from this
// snippet.
Attribute []int64 `json:"attribute,omitempty"`
// BuyerCreativeId: A buyer-specific id identifying the creative in this
// ad.
BuyerCreativeId string `json:"buyerCreativeId,omitempty"`
// ClickThroughUrl: The set of destination urls for the snippet.
ClickThroughUrl []string `json:"clickThroughUrl,omitempty"`
// DisapprovalReasons: The reason for disapproval, if any. Note that not
// all disapproval reasons may be categorized, so it is possible for the
// creative to have a status of DISAPPROVED with an empty list for
// disapproval_reasons. In this case, please reach out to your TAM to
// help debug the issue. Read-only. This field should not be set in
// requests.
DisapprovalReasons []string `json:"disapprovalReasons,omitempty"`
// Height: Ad height.
Height int64 `json:"height,omitempty"`
// Kind: Resource type.
Kind string `json:"kind,omitempty"`
// ProductCategories: Detected product categories, if any. Read-only.
// This field should not be set in requests.
ProductCategories []int64 `json:"productCategories,omitempty"`
// RestrictedCategories: All restricted categories for the ads that may
// be shown from this snippet.
RestrictedCategories []int64 `json:"restrictedCategories,omitempty"`
// SensitiveCategories: Detected sensitive categories, if any.
// Read-only. This field should not be set in requests.
SensitiveCategories []int64 `json:"sensitiveCategories,omitempty"`
// Status: Creative serving status. Read-only. This field should not be
// set in requests.
Status string `json:"status,omitempty"`
// VendorType: All vendor types for the ads that may be shown from this
// snippet.
VendorType []int64 `json:"vendorType,omitempty"`
// VideoURL: The url to fetch a video ad. If set, HTMLSnippet should not
// be set.
VideoURL string `json:"videoURL,omitempty"`
// Width: Ad width.
Width int64 `json:"width,omitempty"`
}
type CreativesList struct {
// Items: A list of creatives.
Items []*Creative `json:"items,omitempty"`
// Kind: Resource type.
Kind string `json:"kind,omitempty"`
// NextPageToken: Continuation token used to page through creatives. To
// retrieve the next page of results, set the next request's "pageToken"
// value to this.
NextPageToken string `json:"nextPageToken,omitempty"`
}
type DirectDeal struct {
// AccountId: The account id of the buyer this deal is for.
AccountId int64 `json:"accountId,omitempty"`
// Advertiser: The name of the advertiser this deal is for.
Advertiser string `json:"advertiser,omitempty"`
// CurrencyCode: The currency code that applies to the fixed_cpm value.
// If not set then assumed to be USD.
CurrencyCode string `json:"currencyCode,omitempty"`
// EndTime: End time for when this deal stops being active. If not set
// then this deal is valid until manually disabled by the publisher. In
// seconds since the epoch.
EndTime int64 `json:"endTime,omitempty,string"`
// FixedCpm: The fixed price for this direct deal. In cpm micros of
// currency according to currency_code.
FixedCpm int64 `json:"fixedCpm,omitempty,string"`
// Id: Deal id.
Id int64 `json:"id,omitempty,string"`
// Kind: Resource type.
Kind string `json:"kind,omitempty"`
// Name: Deal name.
Name string `json:"name,omitempty"`
// SellerNetwork: The name of the publisher offering this direct deal.
SellerNetwork string `json:"sellerNetwork,omitempty"`
// StartTime: Start time for when this deal becomes active. If not set
// then this deal is active immediately upon creation. In seconds since
// the epoch.
StartTime int64 `json:"startTime,omitempty,string"`
}
type DirectDealsList struct {
// DirectDeals: A list of direct deals relevant for your account.
DirectDeals []*DirectDeal `json:"directDeals,omitempty"`
// Kind: Resource type.
Kind string `json:"kind,omitempty"`
}
// method id "adexchangebuyer.accounts.get":
type AccountsGetCall struct {
s *Service
id int64
opt_ map[string]interface{}
}
// Get: Gets one account by ID.
func (r *AccountsService) Get(id int64) *AccountsGetCall {
c := &AccountsGetCall{s: r.s, opt_: make(map[string]interface{})}
c.id = id
return c
}
func (c *AccountsGetCall) Do() (*Account, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
urls := googleapi.ResolveRelative(c.s.BasePath, "accounts/{id}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{id}", strconv.FormatInt(c.id, 10), 1)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(Account)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets one account by ID.",
// "httpMethod": "GET",
// "id": "adexchangebuyer.accounts.get",
// "parameterOrder": [
// "id"
// ],
// "parameters": {
// "id": {
// "description": "The account id",
// "format": "int32",
// "location": "path",
// "required": true,
// "type": "integer"
// }
// },
// "path": "accounts/{id}",
// "response": {
// "$ref": "Account"
// },
// "scopes": [
// "https://www.googleapis.com/auth/adexchange.buyer"
// ]
// }
}
// method id "adexchangebuyer.accounts.list":
type AccountsListCall struct {
s *Service
opt_ map[string]interface{}
}
// List: Retrieves the authenticated user's list of accounts.
func (r *AccountsService) List() *AccountsListCall {
c := &AccountsListCall{s: r.s, opt_: make(map[string]interface{})}
return c
}
func (c *AccountsListCall) Do() (*AccountsList, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
urls := googleapi.ResolveRelative(c.s.BasePath, "accounts")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(AccountsList)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves the authenticated user's list of accounts.",
// "httpMethod": "GET",
// "id": "adexchangebuyer.accounts.list",
// "path": "accounts",
// "response": {
// "$ref": "AccountsList"
// },
// "scopes": [
// "https://www.googleapis.com/auth/adexchange.buyer"
// ]
// }
}
// method id "adexchangebuyer.accounts.patch":
type AccountsPatchCall struct {
s *Service
id int64
account *Account
opt_ map[string]interface{}
}
// Patch: Updates an existing account. This method supports patch
// semantics.
func (r *AccountsService) Patch(id int64, account *Account) *AccountsPatchCall {
c := &AccountsPatchCall{s: r.s, opt_: make(map[string]interface{})}
c.id = id
c.account = account
return c
}
func (c *AccountsPatchCall) Do() (*Account, error) {
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.account)
if err != nil {
return nil, err
}
ctype := "application/json"
params := make(url.Values)
params.Set("alt", "json")
urls := googleapi.ResolveRelative(c.s.BasePath, "accounts/{id}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("PATCH", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{id}", strconv.FormatInt(c.id, 10), 1)
googleapi.SetOpaque(req.URL)
req.Header.Set("Content-Type", ctype)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(Account)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates an existing account. This method supports patch semantics.",
// "httpMethod": "PATCH",
// "id": "adexchangebuyer.accounts.patch",
// "parameterOrder": [
// "id"
// ],
// "parameters": {
// "id": {
// "description": "The account id",
// "format": "int32",
// "location": "path",
// "required": true,
// "type": "integer"
// }
// },
// "path": "accounts/{id}",
// "request": {
// "$ref": "Account"
// },
// "response": {
// "$ref": "Account"
// },
// "scopes": [
// "https://www.googleapis.com/auth/adexchange.buyer"
// ]
// }
}
// method id "adexchangebuyer.accounts.update":
type AccountsUpdateCall struct {
s *Service
id int64
account *Account
opt_ map[string]interface{}
}
// Update: Updates an existing account.
func (r *AccountsService) Update(id int64, account *Account) *AccountsUpdateCall {
c := &AccountsUpdateCall{s: r.s, opt_: make(map[string]interface{})}
c.id = id
c.account = account
return c
}
func (c *AccountsUpdateCall) Do() (*Account, error) {
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.account)
if err != nil {
return nil, err
}
ctype := "application/json"
params := make(url.Values)
params.Set("alt", "json")
urls := googleapi.ResolveRelative(c.s.BasePath, "accounts/{id}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("PUT", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{id}", strconv.FormatInt(c.id, 10), 1)
googleapi.SetOpaque(req.URL)
req.Header.Set("Content-Type", ctype)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(Account)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates an existing account.",
// "httpMethod": "PUT",
// "id": "adexchangebuyer.accounts.update",
// "parameterOrder": [
// "id"
// ],
// "parameters": {
// "id": {
// "description": "The account id",
// "format": "int32",
// "location": "path",
// "required": true,
// "type": "integer"
// }
// },
// "path": "accounts/{id}",
// "request": {
// "$ref": "Account"
// },
// "response": {
// "$ref": "Account"
// },
// "scopes": [
// "https://www.googleapis.com/auth/adexchange.buyer"
// ]
// }
}
// method id "adexchangebuyer.creatives.get":
type CreativesGetCall struct {
s *Service
accountId int64
buyerCreativeId string
opt_ map[string]interface{}
}
// Get: Gets the status for a single creative. A creative will be
// available 30-40 minutes after submission.
func (r *CreativesService) Get(accountId int64, buyerCreativeId string) *CreativesGetCall {
c := &CreativesGetCall{s: r.s, opt_: make(map[string]interface{})}
c.accountId = accountId
c.buyerCreativeId = buyerCreativeId
return c
}
func (c *CreativesGetCall) Do() (*Creative, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
urls := googleapi.ResolveRelative(c.s.BasePath, "creatives/{accountId}/{buyerCreativeId}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{accountId}", strconv.FormatInt(c.accountId, 10), 1)
req.URL.Path = strings.Replace(req.URL.Path, "{buyerCreativeId}", url.QueryEscape(c.buyerCreativeId), 1)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(Creative)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets the status for a single creative. A creative will be available 30-40 minutes after submission.",
// "httpMethod": "GET",
// "id": "adexchangebuyer.creatives.get",
// "parameterOrder": [
// "accountId",
// "buyerCreativeId"
// ],
// "parameters": {
// "accountId": {
// "description": "The id for the account that will serve this creative.",
// "format": "int32",
// "location": "path",
// "required": true,
// "type": "integer"
// },
// "buyerCreativeId": {
// "description": "The buyer-specific id for this creative.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "creatives/{accountId}/{buyerCreativeId}",
// "response": {
// "$ref": "Creative"
// },
// "scopes": [
// "https://www.googleapis.com/auth/adexchange.buyer"
// ]
// }
}
// method id "adexchangebuyer.creatives.insert":
type CreativesInsertCall struct {
s *Service
creative *Creative
opt_ map[string]interface{}
}
// Insert: Submit a new creative.
func (r *CreativesService) Insert(creative *Creative) *CreativesInsertCall {
c := &CreativesInsertCall{s: r.s, opt_: make(map[string]interface{})}
c.creative = creative
return c
}
func (c *CreativesInsertCall) Do() (*Creative, error) {
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.creative)
if err != nil {
return nil, err
}
ctype := "application/json"
params := make(url.Values)
params.Set("alt", "json")
urls := googleapi.ResolveRelative(c.s.BasePath, "creatives")
urls += "?" + params.Encode()
req, _ := http.NewRequest("POST", urls, body)
googleapi.SetOpaque(req.URL)
req.Header.Set("Content-Type", ctype)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(Creative)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Submit a new creative.",
// "httpMethod": "POST",
// "id": "adexchangebuyer.creatives.insert",
// "path": "creatives",
// "request": {
// "$ref": "Creative"
// },
// "response": {
// "$ref": "Creative"
// },
// "scopes": [
// "https://www.googleapis.com/auth/adexchange.buyer"
// ]
// }
}
// method id "adexchangebuyer.creatives.list":
type CreativesListCall struct {
s *Service
opt_ map[string]interface{}
}
// List: Retrieves a list of the authenticated user's active creatives.
// A creative will be available 30-40 minutes after submission.
func (r *CreativesService) List() *CreativesListCall {
c := &CreativesListCall{s: r.s, opt_: make(map[string]interface{})}
return c
}
// MaxResults sets the optional parameter "maxResults": Maximum number
// of entries returned on one result page. If not set, the default is
// 100.
func (c *CreativesListCall) MaxResults(maxResults int64) *CreativesListCall {
c.opt_["maxResults"] = maxResults
return c
}
// PageToken sets the optional parameter "pageToken": A continuation
// token, used to page through ad clients. To retrieve the next page,
// set this parameter to the value of "nextPageToken" from the previous
// response.
func (c *CreativesListCall) PageToken(pageToken string) *CreativesListCall {
c.opt_["pageToken"] = pageToken
return c
}
// StatusFilter sets the optional parameter "statusFilter": When
// specified, only creatives having the given status are returned.
func (c *CreativesListCall) StatusFilter(statusFilter string) *CreativesListCall {
c.opt_["statusFilter"] = statusFilter
return c
}
func (c *CreativesListCall) Do() (*CreativesList, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["maxResults"]; ok {
params.Set("maxResults", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["pageToken"]; ok {
params.Set("pageToken", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["statusFilter"]; ok {
params.Set("statusFilter", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "creatives")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(CreativesList)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves a list of the authenticated user's active creatives. A creative will be available 30-40 minutes after submission.",
// "httpMethod": "GET",
// "id": "adexchangebuyer.creatives.list",
// "parameters": {
// "maxResults": {
// "description": "Maximum number of entries returned on one result page. If not set, the default is 100. Optional.",
// "format": "uint32",
// "location": "query",
// "maximum": "1000",
// "minimum": "1",
// "type": "integer"
// },
// "pageToken": {
// "description": "A continuation token, used to page through ad clients. To retrieve the next page, set this parameter to the value of \"nextPageToken\" from the previous response. Optional.",
// "location": "query",
// "type": "string"
// },
// "statusFilter": {
// "description": "When specified, only creatives having the given status are returned.",
// "enum": [
// "approved",
// "disapproved",
// "not_checked"
// ],
// "enumDescriptions": [
// "Creatives which have been approved.",
// "Creatives which have been disapproved.",
// "Creatives whose status is not yet checked."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "creatives",
// "response": {
// "$ref": "CreativesList"
// },
// "scopes": [
// "https://www.googleapis.com/auth/adexchange.buyer"
// ]
// }
}
// method id "adexchangebuyer.directDeals.get":
type DirectDealsGetCall struct {
s *Service
id int64
opt_ map[string]interface{}
}
// Get: Gets one direct deal by ID.
func (r *DirectDealsService) Get(id int64) *DirectDealsGetCall {
c := &DirectDealsGetCall{s: r.s, opt_: make(map[string]interface{})}
c.id = id
return c
}
func (c *DirectDealsGetCall) Do() (*DirectDeal, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
urls := googleapi.ResolveRelative(c.s.BasePath, "directdeals/{id}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{id}", strconv.FormatInt(c.id, 10), 1)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(DirectDeal)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets one direct deal by ID.",
// "httpMethod": "GET",
// "id": "adexchangebuyer.directDeals.get",
// "parameterOrder": [
// "id"
// ],
// "parameters": {
// "id": {
// "description": "The direct deal id",
// "format": "int64",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "directdeals/{id}",
// "response": {
// "$ref": "DirectDeal"
// },
// "scopes": [
// "https://www.googleapis.com/auth/adexchange.buyer"
// ]
// }
}
// method id "adexchangebuyer.directDeals.list":
type DirectDealsListCall struct {
s *Service
opt_ map[string]interface{}
}
// List: Retrieves the authenticated user's list of direct deals.
func (r *DirectDealsService) List() *DirectDealsListCall {
c := &DirectDealsListCall{s: r.s, opt_: make(map[string]interface{})}
return c
}
func (c *DirectDealsListCall) Do() (*DirectDealsList, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
urls := googleapi.ResolveRelative(c.s.BasePath, "directdeals")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(DirectDealsList)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves the authenticated user's list of direct deals.",
// "httpMethod": "GET",
// "id": "adexchangebuyer.directDeals.list",
// "path": "directdeals",
// "response": {
// "$ref": "DirectDealsList"
// },
// "scopes": [
// "https://www.googleapis.com/auth/adexchange.buyer"
// ]
// }
}

View File

@ -0,0 +1,824 @@
{
"kind": "discovery#restDescription",
"etag": "\"kEk3sFj6Ef5_yR1-H3bAO6qw9mI/mlESaLdrZYKCTBOwQidwTWARgSg\"",
"discoveryVersion": "v1",
"id": "adexchangebuyer:v1.2",
"name": "adexchangebuyer",
"canonicalName": "Ad Exchange Buyer",
"version": "v1.2",
"title": "Ad Exchange Buyer API",
"description": "Lets you manage your Ad Exchange Buyer account.",
"ownerDomain": "google.com",
"ownerName": "Google",
"icons": {
"x16": "http://www.google.com/images/icons/product/doubleclick-16.gif",
"x32": "http://www.google.com/images/icons/product/doubleclick-32.gif"
},
"documentationLink": "https://developers.google.com/ad-exchange/buyer-rest",
"protocol": "rest",
"baseUrl": "https://www.googleapis.com/adexchangebuyer/v1.2/",
"basePath": "/adexchangebuyer/v1.2/",
"rootUrl": "https://www.googleapis.com/",
"servicePath": "adexchangebuyer/v1.2/",
"batchPath": "batch",
"parameters": {
"alt": {
"type": "string",
"description": "Data format for the response.",
"default": "json",
"enum": [
"json"
],
"enumDescriptions": [
"Responses with Content-Type of application/json"
],
"location": "query"
},
"fields": {
"type": "string",
"description": "Selector specifying which fields to include in a partial response.",
"location": "query"
},
"key": {
"type": "string",
"description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.",
"location": "query"
},
"oauth_token": {
"type": "string",
"description": "OAuth 2.0 token for the current user.",
"location": "query"
},
"prettyPrint": {
"type": "boolean",
"description": "Returns response with indentations and line breaks.",
"default": "true",
"location": "query"
},
"quotaUser": {
"type": "string",
"description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.",
"location": "query"
},
"userIp": {
"type": "string",
"description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.",
"location": "query"
}
},
"auth": {
"oauth2": {
"scopes": {
"https://www.googleapis.com/auth/adexchange.buyer": {
"description": "Manage your Ad Exchange buyer account configuration"
}
}
}
},
"schemas": {
"Account": {
"id": "Account",
"type": "object",
"description": "Configuration data for an Ad Exchange buyer account.",
"properties": {
"bidderLocation": {
"type": "array",
"description": "Your bidder locations that have distinct URLs.",
"items": {
"type": "object",
"properties": {
"maximumQps": {
"type": "integer",
"description": "The maximum queries per second the Ad Exchange will send.",
"format": "int32"
},
"region": {
"type": "string",
"description": "The geographical region the Ad Exchange should send requests from. Only used by some quota systems, but always setting the value is recommended. Allowed values: \n- ASIA \n- EUROPE \n- US_EAST \n- US_WEST"
},
"url": {
"type": "string",
"description": "The URL to which the Ad Exchange will send bid requests."
}
}
}
},
"cookieMatchingNid": {
"type": "string",
"description": "The nid parameter value used in cookie match requests. Please contact your technical account manager if you need to change this."
},
"cookieMatchingUrl": {
"type": "string",
"description": "The base URL used in cookie match requests."
},
"id": {
"type": "integer",
"description": "Account id.",
"format": "int32"
},
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#account"
},
"maximumTotalQps": {
"type": "integer",
"description": "The sum of all bidderLocation.maximumQps values cannot exceed this. Please contact your technical account manager if you need to change this.",
"format": "int32"
}
}
},
"AccountsList": {
"id": "AccountsList",
"type": "object",
"description": "An account feed lists Ad Exchange buyer accounts that the user has access to. Each entry in the feed corresponds to a single buyer account.",
"properties": {
"items": {
"type": "array",
"description": "A list of accounts.",
"items": {
"$ref": "Account"
}
},
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#accountsList"
}
}
},
"Creative": {
"id": "Creative",
"type": "object",
"description": "A creative and its classification data.",
"properties": {
"HTMLSnippet": {
"type": "string",
"description": "The HTML snippet that displays the ad when inserted in the web page. If set, videoURL should not be set."
},
"accountId": {
"type": "integer",
"description": "Account id.",
"format": "int32",
"annotations": {
"required": [
"adexchangebuyer.creatives.insert"
]
}
},
"advertiserId": {
"type": "array",
"description": "Detected advertiser id, if any. Read-only. This field should not be set in requests.",
"items": {
"type": "string",
"format": "int64"
}
},
"advertiserName": {
"type": "string",
"description": "The name of the company being advertised in the creative.",
"annotations": {
"required": [
"adexchangebuyer.creatives.insert"
]
}
},
"agencyId": {
"type": "string",
"description": "The agency id for this creative.",
"format": "int64"
},
"attribute": {
"type": "array",
"description": "All attributes for the ads that may be shown from this snippet.",
"items": {
"type": "integer",
"format": "int32"
}
},
"buyerCreativeId": {
"type": "string",
"description": "A buyer-specific id identifying the creative in this ad.",
"annotations": {
"required": [
"adexchangebuyer.creatives.insert"
]
}
},
"clickThroughUrl": {
"type": "array",
"description": "The set of destination urls for the snippet.",
"items": {
"type": "string"
},
"annotations": {
"required": [
"adexchangebuyer.creatives.insert"
]
}
},
"corrections": {
"type": "array",
"description": "Shows any corrections that were applied to this creative. Read-only. This field should not be set in requests.",
"items": {
"type": "object",
"properties": {
"details": {
"type": "array",
"description": "Additional details about the correction.",
"items": {
"type": "string"
}
},
"reason": {
"type": "string",
"description": "The type of correction that was applied to the creative."
}
}
}
},
"disapprovalReasons": {
"type": "array",
"description": "The reasons for disapproval, if any. Note that not all disapproval reasons may be categorized, so it is possible for the creative to have a status of DISAPPROVED with an empty list for disapproval_reasons. In this case, please reach out to your TAM to help debug the issue. Read-only. This field should not be set in requests.",
"items": {
"type": "object",
"properties": {
"details": {
"type": "array",
"description": "Additional details about the reason for disapproval.",
"items": {
"type": "string"
}
},
"reason": {
"type": "string",
"description": "The categorized reason for disapproval."
}
}
}
},
"height": {
"type": "integer",
"description": "Ad height.",
"format": "int32",
"annotations": {
"required": [
"adexchangebuyer.creatives.insert"
]
}
},
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#creative"
},
"productCategories": {
"type": "array",
"description": "Detected product categories, if any. Read-only. This field should not be set in requests.",
"items": {
"type": "integer",
"format": "int32"
}
},
"restrictedCategories": {
"type": "array",
"description": "All restricted categories for the ads that may be shown from this snippet.",
"items": {
"type": "integer",
"format": "int32"
}
},
"sensitiveCategories": {
"type": "array",
"description": "Detected sensitive categories, if any. Read-only. This field should not be set in requests.",
"items": {
"type": "integer",
"format": "int32"
}
},
"status": {
"type": "string",
"description": "Creative serving status. Read-only. This field should not be set in requests."
},
"vendorType": {
"type": "array",
"description": "All vendor types for the ads that may be shown from this snippet.",
"items": {
"type": "integer",
"format": "int32"
}
},
"videoURL": {
"type": "string",
"description": "The url to fetch a video ad. If set, HTMLSnippet should not be set."
},
"width": {
"type": "integer",
"description": "Ad width.",
"format": "int32",
"annotations": {
"required": [
"adexchangebuyer.creatives.insert"
]
}
}
}
},
"CreativesList": {
"id": "CreativesList",
"type": "object",
"description": "The creatives feed lists the active creatives for the Ad Exchange buyer accounts that the user has access to. Each entry in the feed corresponds to a single creative.",
"properties": {
"items": {
"type": "array",
"description": "A list of creatives.",
"items": {
"$ref": "Creative"
}
},
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#creativesList"
},
"nextPageToken": {
"type": "string",
"description": "Continuation token used to page through creatives. To retrieve the next page of results, set the next request's \"pageToken\" value to this."
}
}
},
"DirectDeal": {
"id": "DirectDeal",
"type": "object",
"description": "The configuration data for an Ad Exchange direct deal.",
"properties": {
"accountId": {
"type": "integer",
"description": "The account id of the buyer this deal is for.",
"format": "int32"
},
"advertiser": {
"type": "string",
"description": "The name of the advertiser this deal is for."
},
"currencyCode": {
"type": "string",
"description": "The currency code that applies to the fixed_cpm value. If not set then assumed to be USD."
},
"endTime": {
"type": "string",
"description": "End time for when this deal stops being active. If not set then this deal is valid until manually disabled by the publisher. In seconds since the epoch.",
"format": "int64"
},
"fixedCpm": {
"type": "string",
"description": "The fixed price for this direct deal. In cpm micros of currency according to currency_code. If set, then this deal is eligible for the fixed price tier of buying (highest priority, pay exactly the configured fixed price).",
"format": "int64"
},
"id": {
"type": "string",
"description": "Deal id.",
"format": "int64"
},
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#directDeal"
},
"name": {
"type": "string",
"description": "Deal name."
},
"privateExchangeMinCpm": {
"type": "string",
"description": "The minimum price for this direct deal. In cpm micros of currency according to currency_code. If set, then this deal is eligible for the private exchange tier of buying (below fixed price priority, run as a second price auction).",
"format": "int64"
},
"sellerNetwork": {
"type": "string",
"description": "The name of the publisher offering this direct deal."
},
"startTime": {
"type": "string",
"description": "Start time for when this deal becomes active. If not set then this deal is active immediately upon creation. In seconds since the epoch.",
"format": "int64"
}
}
},
"DirectDealsList": {
"id": "DirectDealsList",
"type": "object",
"description": "A direct deals feed lists Direct Deals the Ad Exchange buyer account has access to. This includes direct deals set up for the buyer account as well as its merged stream seats.",
"properties": {
"directDeals": {
"type": "array",
"description": "A list of direct deals relevant for your account.",
"items": {
"$ref": "DirectDeal"
}
},
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#directDealsList"
}
}
},
"PerformanceReport": {
"id": "PerformanceReport",
"type": "object",
"description": "The configuration data for an Ad Exchange performance report list. TODO(nathanbullock): need to add some release tests before releasing this. https://sites.google.com/a/google.com/adx-integration/Home/engineering/binary-releases/rtb-api-release https://cs.corp.google.com/#piper///depot/google3/contentads/adx/tools/rtb_api/adxrtb.py",
"properties": {
"calloutStatusRate": {
"type": "array",
"description": "Rate of various prefiltering statuses per match. Please refer to the callout-status-codes.txt file for different statuses.",
"items": {
"type": "any"
}
},
"cookieMatcherStatusRate": {
"type": "array",
"description": "Average QPS for cookie matcher operations.",
"items": {
"type": "any"
}
},
"creativeStatusRate": {
"type": "array",
"description": "Rate of ads with a given status. Please refer to the creative-status-codes.txt file for different statuses.",
"items": {
"type": "any"
}
},
"hostedMatchStatusRate": {
"type": "array",
"description": "Average QPS for hosted match operations.",
"items": {
"type": "any"
}
},
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#performanceReport"
},
"latency50thPercentile": {
"type": "number",
"description": "The 50th percentile round trip latency(ms) as perceived from Google servers for the duration period covered by the report.",
"format": "double"
},
"latency85thPercentile": {
"type": "number",
"description": "The 85th percentile round trip latency(ms) as perceived from Google servers for the duration period covered by the report.",
"format": "double"
},
"latency95thPercentile": {
"type": "number",
"description": "The 95th percentile round trip latency(ms) as perceived from Google servers for the duration period covered by the report.",
"format": "double"
},
"noQuotaInRegion": {
"type": "number",
"description": "Rate of various quota account statuses per quota check.",
"format": "double"
},
"outOfQuota": {
"type": "number",
"description": "Rate of various quota account statuses per quota check.",
"format": "double"
},
"pixelMatchRequests": {
"type": "number",
"description": "Average QPS for pixel match requests from clients.",
"format": "double"
},
"pixelMatchResponses": {
"type": "number",
"description": "Average QPS for pixel match responses from clients.",
"format": "double"
},
"quotaConfiguredLimit": {
"type": "number",
"description": "The configured quota limits for this account.",
"format": "double"
},
"quotaThrottledLimit": {
"type": "number",
"description": "The throttled quota limits for this account.",
"format": "double"
},
"region": {
"type": "string",
"description": "The trading location of this data."
},
"timestamp": {
"type": "string",
"description": "The unix timestamp of the starting time of this performance data.",
"format": "int64"
}
}
},
"PerformanceReportList": {
"id": "PerformanceReportList",
"type": "object",
"description": "The configuration data for an Ad Exchange performance report list. https://sites.google.com/a/google.com/adx-integration/Home/engineering/binary-releases/rtb-api-release https://cs.corp.google.com/#piper///depot/google3/contentads/adx/tools/rtb_api/adxrtb.py",
"properties": {
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#performanceReportList"
},
"performance_report": {
"type": "array",
"description": "A list of performance reports relevant for the account.",
"items": {
"$ref": "PerformanceReport"
}
}
}
}
},
"resources": {
"accounts": {
"methods": {
"get": {
"id": "adexchangebuyer.accounts.get",
"path": "accounts/{id}",
"httpMethod": "GET",
"description": "Gets one account by ID.",
"parameters": {
"id": {
"type": "integer",
"description": "The account id",
"required": true,
"format": "int32",
"location": "path"
}
},
"parameterOrder": [
"id"
],
"response": {
"$ref": "Account"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
},
"list": {
"id": "adexchangebuyer.accounts.list",
"path": "accounts",
"httpMethod": "GET",
"description": "Retrieves the authenticated user's list of accounts.",
"response": {
"$ref": "AccountsList"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
},
"patch": {
"id": "adexchangebuyer.accounts.patch",
"path": "accounts/{id}",
"httpMethod": "PATCH",
"description": "Updates an existing account. This method supports patch semantics.",
"parameters": {
"id": {
"type": "integer",
"description": "The account id",
"required": true,
"format": "int32",
"location": "path"
}
},
"parameterOrder": [
"id"
],
"request": {
"$ref": "Account"
},
"response": {
"$ref": "Account"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
},
"update": {
"id": "adexchangebuyer.accounts.update",
"path": "accounts/{id}",
"httpMethod": "PUT",
"description": "Updates an existing account.",
"parameters": {
"id": {
"type": "integer",
"description": "The account id",
"required": true,
"format": "int32",
"location": "path"
}
},
"parameterOrder": [
"id"
],
"request": {
"$ref": "Account"
},
"response": {
"$ref": "Account"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
}
}
},
"creatives": {
"methods": {
"get": {
"id": "adexchangebuyer.creatives.get",
"path": "creatives/{accountId}/{buyerCreativeId}",
"httpMethod": "GET",
"description": "Gets the status for a single creative. A creative will be available 30-40 minutes after submission.",
"parameters": {
"accountId": {
"type": "integer",
"description": "The id for the account that will serve this creative.",
"required": true,
"format": "int32",
"location": "path"
},
"buyerCreativeId": {
"type": "string",
"description": "The buyer-specific id for this creative.",
"required": true,
"location": "path"
}
},
"parameterOrder": [
"accountId",
"buyerCreativeId"
],
"response": {
"$ref": "Creative"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
},
"insert": {
"id": "adexchangebuyer.creatives.insert",
"path": "creatives",
"httpMethod": "POST",
"description": "Submit a new creative.",
"request": {
"$ref": "Creative"
},
"response": {
"$ref": "Creative"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
},
"list": {
"id": "adexchangebuyer.creatives.list",
"path": "creatives",
"httpMethod": "GET",
"description": "Retrieves a list of the authenticated user's active creatives. A creative will be available 30-40 minutes after submission.",
"parameters": {
"maxResults": {
"type": "integer",
"description": "Maximum number of entries returned on one result page. If not set, the default is 100. Optional.",
"format": "uint32",
"minimum": "1",
"maximum": "1000",
"location": "query"
},
"pageToken": {
"type": "string",
"description": "A continuation token, used to page through ad clients. To retrieve the next page, set this parameter to the value of \"nextPageToken\" from the previous response. Optional.",
"location": "query"
},
"statusFilter": {
"type": "string",
"description": "When specified, only creatives having the given status are returned.",
"enum": [
"approved",
"disapproved",
"not_checked"
],
"enumDescriptions": [
"Creatives which have been approved.",
"Creatives which have been disapproved.",
"Creatives whose status is not yet checked."
],
"location": "query"
}
},
"response": {
"$ref": "CreativesList"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
}
}
},
"directDeals": {
"methods": {
"get": {
"id": "adexchangebuyer.directDeals.get",
"path": "directdeals/{id}",
"httpMethod": "GET",
"description": "Gets one direct deal by ID.",
"parameters": {
"id": {
"type": "string",
"description": "The direct deal id",
"required": true,
"format": "int64",
"location": "path"
}
},
"parameterOrder": [
"id"
],
"response": {
"$ref": "DirectDeal"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
},
"list": {
"id": "adexchangebuyer.directDeals.list",
"path": "directdeals",
"httpMethod": "GET",
"description": "Retrieves the authenticated user's list of direct deals.",
"response": {
"$ref": "DirectDealsList"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
}
}
},
"performanceReport": {
"methods": {
"list": {
"id": "adexchangebuyer.performanceReport.list",
"path": "performancereport",
"httpMethod": "GET",
"description": "Retrieves the authenticated user's list of performance metrics.",
"parameters": {
"accountId": {
"type": "string",
"description": "The account id to get the reports.",
"required": true,
"format": "int64",
"location": "query"
},
"endDateTime": {
"type": "string",
"description": "The end time of the report in ISO 8601 timestamp format using UTC.",
"required": true,
"location": "query"
},
"maxResults": {
"type": "integer",
"description": "Maximum number of entries returned on one result page. If not set, the default is 100. Optional.",
"format": "uint32",
"minimum": "1",
"maximum": "1000",
"location": "query"
},
"pageToken": {
"type": "string",
"description": "A continuation token, used to page through performance reports. To retrieve the next page, set this parameter to the value of \"nextPageToken\" from the previous response. Optional.",
"location": "query"
},
"startDateTime": {
"type": "string",
"description": "The start time of the report in ISO 8601 timestamp format using UTC.",
"required": true,
"location": "query"
}
},
"parameterOrder": [
"accountId",
"endDateTime",
"startDateTime"
],
"response": {
"$ref": "PerformanceReportList"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
}
}
}
}
}

View File

@ -0,0 +1,853 @@
{
"kind": "discovery#restDescription",
"etag": "\"kEk3sFj6Ef5_yR1-H3bAO6qw9mI/qdni1GzBHdR8i9VRTRxjSqpGD58\"",
"discoveryVersion": "v1",
"id": "adexchangebuyer:v1.3",
"name": "adexchangebuyer",
"canonicalName": "Ad Exchange Buyer",
"version": "v1.3",
"title": "Ad Exchange Buyer API",
"description": "Lets you manage your Ad Exchange Buyer account.",
"ownerDomain": "google.com",
"ownerName": "Google",
"icons": {
"x16": "http://www.google.com/images/icons/product/doubleclick-16.gif",
"x32": "http://www.google.com/images/icons/product/doubleclick-32.gif"
},
"documentationLink": "https://developers.google.com/ad-exchange/buyer-rest",
"protocol": "rest",
"baseUrl": "https://www.googleapis.com/adexchangebuyer/v1.3/",
"basePath": "/adexchangebuyer/v1.3/",
"rootUrl": "https://www.googleapis.com/",
"servicePath": "adexchangebuyer/v1.3/",
"batchPath": "batch",
"parameters": {
"alt": {
"type": "string",
"description": "Data format for the response.",
"default": "json",
"enum": [
"json"
],
"enumDescriptions": [
"Responses with Content-Type of application/json"
],
"location": "query"
},
"fields": {
"type": "string",
"description": "Selector specifying which fields to include in a partial response.",
"location": "query"
},
"key": {
"type": "string",
"description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.",
"location": "query"
},
"oauth_token": {
"type": "string",
"description": "OAuth 2.0 token for the current user.",
"location": "query"
},
"prettyPrint": {
"type": "boolean",
"description": "Returns response with indentations and line breaks.",
"default": "true",
"location": "query"
},
"quotaUser": {
"type": "string",
"description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.",
"location": "query"
},
"userIp": {
"type": "string",
"description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.",
"location": "query"
}
},
"auth": {
"oauth2": {
"scopes": {
"https://www.googleapis.com/auth/adexchange.buyer": {
"description": "Manage your Ad Exchange buyer account configuration"
}
}
}
},
"schemas": {
"Account": {
"id": "Account",
"type": "object",
"description": "Configuration data for an Ad Exchange buyer account.",
"properties": {
"bidderLocation": {
"type": "array",
"description": "Your bidder locations that have distinct URLs.",
"items": {
"type": "object",
"properties": {
"maximumQps": {
"type": "integer",
"description": "The maximum queries per second the Ad Exchange will send.",
"format": "int32"
},
"region": {
"type": "string",
"description": "The geographical region the Ad Exchange should send requests from. Only used by some quota systems, but always setting the value is recommended. Allowed values: \n- ASIA \n- EUROPE \n- US_EAST \n- US_WEST"
},
"url": {
"type": "string",
"description": "The URL to which the Ad Exchange will send bid requests."
}
}
}
},
"cookieMatchingNid": {
"type": "string",
"description": "The nid parameter value used in cookie match requests. Please contact your technical account manager if you need to change this."
},
"cookieMatchingUrl": {
"type": "string",
"description": "The base URL used in cookie match requests."
},
"id": {
"type": "integer",
"description": "Account id.",
"format": "int32"
},
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#account"
},
"maximumTotalQps": {
"type": "integer",
"description": "The sum of all bidderLocation.maximumQps values cannot exceed this. Please contact your technical account manager if you need to change this.",
"format": "int32"
}
}
},
"AccountsList": {
"id": "AccountsList",
"type": "object",
"description": "An account feed lists Ad Exchange buyer accounts that the user has access to. Each entry in the feed corresponds to a single buyer account.",
"properties": {
"items": {
"type": "array",
"description": "A list of accounts.",
"items": {
"$ref": "Account"
}
},
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#accountsList"
}
}
},
"Creative": {
"id": "Creative",
"type": "object",
"description": "A creative and its classification data.",
"properties": {
"HTMLSnippet": {
"type": "string",
"description": "The HTML snippet that displays the ad when inserted in the web page. If set, videoURL should not be set."
},
"accountId": {
"type": "integer",
"description": "Account id.",
"format": "int32",
"annotations": {
"required": [
"adexchangebuyer.creatives.insert"
]
}
},
"advertiserId": {
"type": "array",
"description": "Detected advertiser id, if any. Read-only. This field should not be set in requests.",
"items": {
"type": "string",
"format": "int64"
}
},
"advertiserName": {
"type": "string",
"description": "The name of the company being advertised in the creative.",
"annotations": {
"required": [
"adexchangebuyer.creatives.insert"
]
}
},
"agencyId": {
"type": "string",
"description": "The agency id for this creative.",
"format": "int64"
},
"attribute": {
"type": "array",
"description": "All attributes for the ads that may be shown from this snippet.",
"items": {
"type": "integer",
"format": "int32"
}
},
"buyerCreativeId": {
"type": "string",
"description": "A buyer-specific id identifying the creative in this ad.",
"annotations": {
"required": [
"adexchangebuyer.creatives.insert"
]
}
},
"clickThroughUrl": {
"type": "array",
"description": "The set of destination urls for the snippet.",
"items": {
"type": "string"
},
"annotations": {
"required": [
"adexchangebuyer.creatives.insert"
]
}
},
"corrections": {
"type": "array",
"description": "Shows any corrections that were applied to this creative. Read-only. This field should not be set in requests.",
"items": {
"type": "object",
"properties": {
"details": {
"type": "array",
"description": "Additional details about the correction.",
"items": {
"type": "string"
}
},
"reason": {
"type": "string",
"description": "The type of correction that was applied to the creative."
}
}
}
},
"disapprovalReasons": {
"type": "array",
"description": "The reasons for disapproval, if any. Note that not all disapproval reasons may be categorized, so it is possible for the creative to have a status of DISAPPROVED with an empty list for disapproval_reasons. In this case, please reach out to your TAM to help debug the issue. Read-only. This field should not be set in requests.",
"items": {
"type": "object",
"properties": {
"details": {
"type": "array",
"description": "Additional details about the reason for disapproval.",
"items": {
"type": "string"
}
},
"reason": {
"type": "string",
"description": "The categorized reason for disapproval."
}
}
}
},
"filteringReasons": {
"type": "object",
"description": "The filtering reasons for the creative. Read-only. This field should not be set in requests.",
"properties": {
"date": {
"type": "string",
"description": "The date in ISO 8601 format for the data. The data is collected from 00:00:00 to 23:59:59 in PST."
},
"reasons": {
"type": "array",
"description": "The filtering reasons.",
"items": {
"type": "object",
"properties": {
"filteringCount": {
"type": "string",
"description": "The number of times the creative was filtered for the status. The count is aggregated across all publishers on the exchange.",
"format": "int64"
},
"filteringStatus": {
"type": "integer",
"description": "The filtering status code. Please refer to \"creative-status-codes.txt\" in the Downloads section for the status codes.",
"format": "int32"
}
}
}
}
}
},
"height": {
"type": "integer",
"description": "Ad height.",
"format": "int32",
"annotations": {
"required": [
"adexchangebuyer.creatives.insert"
]
}
},
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#creative"
},
"productCategories": {
"type": "array",
"description": "Detected product categories, if any. Read-only. This field should not be set in requests.",
"items": {
"type": "integer",
"format": "int32"
}
},
"restrictedCategories": {
"type": "array",
"description": "All restricted categories for the ads that may be shown from this snippet.",
"items": {
"type": "integer",
"format": "int32"
}
},
"sensitiveCategories": {
"type": "array",
"description": "Detected sensitive categories, if any. Read-only. This field should not be set in requests.",
"items": {
"type": "integer",
"format": "int32"
}
},
"status": {
"type": "string",
"description": "Creative serving status. Read-only. This field should not be set in requests."
},
"vendorType": {
"type": "array",
"description": "All vendor types for the ads that may be shown from this snippet.",
"items": {
"type": "integer",
"format": "int32"
}
},
"videoURL": {
"type": "string",
"description": "The url to fetch a video ad. If set, HTMLSnippet should not be set."
},
"width": {
"type": "integer",
"description": "Ad width.",
"format": "int32",
"annotations": {
"required": [
"adexchangebuyer.creatives.insert"
]
}
}
}
},
"CreativesList": {
"id": "CreativesList",
"type": "object",
"description": "The creatives feed lists the active creatives for the Ad Exchange buyer accounts that the user has access to. Each entry in the feed corresponds to a single creative.",
"properties": {
"items": {
"type": "array",
"description": "A list of creatives.",
"items": {
"$ref": "Creative"
}
},
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#creativesList"
},
"nextPageToken": {
"type": "string",
"description": "Continuation token used to page through creatives. To retrieve the next page of results, set the next request's \"pageToken\" value to this."
}
}
},
"DirectDeal": {
"id": "DirectDeal",
"type": "object",
"description": "The configuration data for an Ad Exchange direct deal.",
"properties": {
"accountId": {
"type": "integer",
"description": "The account id of the buyer this deal is for.",
"format": "int32"
},
"advertiser": {
"type": "string",
"description": "The name of the advertiser this deal is for."
},
"currencyCode": {
"type": "string",
"description": "The currency code that applies to the fixed_cpm value. If not set then assumed to be USD."
},
"endTime": {
"type": "string",
"description": "End time for when this deal stops being active. If not set then this deal is valid until manually disabled by the publisher. In seconds since the epoch.",
"format": "int64"
},
"fixedCpm": {
"type": "string",
"description": "The fixed price for this direct deal. In cpm micros of currency according to currency_code. If set, then this deal is eligible for the fixed price tier of buying (highest priority, pay exactly the configured fixed price).",
"format": "int64"
},
"id": {
"type": "string",
"description": "Deal id.",
"format": "int64"
},
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#directDeal"
},
"name": {
"type": "string",
"description": "Deal name."
},
"privateExchangeMinCpm": {
"type": "string",
"description": "The minimum price for this direct deal. In cpm micros of currency according to currency_code. If set, then this deal is eligible for the private exchange tier of buying (below fixed price priority, run as a second price auction).",
"format": "int64"
},
"sellerNetwork": {
"type": "string",
"description": "The name of the publisher offering this direct deal."
},
"startTime": {
"type": "string",
"description": "Start time for when this deal becomes active. If not set then this deal is active immediately upon creation. In seconds since the epoch.",
"format": "int64"
}
}
},
"DirectDealsList": {
"id": "DirectDealsList",
"type": "object",
"description": "A direct deals feed lists Direct Deals the Ad Exchange buyer account has access to. This includes direct deals set up for the buyer account as well as its merged stream seats.",
"properties": {
"directDeals": {
"type": "array",
"description": "A list of direct deals relevant for your account.",
"items": {
"$ref": "DirectDeal"
}
},
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#directDealsList"
}
}
},
"PerformanceReport": {
"id": "PerformanceReport",
"type": "object",
"description": "The configuration data for an Ad Exchange performance report list. TODO(nathanbullock): need to add some release tests before releasing this. https://sites.google.com/a/google.com/adx-integration/Home/engineering/binary-releases/rtb-api-release https://cs.corp.google.com/#piper///depot/google3/contentads/adx/tools/rtb_api/adxrtb.py",
"properties": {
"calloutStatusRate": {
"type": "array",
"description": "Rate of various prefiltering statuses per match. Please refer to the callout-status-codes.txt file for different statuses.",
"items": {
"type": "any"
}
},
"cookieMatcherStatusRate": {
"type": "array",
"description": "Average QPS for cookie matcher operations.",
"items": {
"type": "any"
}
},
"creativeStatusRate": {
"type": "array",
"description": "Rate of ads with a given status. Please refer to the creative-status-codes.txt file for different statuses.",
"items": {
"type": "any"
}
},
"hostedMatchStatusRate": {
"type": "array",
"description": "Average QPS for hosted match operations.",
"items": {
"type": "any"
}
},
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#performanceReport"
},
"latency50thPercentile": {
"type": "number",
"description": "The 50th percentile round trip latency(ms) as perceived from Google servers for the duration period covered by the report.",
"format": "double"
},
"latency85thPercentile": {
"type": "number",
"description": "The 85th percentile round trip latency(ms) as perceived from Google servers for the duration period covered by the report.",
"format": "double"
},
"latency95thPercentile": {
"type": "number",
"description": "The 95th percentile round trip latency(ms) as perceived from Google servers for the duration period covered by the report.",
"format": "double"
},
"noQuotaInRegion": {
"type": "number",
"description": "Rate of various quota account statuses per quota check.",
"format": "double"
},
"outOfQuota": {
"type": "number",
"description": "Rate of various quota account statuses per quota check.",
"format": "double"
},
"pixelMatchRequests": {
"type": "number",
"description": "Average QPS for pixel match requests from clients.",
"format": "double"
},
"pixelMatchResponses": {
"type": "number",
"description": "Average QPS for pixel match responses from clients.",
"format": "double"
},
"quotaConfiguredLimit": {
"type": "number",
"description": "The configured quota limits for this account.",
"format": "double"
},
"quotaThrottledLimit": {
"type": "number",
"description": "The throttled quota limits for this account.",
"format": "double"
},
"region": {
"type": "string",
"description": "The trading location of this data."
},
"timestamp": {
"type": "string",
"description": "The unix timestamp of the starting time of this performance data.",
"format": "int64"
}
}
},
"PerformanceReportList": {
"id": "PerformanceReportList",
"type": "object",
"description": "The configuration data for an Ad Exchange performance report list. https://sites.google.com/a/google.com/adx-integration/Home/engineering/binary-releases/rtb-api-release https://cs.corp.google.com/#piper///depot/google3/contentads/adx/tools/rtb_api/adxrtb.py",
"properties": {
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#performanceReportList"
},
"performanceReport": {
"type": "array",
"description": "A list of performance reports relevant for the account.",
"items": {
"$ref": "PerformanceReport"
}
}
}
}
},
"resources": {
"accounts": {
"methods": {
"get": {
"id": "adexchangebuyer.accounts.get",
"path": "accounts/{id}",
"httpMethod": "GET",
"description": "Gets one account by ID.",
"parameters": {
"id": {
"type": "integer",
"description": "The account id",
"required": true,
"format": "int32",
"location": "path"
}
},
"parameterOrder": [
"id"
],
"response": {
"$ref": "Account"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
},
"list": {
"id": "adexchangebuyer.accounts.list",
"path": "accounts",
"httpMethod": "GET",
"description": "Retrieves the authenticated user's list of accounts.",
"response": {
"$ref": "AccountsList"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
},
"patch": {
"id": "adexchangebuyer.accounts.patch",
"path": "accounts/{id}",
"httpMethod": "PATCH",
"description": "Updates an existing account. This method supports patch semantics.",
"parameters": {
"id": {
"type": "integer",
"description": "The account id",
"required": true,
"format": "int32",
"location": "path"
}
},
"parameterOrder": [
"id"
],
"request": {
"$ref": "Account"
},
"response": {
"$ref": "Account"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
},
"update": {
"id": "adexchangebuyer.accounts.update",
"path": "accounts/{id}",
"httpMethod": "PUT",
"description": "Updates an existing account.",
"parameters": {
"id": {
"type": "integer",
"description": "The account id",
"required": true,
"format": "int32",
"location": "path"
}
},
"parameterOrder": [
"id"
],
"request": {
"$ref": "Account"
},
"response": {
"$ref": "Account"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
}
}
},
"creatives": {
"methods": {
"get": {
"id": "adexchangebuyer.creatives.get",
"path": "creatives/{accountId}/{buyerCreativeId}",
"httpMethod": "GET",
"description": "Gets the status for a single creative. A creative will be available 30-40 minutes after submission.",
"parameters": {
"accountId": {
"type": "integer",
"description": "The id for the account that will serve this creative.",
"required": true,
"format": "int32",
"location": "path"
},
"buyerCreativeId": {
"type": "string",
"description": "The buyer-specific id for this creative.",
"required": true,
"location": "path"
}
},
"parameterOrder": [
"accountId",
"buyerCreativeId"
],
"response": {
"$ref": "Creative"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
},
"insert": {
"id": "adexchangebuyer.creatives.insert",
"path": "creatives",
"httpMethod": "POST",
"description": "Submit a new creative.",
"request": {
"$ref": "Creative"
},
"response": {
"$ref": "Creative"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
},
"list": {
"id": "adexchangebuyer.creatives.list",
"path": "creatives",
"httpMethod": "GET",
"description": "Retrieves a list of the authenticated user's active creatives. A creative will be available 30-40 minutes after submission.",
"parameters": {
"maxResults": {
"type": "integer",
"description": "Maximum number of entries returned on one result page. If not set, the default is 100. Optional.",
"format": "uint32",
"minimum": "1",
"maximum": "1000",
"location": "query"
},
"pageToken": {
"type": "string",
"description": "A continuation token, used to page through ad clients. To retrieve the next page, set this parameter to the value of \"nextPageToken\" from the previous response. Optional.",
"location": "query"
},
"statusFilter": {
"type": "string",
"description": "When specified, only creatives having the given status are returned.",
"enum": [
"approved",
"disapproved",
"not_checked"
],
"enumDescriptions": [
"Creatives which have been approved.",
"Creatives which have been disapproved.",
"Creatives whose status is not yet checked."
],
"location": "query"
}
},
"response": {
"$ref": "CreativesList"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
}
}
},
"directDeals": {
"methods": {
"get": {
"id": "adexchangebuyer.directDeals.get",
"path": "directdeals/{id}",
"httpMethod": "GET",
"description": "Gets one direct deal by ID.",
"parameters": {
"id": {
"type": "string",
"description": "The direct deal id",
"required": true,
"format": "int64",
"location": "path"
}
},
"parameterOrder": [
"id"
],
"response": {
"$ref": "DirectDeal"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
},
"list": {
"id": "adexchangebuyer.directDeals.list",
"path": "directdeals",
"httpMethod": "GET",
"description": "Retrieves the authenticated user's list of direct deals.",
"response": {
"$ref": "DirectDealsList"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
}
}
},
"performanceReport": {
"methods": {
"list": {
"id": "adexchangebuyer.performanceReport.list",
"path": "performancereport",
"httpMethod": "GET",
"description": "Retrieves the authenticated user's list of performance metrics.",
"parameters": {
"accountId": {
"type": "string",
"description": "The account id to get the reports.",
"required": true,
"format": "int64",
"location": "query"
},
"endDateTime": {
"type": "string",
"description": "The end time of the report in ISO 8601 timestamp format using UTC.",
"required": true,
"location": "query"
},
"maxResults": {
"type": "integer",
"description": "Maximum number of entries returned on one result page. If not set, the default is 100. Optional.",
"format": "uint32",
"minimum": "1",
"maximum": "1000",
"location": "query"
},
"pageToken": {
"type": "string",
"description": "A continuation token, used to page through performance reports. To retrieve the next page, set this parameter to the value of \"nextPageToken\" from the previous response. Optional.",
"location": "query"
},
"startDateTime": {
"type": "string",
"description": "The start time of the report in ISO 8601 timestamp format using UTC.",
"required": true,
"location": "query"
}
},
"parameterOrder": [
"accountId",
"endDateTime",
"startDateTime"
],
"response": {
"$ref": "PerformanceReportList"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
}
}
}
}
}

View File

@ -0,0 +1,612 @@
{
"kind": "discovery#restDescription",
"etag": "\"kEk3sFj6Ef5_yR1-H3bAO6qw9mI/uBdBsKoCx2blJHBc5UBukt70JEU\"",
"discoveryVersion": "v1",
"id": "adexchangebuyer:v1",
"name": "adexchangebuyer",
"canonicalName": "Ad Exchange Buyer",
"version": "v1",
"title": "Ad Exchange Buyer API",
"description": "Lets you manage your Ad Exchange Buyer account.",
"ownerDomain": "google.com",
"ownerName": "Google",
"icons": {
"x16": "http://www.google.com/images/icons/product/doubleclick-16.gif",
"x32": "http://www.google.com/images/icons/product/doubleclick-32.gif"
},
"documentationLink": "https://developers.google.com/ad-exchange/buyer-rest",
"protocol": "rest",
"baseUrl": "https://www.googleapis.com/adexchangebuyer/v1/",
"basePath": "/adexchangebuyer/v1/",
"rootUrl": "https://www.googleapis.com/",
"servicePath": "adexchangebuyer/v1/",
"batchPath": "batch",
"parameters": {
"alt": {
"type": "string",
"description": "Data format for the response.",
"default": "json",
"enum": [
"json"
],
"enumDescriptions": [
"Responses with Content-Type of application/json"
],
"location": "query"
},
"fields": {
"type": "string",
"description": "Selector specifying which fields to include in a partial response.",
"location": "query"
},
"key": {
"type": "string",
"description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.",
"location": "query"
},
"oauth_token": {
"type": "string",
"description": "OAuth 2.0 token for the current user.",
"location": "query"
},
"prettyPrint": {
"type": "boolean",
"description": "Returns response with indentations and line breaks.",
"default": "true",
"location": "query"
},
"quotaUser": {
"type": "string",
"description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.",
"location": "query"
},
"userIp": {
"type": "string",
"description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.",
"location": "query"
}
},
"auth": {
"oauth2": {
"scopes": {
"https://www.googleapis.com/auth/adexchange.buyer": {
"description": "Manage your Ad Exchange buyer account configuration"
}
}
}
},
"schemas": {
"Account": {
"id": "Account",
"type": "object",
"description": "Configuration data for an Ad Exchange buyer account.",
"properties": {
"bidderLocation": {
"type": "array",
"description": "Your bidder locations that have distinct URLs.",
"items": {
"type": "object",
"properties": {
"maximumQps": {
"type": "integer",
"description": "The maximum queries per second the Ad Exchange will send.",
"format": "int32"
},
"url": {
"type": "string",
"description": "The URL to which the Ad Exchange will send bid requests."
}
}
}
},
"cookieMatchingNid": {
"type": "string",
"description": "The nid parameter value used in cookie match requests. Please contact your technical account manager if you need to change this."
},
"cookieMatchingUrl": {
"type": "string",
"description": "The base URL used in cookie match requests."
},
"id": {
"type": "integer",
"description": "Account id.",
"format": "int32"
},
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#account"
},
"maximumTotalQps": {
"type": "integer",
"description": "The sum of all bidderLocation.maximumQps values cannot exceed this. Please contact your technical account manager if you need to change this.",
"format": "int32"
}
}
},
"AccountsList": {
"id": "AccountsList",
"type": "object",
"description": "An account feed lists Ad Exchange buyer accounts that the user has access to. Each entry in the feed corresponds to a single buyer account.",
"properties": {
"items": {
"type": "array",
"description": "A list of accounts.",
"items": {
"$ref": "Account"
}
},
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#accountsList"
}
}
},
"Creative": {
"id": "Creative",
"type": "object",
"description": "A creative and its classification data.",
"properties": {
"HTMLSnippet": {
"type": "string",
"description": "The HTML snippet that displays the ad when inserted in the web page. If set, videoURL should not be set."
},
"accountId": {
"type": "integer",
"description": "Account id.",
"format": "int32",
"annotations": {
"required": [
"adexchangebuyer.creatives.insert"
]
}
},
"adgroupId": {
"type": "string",
"description": "The pretargeting adgroup id that this creative will be associated with.",
"format": "int64",
"annotations": {
"required": [
"adexchangebuyer.creatives.insert"
]
}
},
"advertiserId": {
"type": "array",
"description": "Detected advertiser id, if any. Read-only. This field should not be set in requests.",
"items": {
"type": "string",
"format": "int64"
}
},
"advertiserName": {
"type": "string",
"description": "The name of the company being advertised in the creative.",
"annotations": {
"required": [
"adexchangebuyer.creatives.insert"
]
}
},
"attribute": {
"type": "array",
"description": "All attributes for the ads that may be shown from this snippet.",
"items": {
"type": "integer",
"format": "int32"
}
},
"buyerCreativeId": {
"type": "string",
"description": "A buyer-specific id identifying the creative in this ad.",
"annotations": {
"required": [
"adexchangebuyer.creatives.insert"
]
}
},
"clickThroughUrl": {
"type": "array",
"description": "The set of destination urls for the snippet.",
"items": {
"type": "string"
},
"annotations": {
"required": [
"adexchangebuyer.creatives.insert"
]
}
},
"disapprovalReasons": {
"type": "array",
"description": "The reason for disapproval, if any. Note that not all disapproval reasons may be categorized, so it is possible for the creative to have a status of DISAPPROVED with an empty list for disapproval_reasons. In this case, please reach out to your TAM to help debug the issue. Read-only. This field should not be set in requests.",
"items": {
"type": "string"
}
},
"height": {
"type": "integer",
"description": "Ad height.",
"format": "int32",
"annotations": {
"required": [
"adexchangebuyer.creatives.insert"
]
}
},
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#creative"
},
"productCategories": {
"type": "array",
"description": "Detected product categories, if any. Read-only. This field should not be set in requests.",
"items": {
"type": "integer",
"format": "int32"
}
},
"restrictedCategories": {
"type": "array",
"description": "All restricted categories for the ads that may be shown from this snippet.",
"items": {
"type": "integer",
"format": "int32"
}
},
"sensitiveCategories": {
"type": "array",
"description": "Detected sensitive categories, if any. Read-only. This field should not be set in requests.",
"items": {
"type": "integer",
"format": "int32"
}
},
"status": {
"type": "string",
"description": "Creative serving status. Read-only. This field should not be set in requests."
},
"vendorType": {
"type": "array",
"description": "All vendor types for the ads that may be shown from this snippet.",
"items": {
"type": "integer",
"format": "int32"
}
},
"videoURL": {
"type": "string",
"description": "The url to fetch a video ad. If set, HTMLSnippet should not be set."
},
"width": {
"type": "integer",
"description": "Ad width.",
"format": "int32",
"annotations": {
"required": [
"adexchangebuyer.creatives.insert"
]
}
}
}
},
"CreativesList": {
"id": "CreativesList",
"type": "object",
"description": "The creatives feed lists the active creatives for the Ad Exchange buyer accounts that the user has access to. Each entry in the feed corresponds to a single creative.",
"properties": {
"items": {
"type": "array",
"description": "A list of creatives.",
"items": {
"$ref": "Creative"
}
},
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#creativesList"
},
"nextPageToken": {
"type": "string",
"description": "Continuation token used to page through creatives. To retrieve the next page of results, set the next request's \"pageToken\" value to this."
}
}
},
"DirectDeal": {
"id": "DirectDeal",
"type": "object",
"description": "The configuration data for an Ad Exchange direct deal.",
"properties": {
"accountId": {
"type": "integer",
"description": "The account id of the buyer this deal is for.",
"format": "int32"
},
"advertiser": {
"type": "string",
"description": "The name of the advertiser this deal is for."
},
"currencyCode": {
"type": "string",
"description": "The currency code that applies to the fixed_cpm value. If not set then assumed to be USD."
},
"endTime": {
"type": "string",
"description": "End time for when this deal stops being active. If not set then this deal is valid until manually disabled by the publisher. In seconds since the epoch.",
"format": "int64"
},
"fixedCpm": {
"type": "string",
"description": "The fixed price for this direct deal. In cpm micros of currency according to currency_code.",
"format": "int64"
},
"id": {
"type": "string",
"description": "Deal id.",
"format": "int64"
},
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#directDeal"
},
"name": {
"type": "string",
"description": "Deal name."
},
"sellerNetwork": {
"type": "string",
"description": "The name of the publisher offering this direct deal."
},
"startTime": {
"type": "string",
"description": "Start time for when this deal becomes active. If not set then this deal is active immediately upon creation. In seconds since the epoch.",
"format": "int64"
}
}
},
"DirectDealsList": {
"id": "DirectDealsList",
"type": "object",
"description": "A direct deals feed lists Direct Deals the Ad Exchange buyer account has access to. This includes direct deals set up for the buyer account as well as its merged stream seats.",
"properties": {
"directDeals": {
"type": "array",
"description": "A list of direct deals relevant for your account.",
"items": {
"$ref": "DirectDeal"
}
},
"kind": {
"type": "string",
"description": "Resource type.",
"default": "adexchangebuyer#directDealsList"
}
}
}
},
"resources": {
"accounts": {
"methods": {
"get": {
"id": "adexchangebuyer.accounts.get",
"path": "accounts/{id}",
"httpMethod": "GET",
"description": "Gets one account by ID.",
"parameters": {
"id": {
"type": "integer",
"description": "The account id",
"required": true,
"format": "int32",
"location": "path"
}
},
"parameterOrder": [
"id"
],
"response": {
"$ref": "Account"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
},
"list": {
"id": "adexchangebuyer.accounts.list",
"path": "accounts",
"httpMethod": "GET",
"description": "Retrieves the authenticated user's list of accounts.",
"response": {
"$ref": "AccountsList"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
},
"patch": {
"id": "adexchangebuyer.accounts.patch",
"path": "accounts/{id}",
"httpMethod": "PATCH",
"description": "Updates an existing account. This method supports patch semantics.",
"parameters": {
"id": {
"type": "integer",
"description": "The account id",
"required": true,
"format": "int32",
"location": "path"
}
},
"parameterOrder": [
"id"
],
"request": {
"$ref": "Account"
},
"response": {
"$ref": "Account"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
},
"update": {
"id": "adexchangebuyer.accounts.update",
"path": "accounts/{id}",
"httpMethod": "PUT",
"description": "Updates an existing account.",
"parameters": {
"id": {
"type": "integer",
"description": "The account id",
"required": true,
"format": "int32",
"location": "path"
}
},
"parameterOrder": [
"id"
],
"request": {
"$ref": "Account"
},
"response": {
"$ref": "Account"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
}
}
},
"creatives": {
"methods": {
"get": {
"id": "adexchangebuyer.creatives.get",
"path": "creatives/{accountId}/{buyerCreativeId}",
"httpMethod": "GET",
"description": "Gets the status for a single creative.",
"parameters": {
"accountId": {
"type": "integer",
"description": "The id for the account that will serve this creative.",
"required": true,
"format": "int32",
"location": "path"
},
"adgroupId": {
"type": "string",
"description": "The adgroup this creative belongs to.",
"required": true,
"format": "int64",
"location": "query"
},
"buyerCreativeId": {
"type": "string",
"description": "The buyer-specific id for this creative.",
"required": true,
"location": "path"
}
},
"parameterOrder": [
"accountId",
"buyerCreativeId",
"adgroupId"
],
"response": {
"$ref": "Creative"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
},
"insert": {
"id": "adexchangebuyer.creatives.insert",
"path": "creatives",
"httpMethod": "POST",
"description": "Submit a new creative.",
"request": {
"$ref": "Creative"
},
"response": {
"$ref": "Creative"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
},
"list": {
"id": "adexchangebuyer.creatives.list",
"path": "creatives",
"httpMethod": "GET",
"description": "Retrieves a list of the authenticated user's active creatives.",
"parameters": {
"maxResults": {
"type": "integer",
"description": "Maximum number of entries returned on one result page. If not set, the default is 100. Optional.",
"format": "uint32",
"minimum": "1",
"maximum": "1000",
"location": "query"
},
"pageToken": {
"type": "string",
"description": "A continuation token, used to page through ad clients. To retrieve the next page, set this parameter to the value of \"nextPageToken\" from the previous response. Optional.",
"location": "query"
}
},
"response": {
"$ref": "CreativesList"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
}
}
},
"directDeals": {
"methods": {
"get": {
"id": "adexchangebuyer.directDeals.get",
"path": "directdeals/{id}",
"httpMethod": "GET",
"description": "Gets one direct deal by ID.",
"parameters": {
"id": {
"type": "string",
"description": "The direct deal id",
"required": true,
"format": "int64",
"location": "path"
}
},
"parameterOrder": [
"id"
],
"response": {
"$ref": "DirectDeal"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
},
"list": {
"id": "adexchangebuyer.directDeals.list",
"path": "directdeals",
"httpMethod": "GET",
"description": "Retrieves the authenticated user's list of direct deals.",
"response": {
"$ref": "DirectDealsList"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.buyer"
]
}
}
}
}
}

View File

@ -0,0 +1,885 @@
// Package adexchangebuyer provides access to the Ad Exchange Buyer API.
//
// See https://developers.google.com/ad-exchange/buyer-rest
//
// Usage example:
//
// import "code.google.com/p/google-api-go-client/adexchangebuyer/v1"
// ...
// adexchangebuyerService, err := adexchangebuyer.New(oauthHttpClient)
package adexchangebuyer
import (
"bytes"
"code.google.com/p/google-api-go-client/googleapi"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
)
// Always reference these packages, just in case the auto-generated code
// below doesn't.
var _ = bytes.NewBuffer
var _ = strconv.Itoa
var _ = fmt.Sprintf
var _ = json.NewDecoder
var _ = io.Copy
var _ = url.Parse
var _ = googleapi.Version
var _ = errors.New
var _ = strings.Replace
const apiId = "adexchangebuyer:v1"
const apiName = "adexchangebuyer"
const apiVersion = "v1"
const basePath = "https://www.googleapis.com/adexchangebuyer/v1/"
// OAuth2 scopes used by this API.
const (
// Manage your Ad Exchange buyer account configuration
AdexchangeBuyerScope = "https://www.googleapis.com/auth/adexchange.buyer"
)
func New(client *http.Client) (*Service, error) {
if client == nil {
return nil, errors.New("client is nil")
}
s := &Service{client: client, BasePath: basePath}
s.Accounts = NewAccountsService(s)
s.Creatives = NewCreativesService(s)
s.DirectDeals = NewDirectDealsService(s)
return s, nil
}
type Service struct {
client *http.Client
BasePath string // API endpoint base URL
Accounts *AccountsService
Creatives *CreativesService
DirectDeals *DirectDealsService
}
func NewAccountsService(s *Service) *AccountsService {
rs := &AccountsService{s: s}
return rs
}
type AccountsService struct {
s *Service
}
func NewCreativesService(s *Service) *CreativesService {
rs := &CreativesService{s: s}
return rs
}
type CreativesService struct {
s *Service
}
func NewDirectDealsService(s *Service) *DirectDealsService {
rs := &DirectDealsService{s: s}
return rs
}
type DirectDealsService struct {
s *Service
}
type Account struct {
// BidderLocation: Your bidder locations that have distinct URLs.
BidderLocation []*AccountBidderLocation `json:"bidderLocation,omitempty"`
// CookieMatchingNid: The nid parameter value used in cookie match
// requests. Please contact your technical account manager if you need
// to change this.
CookieMatchingNid string `json:"cookieMatchingNid,omitempty"`
// CookieMatchingUrl: The base URL used in cookie match requests.
CookieMatchingUrl string `json:"cookieMatchingUrl,omitempty"`
// Id: Account id.
Id int64 `json:"id,omitempty"`
// Kind: Resource type.
Kind string `json:"kind,omitempty"`
// MaximumTotalQps: The sum of all bidderLocation.maximumQps values
// cannot exceed this. Please contact your technical account manager if
// you need to change this.
MaximumTotalQps int64 `json:"maximumTotalQps,omitempty"`
}
type AccountBidderLocation struct {
// MaximumQps: The maximum queries per second the Ad Exchange will send.
MaximumQps int64 `json:"maximumQps,omitempty"`
// Url: The URL to which the Ad Exchange will send bid requests.
Url string `json:"url,omitempty"`
}
type AccountsList struct {
// Items: A list of accounts.
Items []*Account `json:"items,omitempty"`
// Kind: Resource type.
Kind string `json:"kind,omitempty"`
}
type Creative struct {
// HTMLSnippet: The HTML snippet that displays the ad when inserted in
// the web page. If set, videoURL should not be set.
HTMLSnippet string `json:"HTMLSnippet,omitempty"`
// AccountId: Account id.
AccountId int64 `json:"accountId,omitempty"`
// AdgroupId: The pretargeting adgroup id that this creative will be
// associated with.
AdgroupId int64 `json:"adgroupId,omitempty,string"`
// AdvertiserId: Detected advertiser id, if any. Read-only. This field
// should not be set in requests.
AdvertiserId googleapi.Int64s `json:"advertiserId,omitempty"`
// AdvertiserName: The name of the company being advertised in the
// creative.
AdvertiserName string `json:"advertiserName,omitempty"`
// Attribute: All attributes for the ads that may be shown from this
// snippet.
Attribute []int64 `json:"attribute,omitempty"`
// BuyerCreativeId: A buyer-specific id identifying the creative in this
// ad.
BuyerCreativeId string `json:"buyerCreativeId,omitempty"`
// ClickThroughUrl: The set of destination urls for the snippet.
ClickThroughUrl []string `json:"clickThroughUrl,omitempty"`
// DisapprovalReasons: The reason for disapproval, if any. Note that not
// all disapproval reasons may be categorized, so it is possible for the
// creative to have a status of DISAPPROVED with an empty list for
// disapproval_reasons. In this case, please reach out to your TAM to
// help debug the issue. Read-only. This field should not be set in
// requests.
DisapprovalReasons []string `json:"disapprovalReasons,omitempty"`
// Height: Ad height.
Height int64 `json:"height,omitempty"`
// Kind: Resource type.
Kind string `json:"kind,omitempty"`
// ProductCategories: Detected product categories, if any. Read-only.
// This field should not be set in requests.
ProductCategories []int64 `json:"productCategories,omitempty"`
// RestrictedCategories: All restricted categories for the ads that may
// be shown from this snippet.
RestrictedCategories []int64 `json:"restrictedCategories,omitempty"`
// SensitiveCategories: Detected sensitive categories, if any.
// Read-only. This field should not be set in requests.
SensitiveCategories []int64 `json:"sensitiveCategories,omitempty"`
// Status: Creative serving status. Read-only. This field should not be
// set in requests.
Status string `json:"status,omitempty"`
// VendorType: All vendor types for the ads that may be shown from this
// snippet.
VendorType []int64 `json:"vendorType,omitempty"`
// VideoURL: The url to fetch a video ad. If set, HTMLSnippet should not
// be set.
VideoURL string `json:"videoURL,omitempty"`
// Width: Ad width.
Width int64 `json:"width,omitempty"`
}
type CreativesList struct {
// Items: A list of creatives.
Items []*Creative `json:"items,omitempty"`
// Kind: Resource type.
Kind string `json:"kind,omitempty"`
// NextPageToken: Continuation token used to page through creatives. To
// retrieve the next page of results, set the next request's "pageToken"
// value to this.
NextPageToken string `json:"nextPageToken,omitempty"`
}
type DirectDeal struct {
// AccountId: The account id of the buyer this deal is for.
AccountId int64 `json:"accountId,omitempty"`
// Advertiser: The name of the advertiser this deal is for.
Advertiser string `json:"advertiser,omitempty"`
// CurrencyCode: The currency code that applies to the fixed_cpm value.
// If not set then assumed to be USD.
CurrencyCode string `json:"currencyCode,omitempty"`
// EndTime: End time for when this deal stops being active. If not set
// then this deal is valid until manually disabled by the publisher. In
// seconds since the epoch.
EndTime int64 `json:"endTime,omitempty,string"`
// FixedCpm: The fixed price for this direct deal. In cpm micros of
// currency according to currency_code.
FixedCpm int64 `json:"fixedCpm,omitempty,string"`
// Id: Deal id.
Id int64 `json:"id,omitempty,string"`
// Kind: Resource type.
Kind string `json:"kind,omitempty"`
// Name: Deal name.
Name string `json:"name,omitempty"`
// SellerNetwork: The name of the publisher offering this direct deal.
SellerNetwork string `json:"sellerNetwork,omitempty"`
// StartTime: Start time for when this deal becomes active. If not set
// then this deal is active immediately upon creation. In seconds since
// the epoch.
StartTime int64 `json:"startTime,omitempty,string"`
}
type DirectDealsList struct {
// DirectDeals: A list of direct deals relevant for your account.
DirectDeals []*DirectDeal `json:"directDeals,omitempty"`
// Kind: Resource type.
Kind string `json:"kind,omitempty"`
}
// method id "adexchangebuyer.accounts.get":
type AccountsGetCall struct {
s *Service
id int64
opt_ map[string]interface{}
}
// Get: Gets one account by ID.
func (r *AccountsService) Get(id int64) *AccountsGetCall {
c := &AccountsGetCall{s: r.s, opt_: make(map[string]interface{})}
c.id = id
return c
}
func (c *AccountsGetCall) Do() (*Account, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
urls := googleapi.ResolveRelative(c.s.BasePath, "accounts/{id}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{id}", strconv.FormatInt(c.id, 10), 1)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(Account)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets one account by ID.",
// "httpMethod": "GET",
// "id": "adexchangebuyer.accounts.get",
// "parameterOrder": [
// "id"
// ],
// "parameters": {
// "id": {
// "description": "The account id",
// "format": "int32",
// "location": "path",
// "required": true,
// "type": "integer"
// }
// },
// "path": "accounts/{id}",
// "response": {
// "$ref": "Account"
// },
// "scopes": [
// "https://www.googleapis.com/auth/adexchange.buyer"
// ]
// }
}
// method id "adexchangebuyer.accounts.list":
type AccountsListCall struct {
s *Service
opt_ map[string]interface{}
}
// List: Retrieves the authenticated user's list of accounts.
func (r *AccountsService) List() *AccountsListCall {
c := &AccountsListCall{s: r.s, opt_: make(map[string]interface{})}
return c
}
func (c *AccountsListCall) Do() (*AccountsList, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
urls := googleapi.ResolveRelative(c.s.BasePath, "accounts")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(AccountsList)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves the authenticated user's list of accounts.",
// "httpMethod": "GET",
// "id": "adexchangebuyer.accounts.list",
// "path": "accounts",
// "response": {
// "$ref": "AccountsList"
// },
// "scopes": [
// "https://www.googleapis.com/auth/adexchange.buyer"
// ]
// }
}
// method id "adexchangebuyer.accounts.patch":
type AccountsPatchCall struct {
s *Service
id int64
account *Account
opt_ map[string]interface{}
}
// Patch: Updates an existing account. This method supports patch
// semantics.
func (r *AccountsService) Patch(id int64, account *Account) *AccountsPatchCall {
c := &AccountsPatchCall{s: r.s, opt_: make(map[string]interface{})}
c.id = id
c.account = account
return c
}
func (c *AccountsPatchCall) Do() (*Account, error) {
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.account)
if err != nil {
return nil, err
}
ctype := "application/json"
params := make(url.Values)
params.Set("alt", "json")
urls := googleapi.ResolveRelative(c.s.BasePath, "accounts/{id}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("PATCH", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{id}", strconv.FormatInt(c.id, 10), 1)
googleapi.SetOpaque(req.URL)
req.Header.Set("Content-Type", ctype)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(Account)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates an existing account. This method supports patch semantics.",
// "httpMethod": "PATCH",
// "id": "adexchangebuyer.accounts.patch",
// "parameterOrder": [
// "id"
// ],
// "parameters": {
// "id": {
// "description": "The account id",
// "format": "int32",
// "location": "path",
// "required": true,
// "type": "integer"
// }
// },
// "path": "accounts/{id}",
// "request": {
// "$ref": "Account"
// },
// "response": {
// "$ref": "Account"
// },
// "scopes": [
// "https://www.googleapis.com/auth/adexchange.buyer"
// ]
// }
}
// method id "adexchangebuyer.accounts.update":
type AccountsUpdateCall struct {
s *Service
id int64
account *Account
opt_ map[string]interface{}
}
// Update: Updates an existing account.
func (r *AccountsService) Update(id int64, account *Account) *AccountsUpdateCall {
c := &AccountsUpdateCall{s: r.s, opt_: make(map[string]interface{})}
c.id = id
c.account = account
return c
}
func (c *AccountsUpdateCall) Do() (*Account, error) {
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.account)
if err != nil {
return nil, err
}
ctype := "application/json"
params := make(url.Values)
params.Set("alt", "json")
urls := googleapi.ResolveRelative(c.s.BasePath, "accounts/{id}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("PUT", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{id}", strconv.FormatInt(c.id, 10), 1)
googleapi.SetOpaque(req.URL)
req.Header.Set("Content-Type", ctype)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(Account)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates an existing account.",
// "httpMethod": "PUT",
// "id": "adexchangebuyer.accounts.update",
// "parameterOrder": [
// "id"
// ],
// "parameters": {
// "id": {
// "description": "The account id",
// "format": "int32",
// "location": "path",
// "required": true,
// "type": "integer"
// }
// },
// "path": "accounts/{id}",
// "request": {
// "$ref": "Account"
// },
// "response": {
// "$ref": "Account"
// },
// "scopes": [
// "https://www.googleapis.com/auth/adexchange.buyer"
// ]
// }
}
// method id "adexchangebuyer.creatives.get":
type CreativesGetCall struct {
s *Service
accountId int64
buyerCreativeId string
adgroupId int64
opt_ map[string]interface{}
}
// Get: Gets the status for a single creative.
func (r *CreativesService) Get(accountId int64, buyerCreativeId string, adgroupId int64) *CreativesGetCall {
c := &CreativesGetCall{s: r.s, opt_: make(map[string]interface{})}
c.accountId = accountId
c.buyerCreativeId = buyerCreativeId
c.adgroupId = adgroupId
return c
}
func (c *CreativesGetCall) Do() (*Creative, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
params.Set("adgroupId", fmt.Sprintf("%v", c.adgroupId))
urls := googleapi.ResolveRelative(c.s.BasePath, "creatives/{accountId}/{buyerCreativeId}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{accountId}", strconv.FormatInt(c.accountId, 10), 1)
req.URL.Path = strings.Replace(req.URL.Path, "{buyerCreativeId}", url.QueryEscape(c.buyerCreativeId), 1)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(Creative)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets the status for a single creative.",
// "httpMethod": "GET",
// "id": "adexchangebuyer.creatives.get",
// "parameterOrder": [
// "accountId",
// "buyerCreativeId",
// "adgroupId"
// ],
// "parameters": {
// "accountId": {
// "description": "The id for the account that will serve this creative.",
// "format": "int32",
// "location": "path",
// "required": true,
// "type": "integer"
// },
// "adgroupId": {
// "description": "The adgroup this creative belongs to.",
// "format": "int64",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "buyerCreativeId": {
// "description": "The buyer-specific id for this creative.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "creatives/{accountId}/{buyerCreativeId}",
// "response": {
// "$ref": "Creative"
// },
// "scopes": [
// "https://www.googleapis.com/auth/adexchange.buyer"
// ]
// }
}
// method id "adexchangebuyer.creatives.insert":
type CreativesInsertCall struct {
s *Service
creative *Creative
opt_ map[string]interface{}
}
// Insert: Submit a new creative.
func (r *CreativesService) Insert(creative *Creative) *CreativesInsertCall {
c := &CreativesInsertCall{s: r.s, opt_: make(map[string]interface{})}
c.creative = creative
return c
}
func (c *CreativesInsertCall) Do() (*Creative, error) {
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.creative)
if err != nil {
return nil, err
}
ctype := "application/json"
params := make(url.Values)
params.Set("alt", "json")
urls := googleapi.ResolveRelative(c.s.BasePath, "creatives")
urls += "?" + params.Encode()
req, _ := http.NewRequest("POST", urls, body)
googleapi.SetOpaque(req.URL)
req.Header.Set("Content-Type", ctype)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(Creative)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Submit a new creative.",
// "httpMethod": "POST",
// "id": "adexchangebuyer.creatives.insert",
// "path": "creatives",
// "request": {
// "$ref": "Creative"
// },
// "response": {
// "$ref": "Creative"
// },
// "scopes": [
// "https://www.googleapis.com/auth/adexchange.buyer"
// ]
// }
}
// method id "adexchangebuyer.creatives.list":
type CreativesListCall struct {
s *Service
opt_ map[string]interface{}
}
// List: Retrieves a list of the authenticated user's active creatives.
func (r *CreativesService) List() *CreativesListCall {
c := &CreativesListCall{s: r.s, opt_: make(map[string]interface{})}
return c
}
// MaxResults sets the optional parameter "maxResults": Maximum number
// of entries returned on one result page. If not set, the default is
// 100.
func (c *CreativesListCall) MaxResults(maxResults int64) *CreativesListCall {
c.opt_["maxResults"] = maxResults
return c
}
// PageToken sets the optional parameter "pageToken": A continuation
// token, used to page through ad clients. To retrieve the next page,
// set this parameter to the value of "nextPageToken" from the previous
// response.
func (c *CreativesListCall) PageToken(pageToken string) *CreativesListCall {
c.opt_["pageToken"] = pageToken
return c
}
func (c *CreativesListCall) Do() (*CreativesList, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["maxResults"]; ok {
params.Set("maxResults", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["pageToken"]; ok {
params.Set("pageToken", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "creatives")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(CreativesList)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves a list of the authenticated user's active creatives.",
// "httpMethod": "GET",
// "id": "adexchangebuyer.creatives.list",
// "parameters": {
// "maxResults": {
// "description": "Maximum number of entries returned on one result page. If not set, the default is 100. Optional.",
// "format": "uint32",
// "location": "query",
// "maximum": "1000",
// "minimum": "1",
// "type": "integer"
// },
// "pageToken": {
// "description": "A continuation token, used to page through ad clients. To retrieve the next page, set this parameter to the value of \"nextPageToken\" from the previous response. Optional.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "creatives",
// "response": {
// "$ref": "CreativesList"
// },
// "scopes": [
// "https://www.googleapis.com/auth/adexchange.buyer"
// ]
// }
}
// method id "adexchangebuyer.directDeals.get":
type DirectDealsGetCall struct {
s *Service
id int64
opt_ map[string]interface{}
}
// Get: Gets one direct deal by ID.
func (r *DirectDealsService) Get(id int64) *DirectDealsGetCall {
c := &DirectDealsGetCall{s: r.s, opt_: make(map[string]interface{})}
c.id = id
return c
}
func (c *DirectDealsGetCall) Do() (*DirectDeal, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
urls := googleapi.ResolveRelative(c.s.BasePath, "directdeals/{id}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{id}", strconv.FormatInt(c.id, 10), 1)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(DirectDeal)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets one direct deal by ID.",
// "httpMethod": "GET",
// "id": "adexchangebuyer.directDeals.get",
// "parameterOrder": [
// "id"
// ],
// "parameters": {
// "id": {
// "description": "The direct deal id",
// "format": "int64",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "directdeals/{id}",
// "response": {
// "$ref": "DirectDeal"
// },
// "scopes": [
// "https://www.googleapis.com/auth/adexchange.buyer"
// ]
// }
}
// method id "adexchangebuyer.directDeals.list":
type DirectDealsListCall struct {
s *Service
opt_ map[string]interface{}
}
// List: Retrieves the authenticated user's list of direct deals.
func (r *DirectDealsService) List() *DirectDealsListCall {
c := &DirectDealsListCall{s: r.s, opt_: make(map[string]interface{})}
return c
}
func (c *DirectDealsListCall) Do() (*DirectDealsList, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
urls := googleapi.ResolveRelative(c.s.BasePath, "directdeals")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(DirectDealsList)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves the authenticated user's list of direct deals.",
// "httpMethod": "GET",
// "id": "adexchangebuyer.directDeals.list",
// "path": "directdeals",
// "response": {
// "$ref": "DirectDealsList"
// },
// "scopes": [
// "https://www.googleapis.com/auth/adexchange.buyer"
// ]
// }
}

View File

@ -0,0 +1,917 @@
{
"kind": "discovery#restDescription",
"etag": "\"kEk3sFj6Ef5_yR1-H3bAO6qw9mI/k4EGd11ZUVmhrZoqHDxlI_JyIAo\"",
"discoveryVersion": "v1",
"id": "adexchangeseller:v1",
"name": "adexchangeseller",
"canonicalName": "Ad Exchange Seller",
"version": "v1",
"title": "Ad Exchange Seller API",
"description": "Gives Ad Exchange seller users access to their inventory and the ability to generate reports",
"ownerDomain": "google.com",
"ownerName": "Google",
"icons": {
"x16": "http://www.google.com/images/icons/product/doubleclick-16.gif",
"x32": "http://www.google.com/images/icons/product/doubleclick-32.gif"
},
"documentationLink": "https://developers.google.com/ad-exchange/seller-rest/",
"protocol": "rest",
"baseUrl": "https://www.googleapis.com/adexchangeseller/v1/",
"basePath": "/adexchangeseller/v1/",
"rootUrl": "https://www.googleapis.com/",
"servicePath": "adexchangeseller/v1/",
"batchPath": "batch",
"parameters": {
"alt": {
"type": "string",
"description": "Data format for the response.",
"default": "json",
"enum": [
"csv",
"json"
],
"enumDescriptions": [
"Responses with Content-Type of text/csv",
"Responses with Content-Type of application/json"
],
"location": "query"
},
"fields": {
"type": "string",
"description": "Selector specifying which fields to include in a partial response.",
"location": "query"
},
"key": {
"type": "string",
"description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.",
"location": "query"
},
"oauth_token": {
"type": "string",
"description": "OAuth 2.0 token for the current user.",
"location": "query"
},
"prettyPrint": {
"type": "boolean",
"description": "Returns response with indentations and line breaks.",
"default": "true",
"location": "query"
},
"quotaUser": {
"type": "string",
"description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.",
"location": "query"
},
"userIp": {
"type": "string",
"description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.",
"location": "query"
}
},
"auth": {
"oauth2": {
"scopes": {
"https://www.googleapis.com/auth/adexchange.seller": {
"description": "View and manage your Ad Exchange data"
},
"https://www.googleapis.com/auth/adexchange.seller.readonly": {
"description": "View your Ad Exchange data"
}
}
}
},
"schemas": {
"AdClient": {
"id": "AdClient",
"type": "object",
"properties": {
"arcOptIn": {
"type": "boolean",
"description": "Whether this ad client is opted in to ARC."
},
"id": {
"type": "string",
"description": "Unique identifier of this ad client."
},
"kind": {
"type": "string",
"description": "Kind of resource this is, in this case adexchangeseller#adClient.",
"default": "adexchangeseller#adClient"
},
"productCode": {
"type": "string",
"description": "This ad client's product code, which corresponds to the PRODUCT_CODE report dimension."
},
"supportsReporting": {
"type": "boolean",
"description": "Whether this ad client supports being reported on."
}
}
},
"AdClients": {
"id": "AdClients",
"type": "object",
"properties": {
"etag": {
"type": "string",
"description": "ETag of this response for caching purposes."
},
"items": {
"type": "array",
"description": "The ad clients returned in this list response.",
"items": {
"$ref": "AdClient"
}
},
"kind": {
"type": "string",
"description": "Kind of list this is, in this case adexchangeseller#adClients.",
"default": "adexchangeseller#adClients"
},
"nextPageToken": {
"type": "string",
"description": "Continuation token used to page through ad clients. To retrieve the next page of results, set the next request's \"pageToken\" value to this."
}
}
},
"AdUnit": {
"id": "AdUnit",
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "Identity code of this ad unit, not necessarily unique across ad clients."
},
"id": {
"type": "string",
"description": "Unique identifier of this ad unit. This should be considered an opaque identifier; it is not safe to rely on it being in any particular format."
},
"kind": {
"type": "string",
"description": "Kind of resource this is, in this case adexchangeseller#adUnit.",
"default": "adexchangeseller#adUnit"
},
"name": {
"type": "string",
"description": "Name of this ad unit."
},
"status": {
"type": "string",
"description": "Status of this ad unit. Possible values are:\nNEW: Indicates that the ad unit was created within the last seven days and does not yet have any activity associated with it.\n\nACTIVE: Indicates that there has been activity on this ad unit in the last seven days.\n\nINACTIVE: Indicates that there has been no activity on this ad unit in the last seven days."
}
}
},
"AdUnits": {
"id": "AdUnits",
"type": "object",
"properties": {
"etag": {
"type": "string",
"description": "ETag of this response for caching purposes."
},
"items": {
"type": "array",
"description": "The ad units returned in this list response.",
"items": {
"$ref": "AdUnit"
}
},
"kind": {
"type": "string",
"description": "Kind of list this is, in this case adexchangeseller#adUnits.",
"default": "adexchangeseller#adUnits"
},
"nextPageToken": {
"type": "string",
"description": "Continuation token used to page through ad units. To retrieve the next page of results, set the next request's \"pageToken\" value to this."
}
}
},
"CustomChannel": {
"id": "CustomChannel",
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "Code of this custom channel, not necessarily unique across ad clients."
},
"id": {
"type": "string",
"description": "Unique identifier of this custom channel. This should be considered an opaque identifier; it is not safe to rely on it being in any particular format."
},
"kind": {
"type": "string",
"description": "Kind of resource this is, in this case adexchangeseller#customChannel.",
"default": "adexchangeseller#customChannel"
},
"name": {
"type": "string",
"description": "Name of this custom channel."
},
"targetingInfo": {
"type": "object",
"description": "The targeting information of this custom channel, if activated.",
"properties": {
"adsAppearOn": {
"type": "string",
"description": "The name used to describe this channel externally."
},
"description": {
"type": "string",
"description": "The external description of the channel."
},
"location": {
"type": "string",
"description": "The locations in which ads appear. (Only valid for content and mobile content ads). Acceptable values for content ads are: TOP_LEFT, TOP_CENTER, TOP_RIGHT, MIDDLE_LEFT, MIDDLE_CENTER, MIDDLE_RIGHT, BOTTOM_LEFT, BOTTOM_CENTER, BOTTOM_RIGHT, MULTIPLE_LOCATIONS. Acceptable values for mobile content ads are: TOP, MIDDLE, BOTTOM, MULTIPLE_LOCATIONS."
},
"siteLanguage": {
"type": "string",
"description": "The language of the sites ads will be displayed on."
}
}
}
}
},
"CustomChannels": {
"id": "CustomChannels",
"type": "object",
"properties": {
"etag": {
"type": "string",
"description": "ETag of this response for caching purposes."
},
"items": {
"type": "array",
"description": "The custom channels returned in this list response.",
"items": {
"$ref": "CustomChannel"
}
},
"kind": {
"type": "string",
"description": "Kind of list this is, in this case adexchangeseller#customChannels.",
"default": "adexchangeseller#customChannels"
},
"nextPageToken": {
"type": "string",
"description": "Continuation token used to page through custom channels. To retrieve the next page of results, set the next request's \"pageToken\" value to this."
}
}
},
"Report": {
"id": "Report",
"type": "object",
"properties": {
"averages": {
"type": "array",
"description": "The averages of the report. This is the same length as any other row in the report; cells corresponding to dimension columns are empty.",
"items": {
"type": "string"
}
},
"headers": {
"type": "array",
"description": "The header information of the columns requested in the report. This is a list of headers; one for each dimension in the request, followed by one for each metric in the request.",
"items": {
"type": "object",
"properties": {
"currency": {
"type": "string",
"description": "The currency of this column. Only present if the header type is METRIC_CURRENCY."
},
"name": {
"type": "string",
"description": "The name of the header."
},
"type": {
"type": "string",
"description": "The type of the header; one of DIMENSION, METRIC_TALLY, METRIC_RATIO, or METRIC_CURRENCY."
}
}
}
},
"kind": {
"type": "string",
"description": "Kind this is, in this case adexchangeseller#report.",
"default": "adexchangeseller#report"
},
"rows": {
"type": "array",
"description": "The output rows of the report. Each row is a list of cells; one for each dimension in the request, followed by one for each metric in the request. The dimension cells contain strings, and the metric cells contain numbers.",
"items": {
"type": "array",
"items": {
"type": "string"
}
}
},
"totalMatchedRows": {
"type": "string",
"description": "The total number of rows matched by the report request. Fewer rows may be returned in the response due to being limited by the row count requested or the report row limit.",
"format": "int64"
},
"totals": {
"type": "array",
"description": "The totals of the report. This is the same length as any other row in the report; cells corresponding to dimension columns are empty.",
"items": {
"type": "string"
}
},
"warnings": {
"type": "array",
"description": "Any warnings associated with generation of the report.",
"items": {
"type": "string"
}
}
}
},
"SavedReport": {
"id": "SavedReport",
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "Unique identifier of this saved report."
},
"kind": {
"type": "string",
"description": "Kind of resource this is, in this case adexchangeseller#savedReport.",
"default": "adexchangeseller#savedReport"
},
"name": {
"type": "string",
"description": "This saved report's name."
}
}
},
"SavedReports": {
"id": "SavedReports",
"type": "object",
"properties": {
"etag": {
"type": "string",
"description": "ETag of this response for caching purposes."
},
"items": {
"type": "array",
"description": "The saved reports returned in this list response.",
"items": {
"$ref": "SavedReport"
}
},
"kind": {
"type": "string",
"description": "Kind of list this is, in this case adexchangeseller#savedReports.",
"default": "adexchangeseller#savedReports"
},
"nextPageToken": {
"type": "string",
"description": "Continuation token used to page through saved reports. To retrieve the next page of results, set the next request's \"pageToken\" value to this."
}
}
},
"UrlChannel": {
"id": "UrlChannel",
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "Unique identifier of this URL channel. This should be considered an opaque identifier; it is not safe to rely on it being in any particular format."
},
"kind": {
"type": "string",
"description": "Kind of resource this is, in this case adexchangeseller#urlChannel.",
"default": "adexchangeseller#urlChannel"
},
"urlPattern": {
"type": "string",
"description": "URL Pattern of this URL channel. Does not include \"http://\" or \"https://\". Example: www.example.com/home"
}
}
},
"UrlChannels": {
"id": "UrlChannels",
"type": "object",
"properties": {
"etag": {
"type": "string",
"description": "ETag of this response for caching purposes."
},
"items": {
"type": "array",
"description": "The URL channels returned in this list response.",
"items": {
"$ref": "UrlChannel"
}
},
"kind": {
"type": "string",
"description": "Kind of list this is, in this case adexchangeseller#urlChannels.",
"default": "adexchangeseller#urlChannels"
},
"nextPageToken": {
"type": "string",
"description": "Continuation token used to page through URL channels. To retrieve the next page of results, set the next request's \"pageToken\" value to this."
}
}
}
},
"resources": {
"adclients": {
"methods": {
"list": {
"id": "adexchangeseller.adclients.list",
"path": "adclients",
"httpMethod": "GET",
"description": "List all ad clients in this Ad Exchange account.",
"parameters": {
"maxResults": {
"type": "integer",
"description": "The maximum number of ad clients to include in the response, used for paging.",
"format": "uint32",
"minimum": "0",
"maximum": "10000",
"location": "query"
},
"pageToken": {
"type": "string",
"description": "A continuation token, used to page through ad clients. To retrieve the next page, set this parameter to the value of \"nextPageToken\" from the previous response.",
"location": "query"
}
},
"response": {
"$ref": "AdClients"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.seller",
"https://www.googleapis.com/auth/adexchange.seller.readonly"
]
}
}
},
"adunits": {
"methods": {
"get": {
"id": "adexchangeseller.adunits.get",
"path": "adclients/{adClientId}/adunits/{adUnitId}",
"httpMethod": "GET",
"description": "Gets the specified ad unit in the specified ad client.",
"parameters": {
"adClientId": {
"type": "string",
"description": "Ad client for which to get the ad unit.",
"required": true,
"location": "path"
},
"adUnitId": {
"type": "string",
"description": "Ad unit to retrieve.",
"required": true,
"location": "path"
}
},
"parameterOrder": [
"adClientId",
"adUnitId"
],
"response": {
"$ref": "AdUnit"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.seller",
"https://www.googleapis.com/auth/adexchange.seller.readonly"
]
},
"list": {
"id": "adexchangeseller.adunits.list",
"path": "adclients/{adClientId}/adunits",
"httpMethod": "GET",
"description": "List all ad units in the specified ad client for this Ad Exchange account.",
"parameters": {
"adClientId": {
"type": "string",
"description": "Ad client for which to list ad units.",
"required": true,
"location": "path"
},
"includeInactive": {
"type": "boolean",
"description": "Whether to include inactive ad units. Default: true.",
"location": "query"
},
"maxResults": {
"type": "integer",
"description": "The maximum number of ad units to include in the response, used for paging.",
"format": "uint32",
"minimum": "0",
"maximum": "10000",
"location": "query"
},
"pageToken": {
"type": "string",
"description": "A continuation token, used to page through ad units. To retrieve the next page, set this parameter to the value of \"nextPageToken\" from the previous response.",
"location": "query"
}
},
"parameterOrder": [
"adClientId"
],
"response": {
"$ref": "AdUnits"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.seller",
"https://www.googleapis.com/auth/adexchange.seller.readonly"
]
}
},
"resources": {
"customchannels": {
"methods": {
"list": {
"id": "adexchangeseller.adunits.customchannels.list",
"path": "adclients/{adClientId}/adunits/{adUnitId}/customchannels",
"httpMethod": "GET",
"description": "List all custom channels which the specified ad unit belongs to.",
"parameters": {
"adClientId": {
"type": "string",
"description": "Ad client which contains the ad unit.",
"required": true,
"location": "path"
},
"adUnitId": {
"type": "string",
"description": "Ad unit for which to list custom channels.",
"required": true,
"location": "path"
},
"maxResults": {
"type": "integer",
"description": "The maximum number of custom channels to include in the response, used for paging.",
"format": "uint32",
"minimum": "0",
"maximum": "10000",
"location": "query"
},
"pageToken": {
"type": "string",
"description": "A continuation token, used to page through custom channels. To retrieve the next page, set this parameter to the value of \"nextPageToken\" from the previous response.",
"location": "query"
}
},
"parameterOrder": [
"adClientId",
"adUnitId"
],
"response": {
"$ref": "CustomChannels"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.seller",
"https://www.googleapis.com/auth/adexchange.seller.readonly"
]
}
}
}
}
},
"customchannels": {
"methods": {
"get": {
"id": "adexchangeseller.customchannels.get",
"path": "adclients/{adClientId}/customchannels/{customChannelId}",
"httpMethod": "GET",
"description": "Get the specified custom channel from the specified ad client.",
"parameters": {
"adClientId": {
"type": "string",
"description": "Ad client which contains the custom channel.",
"required": true,
"location": "path"
},
"customChannelId": {
"type": "string",
"description": "Custom channel to retrieve.",
"required": true,
"location": "path"
}
},
"parameterOrder": [
"adClientId",
"customChannelId"
],
"response": {
"$ref": "CustomChannel"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.seller",
"https://www.googleapis.com/auth/adexchange.seller.readonly"
]
},
"list": {
"id": "adexchangeseller.customchannels.list",
"path": "adclients/{adClientId}/customchannels",
"httpMethod": "GET",
"description": "List all custom channels in the specified ad client for this Ad Exchange account.",
"parameters": {
"adClientId": {
"type": "string",
"description": "Ad client for which to list custom channels.",
"required": true,
"location": "path"
},
"maxResults": {
"type": "integer",
"description": "The maximum number of custom channels to include in the response, used for paging.",
"format": "uint32",
"minimum": "0",
"maximum": "10000",
"location": "query"
},
"pageToken": {
"type": "string",
"description": "A continuation token, used to page through custom channels. To retrieve the next page, set this parameter to the value of \"nextPageToken\" from the previous response.",
"location": "query"
}
},
"parameterOrder": [
"adClientId"
],
"response": {
"$ref": "CustomChannels"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.seller",
"https://www.googleapis.com/auth/adexchange.seller.readonly"
]
}
},
"resources": {
"adunits": {
"methods": {
"list": {
"id": "adexchangeseller.customchannels.adunits.list",
"path": "adclients/{adClientId}/customchannels/{customChannelId}/adunits",
"httpMethod": "GET",
"description": "List all ad units in the specified custom channel.",
"parameters": {
"adClientId": {
"type": "string",
"description": "Ad client which contains the custom channel.",
"required": true,
"location": "path"
},
"customChannelId": {
"type": "string",
"description": "Custom channel for which to list ad units.",
"required": true,
"location": "path"
},
"includeInactive": {
"type": "boolean",
"description": "Whether to include inactive ad units. Default: true.",
"location": "query"
},
"maxResults": {
"type": "integer",
"description": "The maximum number of ad units to include in the response, used for paging.",
"format": "uint32",
"minimum": "0",
"maximum": "10000",
"location": "query"
},
"pageToken": {
"type": "string",
"description": "A continuation token, used to page through ad units. To retrieve the next page, set this parameter to the value of \"nextPageToken\" from the previous response.",
"location": "query"
}
},
"parameterOrder": [
"adClientId",
"customChannelId"
],
"response": {
"$ref": "AdUnits"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.seller",
"https://www.googleapis.com/auth/adexchange.seller.readonly"
]
}
}
}
}
},
"reports": {
"methods": {
"generate": {
"id": "adexchangeseller.reports.generate",
"path": "reports",
"httpMethod": "GET",
"description": "Generate an Ad Exchange report based on the report request sent in the query parameters. Returns the result as JSON; to retrieve output in CSV format specify \"alt=csv\" as a query parameter.",
"parameters": {
"dimension": {
"type": "string",
"description": "Dimensions to base the report on.",
"pattern": "[a-zA-Z_]+",
"repeated": true,
"location": "query"
},
"endDate": {
"type": "string",
"description": "End of the date range to report on in \"YYYY-MM-DD\" format, inclusive.",
"required": true,
"pattern": "\\d{4}-\\d{2}-\\d{2}|(today|startOfMonth|startOfYear)(([\\-\\+]\\d+[dwmy]){0,3}?)",
"location": "query"
},
"filter": {
"type": "string",
"description": "Filters to be run on the report.",
"pattern": "[a-zA-Z_]+(==|=@).+",
"repeated": true,
"location": "query"
},
"locale": {
"type": "string",
"description": "Optional locale to use for translating report output to a local language. Defaults to \"en_US\" if not specified.",
"pattern": "[a-zA-Z_]+",
"location": "query"
},
"maxResults": {
"type": "integer",
"description": "The maximum number of rows of report data to return.",
"format": "uint32",
"minimum": "0",
"maximum": "50000",
"location": "query"
},
"metric": {
"type": "string",
"description": "Numeric columns to include in the report.",
"pattern": "[a-zA-Z_]+",
"repeated": true,
"location": "query"
},
"sort": {
"type": "string",
"description": "The name of a dimension or metric to sort the resulting report on, optionally prefixed with \"+\" to sort ascending or \"-\" to sort descending. If no prefix is specified, the column is sorted ascending.",
"pattern": "(\\+|-)?[a-zA-Z_]+",
"repeated": true,
"location": "query"
},
"startDate": {
"type": "string",
"description": "Start of the date range to report on in \"YYYY-MM-DD\" format, inclusive.",
"required": true,
"pattern": "\\d{4}-\\d{2}-\\d{2}|(today|startOfMonth|startOfYear)(([\\-\\+]\\d+[dwmy]){0,3}?)",
"location": "query"
},
"startIndex": {
"type": "integer",
"description": "Index of the first row of report data to return.",
"format": "uint32",
"minimum": "0",
"maximum": "5000",
"location": "query"
}
},
"parameterOrder": [
"startDate",
"endDate"
],
"response": {
"$ref": "Report"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.seller",
"https://www.googleapis.com/auth/adexchange.seller.readonly"
],
"supportsMediaDownload": true
}
},
"resources": {
"saved": {
"methods": {
"generate": {
"id": "adexchangeseller.reports.saved.generate",
"path": "reports/{savedReportId}",
"httpMethod": "GET",
"description": "Generate an Ad Exchange report based on the saved report ID sent in the query parameters.",
"parameters": {
"locale": {
"type": "string",
"description": "Optional locale to use for translating report output to a local language. Defaults to \"en_US\" if not specified.",
"pattern": "[a-zA-Z_]+",
"location": "query"
},
"maxResults": {
"type": "integer",
"description": "The maximum number of rows of report data to return.",
"format": "int32",
"minimum": "0",
"maximum": "50000",
"location": "query"
},
"savedReportId": {
"type": "string",
"description": "The saved report to retrieve.",
"required": true,
"location": "path"
},
"startIndex": {
"type": "integer",
"description": "Index of the first row of report data to return.",
"format": "int32",
"minimum": "0",
"maximum": "5000",
"location": "query"
}
},
"parameterOrder": [
"savedReportId"
],
"response": {
"$ref": "Report"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.seller",
"https://www.googleapis.com/auth/adexchange.seller.readonly"
]
},
"list": {
"id": "adexchangeseller.reports.saved.list",
"path": "reports/saved",
"httpMethod": "GET",
"description": "List all saved reports in this Ad Exchange account.",
"parameters": {
"maxResults": {
"type": "integer",
"description": "The maximum number of saved reports to include in the response, used for paging.",
"format": "int32",
"minimum": "0",
"maximum": "100",
"location": "query"
},
"pageToken": {
"type": "string",
"description": "A continuation token, used to page through saved reports. To retrieve the next page, set this parameter to the value of \"nextPageToken\" from the previous response.",
"location": "query"
}
},
"response": {
"$ref": "SavedReports"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.seller",
"https://www.googleapis.com/auth/adexchange.seller.readonly"
]
}
}
}
}
},
"urlchannels": {
"methods": {
"list": {
"id": "adexchangeseller.urlchannels.list",
"path": "adclients/{adClientId}/urlchannels",
"httpMethod": "GET",
"description": "List all URL channels in the specified ad client for this Ad Exchange account.",
"parameters": {
"adClientId": {
"type": "string",
"description": "Ad client for which to list URL channels.",
"required": true,
"location": "path"
},
"maxResults": {
"type": "integer",
"description": "The maximum number of URL channels to include in the response, used for paging.",
"format": "uint32",
"minimum": "0",
"maximum": "10000",
"location": "query"
},
"pageToken": {
"type": "string",
"description": "A continuation token, used to page through URL channels. To retrieve the next page, set this parameter to the value of \"nextPageToken\" from the previous response.",
"location": "query"
}
},
"parameterOrder": [
"adClientId"
],
"response": {
"$ref": "UrlChannels"
},
"scopes": [
"https://www.googleapis.com/auth/adexchange.seller",
"https://www.googleapis.com/auth/adexchange.seller.readonly"
]
}
}
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,172 @@
{
"kind": "discovery#restDescription",
"etag": "\"kEk3sFj6Ef5_yR1-H3bAO6qw9mI/5IR4qYAEytuHObETjxcLeQt8rDQ\"",
"discoveryVersion": "v1",
"id": "admin:email_migration_v2",
"name": "admin",
"version": "email_migration_v2",
"title": "Email Migration API v2",
"description": "Email Migration API lets you migrate emails of users to Google backends.",
"ownerDomain": "google.com",
"ownerName": "Google",
"icons": {
"x16": "http://www.google.com/images/icons/product/search-16.gif",
"x32": "http://www.google.com/images/icons/product/search-32.gif"
},
"documentationLink": "https://developers.google.com/admin-sdk/email-migration/v2/",
"protocol": "rest",
"baseUrl": "https://www.googleapis.com/email/v2/users/",
"basePath": "/email/v2/users/",
"rootUrl": "https://www.googleapis.com/",
"servicePath": "email/v2/users/",
"batchPath": "batch",
"parameters": {
"alt": {
"type": "string",
"description": "Data format for the response.",
"default": "json",
"enum": [
"json"
],
"enumDescriptions": [
"Responses with Content-Type of application/json"
],
"location": "query"
},
"fields": {
"type": "string",
"description": "Selector specifying which fields to include in a partial response.",
"location": "query"
},
"key": {
"type": "string",
"description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.",
"location": "query"
},
"oauth_token": {
"type": "string",
"description": "OAuth 2.0 token for the current user.",
"location": "query"
},
"prettyPrint": {
"type": "boolean",
"description": "Returns response with indentations and line breaks.",
"default": "true",
"location": "query"
},
"quotaUser": {
"type": "string",
"description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.",
"location": "query"
},
"userIp": {
"type": "string",
"description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.",
"location": "query"
}
},
"auth": {
"oauth2": {
"scopes": {
"https://www.googleapis.com/auth/email.migration": {
"description": "Manage email messages of users on your domain"
}
}
}
},
"schemas": {
"MailItem": {
"id": "MailItem",
"type": "object",
"description": "JSON template for MailItem object in Email Migration API.",
"properties": {
"isDeleted": {
"type": "boolean",
"description": "Boolean indicating if the mail is deleted (used in Vault)"
},
"isDraft": {
"type": "boolean",
"description": "Boolean indicating if the mail is draft"
},
"isInbox": {
"type": "boolean",
"description": "Boolean indicating if the mail is in inbox"
},
"isSent": {
"type": "boolean",
"description": "Boolean indicating if the mail is in 'sent mails'"
},
"isStarred": {
"type": "boolean",
"description": "Boolean indicating if the mail is starred"
},
"isTrash": {
"type": "boolean",
"description": "Boolean indicating if the mail is in trash"
},
"isUnread": {
"type": "boolean",
"description": "Boolean indicating if the mail is unread"
},
"kind": {
"type": "string",
"description": "Kind of resource this is.",
"default": "mailItem"
},
"labels": {
"type": "array",
"description": "List of labels (strings)",
"items": {
"type": "string"
}
}
}
}
},
"resources": {
"mail": {
"methods": {
"insert": {
"id": "emailMigration.mail.insert",
"path": "{userKey}/mail",
"httpMethod": "POST",
"description": "Insert Mail into Google's Gmail backends",
"parameters": {
"userKey": {
"type": "string",
"description": "The email or immutable id of the user",
"required": true,
"location": "path"
}
},
"parameterOrder": [
"userKey"
],
"request": {
"$ref": "MailItem"
},
"scopes": [
"https://www.googleapis.com/auth/email.migration"
],
"supportsMediaUpload": true,
"mediaUpload": {
"accept": [
"message/rfc822"
],
"maxSize": "35MB",
"protocols": {
"simple": {
"multipart": true,
"path": "/upload/email/v2/users/{userKey}/mail"
},
"resumable": {
"multipart": true,
"path": "/resumable/upload/email/v2/users/{userKey}/mail"
}
}
}
}
}
}
}
}

View File

@ -0,0 +1,198 @@
// Package admin provides access to the Email Migration API v2.
//
// See https://developers.google.com/admin-sdk/email-migration/v2/
//
// Usage example:
//
// import "code.google.com/p/google-api-go-client/admin/email_migration_v2"
// ...
// adminService, err := admin.New(oauthHttpClient)
package admin
import (
"bytes"
"code.google.com/p/google-api-go-client/googleapi"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
)
// Always reference these packages, just in case the auto-generated code
// below doesn't.
var _ = bytes.NewBuffer
var _ = strconv.Itoa
var _ = fmt.Sprintf
var _ = json.NewDecoder
var _ = io.Copy
var _ = url.Parse
var _ = googleapi.Version
var _ = errors.New
var _ = strings.Replace
const apiId = "admin:email_migration_v2"
const apiName = "admin"
const apiVersion = "email_migration_v2"
const basePath = "https://www.googleapis.com/email/v2/users/"
// OAuth2 scopes used by this API.
const (
// Manage email messages of users on your domain
EmailMigrationScope = "https://www.googleapis.com/auth/email.migration"
)
func New(client *http.Client) (*Service, error) {
if client == nil {
return nil, errors.New("client is nil")
}
s := &Service{client: client, BasePath: basePath}
s.Mail = NewMailService(s)
return s, nil
}
type Service struct {
client *http.Client
BasePath string // API endpoint base URL
Mail *MailService
}
func NewMailService(s *Service) *MailService {
rs := &MailService{s: s}
return rs
}
type MailService struct {
s *Service
}
type MailItem struct {
// IsDeleted: Boolean indicating if the mail is deleted (used in Vault)
IsDeleted bool `json:"isDeleted,omitempty"`
// IsDraft: Boolean indicating if the mail is draft
IsDraft bool `json:"isDraft,omitempty"`
// IsInbox: Boolean indicating if the mail is in inbox
IsInbox bool `json:"isInbox,omitempty"`
// IsSent: Boolean indicating if the mail is in 'sent mails'
IsSent bool `json:"isSent,omitempty"`
// IsStarred: Boolean indicating if the mail is starred
IsStarred bool `json:"isStarred,omitempty"`
// IsTrash: Boolean indicating if the mail is in trash
IsTrash bool `json:"isTrash,omitempty"`
// IsUnread: Boolean indicating if the mail is unread
IsUnread bool `json:"isUnread,omitempty"`
// Kind: Kind of resource this is.
Kind string `json:"kind,omitempty"`
// Labels: List of labels (strings)
Labels []string `json:"labels,omitempty"`
}
// method id "emailMigration.mail.insert":
type MailInsertCall struct {
s *Service
userKey string
mailitem *MailItem
opt_ map[string]interface{}
media_ io.Reader
}
// Insert: Insert Mail into Google's Gmail backends
func (r *MailService) Insert(userKey string, mailitem *MailItem) *MailInsertCall {
c := &MailInsertCall{s: r.s, opt_: make(map[string]interface{})}
c.userKey = userKey
c.mailitem = mailitem
return c
}
func (c *MailInsertCall) Media(r io.Reader) *MailInsertCall {
c.media_ = r
return c
}
func (c *MailInsertCall) Do() error {
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.mailitem)
if err != nil {
return err
}
ctype := "application/json"
params := make(url.Values)
params.Set("alt", "json")
urls := googleapi.ResolveRelative(c.s.BasePath, "{userKey}/mail")
if c.media_ != nil {
urls = strings.Replace(urls, "https://www.googleapis.com/", "https://www.googleapis.com/upload/", 1)
params.Set("uploadType", "multipart")
}
urls += "?" + params.Encode()
contentLength_, hasMedia_ := googleapi.ConditionallyIncludeMedia(c.media_, &body, &ctype)
req, _ := http.NewRequest("POST", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{userKey}", url.QueryEscape(c.userKey), 1)
googleapi.SetOpaque(req.URL)
if hasMedia_ {
req.ContentLength = contentLength_
}
req.Header.Set("Content-Type", ctype)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Insert Mail into Google's Gmail backends",
// "httpMethod": "POST",
// "id": "emailMigration.mail.insert",
// "mediaUpload": {
// "accept": [
// "message/rfc822"
// ],
// "maxSize": "35MB",
// "protocols": {
// "resumable": {
// "multipart": true,
// "path": "/resumable/upload/email/v2/users/{userKey}/mail"
// },
// "simple": {
// "multipart": true,
// "path": "/upload/email/v2/users/{userKey}/mail"
// }
// }
// },
// "parameterOrder": [
// "userKey"
// ],
// "parameters": {
// "userKey": {
// "description": "The email or immutable id of the user",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "{userKey}/mail",
// "request": {
// "$ref": "MailItem"
// },
// "scopes": [
// "https://www.googleapis.com/auth/email.migration"
// ],
// "supportsMediaUpload": true
// }
}

View File

@ -0,0 +1,728 @@
{
"kind": "discovery#restDescription",
"etag": "\"kEk3sFj6Ef5_yR1-H3bAO6qw9mI/WhvzCm5J5nAWPdnVXhGkrRz8-Wc\"",
"discoveryVersion": "v1",
"id": "admin:reports_v1",
"name": "admin",
"canonicalName": "reports",
"version": "reports_v1",
"title": "Admin Reports API",
"description": "Allows the administrators of Google Apps customers to fetch reports about the usage, collaboration, security and risk for their users.",
"ownerDomain": "google.com",
"ownerName": "Google",
"packagePath": "admin",
"icons": {
"x16": "http://www.google.com/images/icons/product/search-16.gif",
"x32": "http://www.google.com/images/icons/product/search-32.gif"
},
"documentationLink": "https://developers.google.com/admin-sdk/reports/",
"protocol": "rest",
"baseUrl": "https://www.googleapis.com/admin/reports/v1/",
"basePath": "/admin/reports/v1/",
"rootUrl": "https://www.googleapis.com/",
"servicePath": "admin/reports/v1/",
"batchPath": "batch",
"parameters": {
"alt": {
"type": "string",
"description": "Data format for the response.",
"default": "json",
"enum": [
"json"
],
"enumDescriptions": [
"Responses with Content-Type of application/json"
],
"location": "query"
},
"fields": {
"type": "string",
"description": "Selector specifying which fields to include in a partial response.",
"location": "query"
},
"key": {
"type": "string",
"description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.",
"location": "query"
},
"oauth_token": {
"type": "string",
"description": "OAuth 2.0 token for the current user.",
"location": "query"
},
"prettyPrint": {
"type": "boolean",
"description": "Returns response with indentations and line breaks.",
"default": "true",
"location": "query"
},
"quotaUser": {
"type": "string",
"description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.",
"location": "query"
},
"userIp": {
"type": "string",
"description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.",
"location": "query"
}
},
"auth": {
"oauth2": {
"scopes": {
"https://www.googleapis.com/auth/admin.reports.audit.readonly": {
"description": "View audit reports of Google Apps for your domain"
},
"https://www.googleapis.com/auth/admin.reports.usage.readonly": {
"description": "View usage reports of Google Apps for your domain"
}
}
}
},
"schemas": {
"Activities": {
"id": "Activities",
"type": "object",
"description": "JSON template for a collection of activites.",
"properties": {
"etag": {
"type": "string",
"description": "ETag of the resource."
},
"items": {
"type": "array",
"description": "Each record in read response.",
"items": {
"$ref": "Activity"
}
},
"kind": {
"type": "string",
"description": "Kind of list response this is.",
"default": "admin#reports#activities"
},
"nextPageToken": {
"type": "string",
"description": "Token for retrieving the next page"
}
}
},
"Activity": {
"id": "Activity",
"type": "object",
"description": "JSON template for the activity resource.",
"properties": {
"actor": {
"type": "object",
"description": "User doing the action.",
"properties": {
"callerType": {
"type": "string",
"description": "User or OAuth 2LO request."
},
"email": {
"type": "string",
"description": "Email address of the user."
},
"key": {
"type": "string",
"description": "For OAuth 2LO API requests, consumer_key of the requestor."
},
"profileId": {
"type": "string",
"description": "Obfuscated user id of the user."
}
}
},
"etag": {
"type": "string",
"description": "ETag of the entry."
},
"events": {
"type": "array",
"description": "Activity events.",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Name of event."
},
"parameters": {
"type": "array",
"description": "Parameter value pairs for various applications.",
"items": {
"type": "object",
"properties": {
"boolValue": {
"type": "boolean",
"description": "Boolean value of the parameter."
},
"intValue": {
"type": "string",
"description": "Integral value of the parameter.",
"format": "int64"
},
"name": {
"type": "string",
"description": "The name of the parameter."
},
"value": {
"type": "string",
"description": "String value of the parameter."
}
}
}
},
"type": {
"type": "string",
"description": "Type of event."
}
}
}
},
"id": {
"type": "object",
"description": "Unique identifier for each activity record.",
"properties": {
"applicationName": {
"type": "string",
"description": "Application name to which the event belongs."
},
"customerId": {
"type": "string",
"description": "Obfuscated customer ID of the source customer."
},
"time": {
"type": "string",
"description": "Time of occurrence of the activity.",
"format": "date-time"
},
"uniqueQualifier": {
"type": "string",
"description": "Unique qualifier if multiple events have the same time.",
"format": "int64"
}
}
},
"ipAddress": {
"type": "string",
"description": "IP Address of the user doing the action."
},
"kind": {
"type": "string",
"description": "Kind of resource this is.",
"default": "admin#reports#activity"
},
"ownerDomain": {
"type": "string",
"description": "Domain of source customer."
}
}
},
"Channel": {
"id": "Channel",
"type": "object",
"description": "An notification channel used to watch for resource changes.",
"properties": {
"address": {
"type": "string",
"description": "The address where notifications are delivered for this channel."
},
"expiration": {
"type": "string",
"description": "Date and time of notification channel expiration, expressed as a Unix timestamp, in milliseconds. Optional.",
"format": "int64"
},
"id": {
"type": "string",
"description": "A UUID or similar unique string that identifies this channel."
},
"kind": {
"type": "string",
"description": "Identifies this as a notification channel used to watch for changes to a resource. Value: the fixed string \"api#channel\".",
"default": "api#channel"
},
"params": {
"type": "object",
"description": "Additional parameters controlling delivery channel behavior. Optional.",
"additionalProperties": {
"type": "string",
"description": "Declares a new parameter by name."
}
},
"payload": {
"type": "boolean",
"description": "A Boolean value to indicate whether payload is wanted. Optional."
},
"resourceId": {
"type": "string",
"description": "An opaque ID that identifies the resource being watched on this channel. Stable across different API versions."
},
"resourceUri": {
"type": "string",
"description": "A version-specific identifier for the watched resource."
},
"token": {
"type": "string",
"description": "An arbitrary string delivered to the target address with each notification delivered over this channel. Optional."
},
"type": {
"type": "string",
"description": "The type of delivery mechanism used for this channel."
}
}
},
"UsageReport": {
"id": "UsageReport",
"type": "object",
"description": "JSON template for a usage report.",
"properties": {
"date": {
"type": "string",
"description": "The date to which the record belongs.",
"readOnly": true
},
"entity": {
"type": "object",
"description": "Information about the type of the item.",
"readOnly": true,
"properties": {
"customerId": {
"type": "string",
"description": "Obfuscated customer id for the record.",
"readOnly": true
},
"profileId": {
"type": "string",
"description": "Obfuscated user id for the record.",
"readOnly": true
},
"type": {
"type": "string",
"description": "The type of item, can be a customer or user.",
"readOnly": true
},
"userEmail": {
"type": "string",
"description": "user's email.",
"readOnly": true
}
}
},
"etag": {
"type": "string",
"description": "ETag of the resource."
},
"kind": {
"type": "string",
"description": "The kind of object.",
"default": "admin#reports#usageReport"
},
"parameters": {
"type": "array",
"description": "Parameter value pairs for various applications.",
"readOnly": true,
"items": {
"type": "object",
"properties": {
"boolValue": {
"type": "boolean",
"description": "Boolean value of the parameter.",
"readOnly": true
},
"datetimeValue": {
"type": "string",
"description": "RFC 3339 formatted value of the parameter.",
"format": "date-time",
"readOnly": true
},
"intValue": {
"type": "string",
"description": "Integral value of the parameter.",
"format": "int64",
"readOnly": true
},
"msgValue": {
"type": "array",
"description": "Nested message value of the parameter.",
"readOnly": true,
"items": {
"type": "object",
"additionalProperties": {
"type": "any"
}
}
},
"name": {
"type": "string",
"description": "The name of the parameter."
},
"stringValue": {
"type": "string",
"description": "String value of the parameter.",
"readOnly": true
}
}
}
}
}
},
"UsageReports": {
"id": "UsageReports",
"type": "object",
"description": "JSON template for a collection of usage reports.",
"properties": {
"etag": {
"type": "string",
"description": "ETag of the resource."
},
"kind": {
"type": "string",
"description": "The kind of object.",
"default": "admin#reports#usageReports"
},
"nextPageToken": {
"type": "string",
"description": "Token for retrieving the next page"
},
"usageReports": {
"type": "array",
"description": "Various application parameter records.",
"items": {
"$ref": "UsageReport"
}
},
"warnings": {
"type": "array",
"description": "Warnings if any.",
"items": {
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "Machine readable code / warning type."
},
"data": {
"type": "array",
"description": "Key-Value pairs to give detailed information on the warning.",
"items": {
"type": "object",
"properties": {
"key": {
"type": "string",
"description": "Key associated with a key-value pair to give detailed information on the warning."
},
"value": {
"type": "string",
"description": "Value associated with a key-value pair to give detailed information on the warning."
}
}
}
},
"message": {
"type": "string",
"description": "Human readable message for the warning."
}
}
}
}
}
}
},
"resources": {
"activities": {
"methods": {
"list": {
"id": "reports.activities.list",
"path": "activity/users/{userKey}/applications/{applicationName}",
"httpMethod": "GET",
"description": "Retrieves a list of activities for a specific customer and application.",
"parameters": {
"actorIpAddress": {
"type": "string",
"description": "IP Address of host where the event was performed. Supports both IPv4 and IPv6 addresses.",
"location": "query"
},
"applicationName": {
"type": "string",
"description": "Application name for which the events are to be retrieved.",
"required": true,
"pattern": "(admin)|(docs)|(login)",
"location": "path"
},
"customerId": {
"type": "string",
"description": "Represents the customer for which the data is to be fetched.",
"pattern": "C.+",
"location": "query"
},
"endTime": {
"type": "string",
"description": "Return events which occured at or before this time.",
"pattern": "(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)T(\\d\\d):(\\d\\d):(\\d\\d)(?:\\.(\\d+))?(?:(Z)|([-+])(\\d\\d):(\\d\\d))",
"location": "query"
},
"eventName": {
"type": "string",
"description": "Name of the event being queried.",
"location": "query"
},
"filters": {
"type": "string",
"description": "Event parameters in the form [parameter1 name][operator][parameter1 value],[parameter2 name][operator][parameter2 value],...",
"pattern": "(.+[\u003c,\u003c=,==,\u003e=,\u003e,\u003c\u003e].+,)*(.+[\u003c,\u003c=,==,\u003e=,\u003e,\u003c\u003e].+)",
"location": "query"
},
"maxResults": {
"type": "integer",
"description": "Number of activity records to be shown in each page.",
"format": "int32",
"minimum": "1",
"maximum": "1000",
"location": "query"
},
"pageToken": {
"type": "string",
"description": "Token to specify next page.",
"location": "query"
},
"startTime": {
"type": "string",
"description": "Return events which occured at or after this time.",
"pattern": "(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)T(\\d\\d):(\\d\\d):(\\d\\d)(?:\\.(\\d+))?(?:(Z)|([-+])(\\d\\d):(\\d\\d))",
"location": "query"
},
"userKey": {
"type": "string",
"description": "Represents the profile id or the user email for which the data should be filtered. When 'all' is specified as the userKey, it returns usageReports for all users.",
"required": true,
"location": "path"
}
},
"parameterOrder": [
"userKey",
"applicationName"
],
"response": {
"$ref": "Activities"
},
"scopes": [
"https://www.googleapis.com/auth/admin.reports.audit.readonly"
],
"supportsSubscription": true
},
"watch": {
"id": "reports.activities.watch",
"path": "activity/users/{userKey}/applications/{applicationName}/watch",
"httpMethod": "POST",
"description": "Push changes to activities",
"parameters": {
"actorIpAddress": {
"type": "string",
"description": "IP Address of host where the event was performed. Supports both IPv4 and IPv6 addresses.",
"location": "query"
},
"applicationName": {
"type": "string",
"description": "Application name for which the events are to be retrieved.",
"required": true,
"pattern": "(admin)|(docs)|(login)",
"location": "path"
},
"customerId": {
"type": "string",
"description": "Represents the customer for which the data is to be fetched.",
"pattern": "C.+",
"location": "query"
},
"endTime": {
"type": "string",
"description": "Return events which occured at or before this time.",
"pattern": "(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)T(\\d\\d):(\\d\\d):(\\d\\d)(?:\\.(\\d+))?(?:(Z)|([-+])(\\d\\d):(\\d\\d))",
"location": "query"
},
"eventName": {
"type": "string",
"description": "Name of the event being queried.",
"location": "query"
},
"filters": {
"type": "string",
"description": "Event parameters in the form [parameter1 name][operator][parameter1 value],[parameter2 name][operator][parameter2 value],...",
"pattern": "(.+[\u003c,\u003c=,==,\u003e=,\u003e,\u003c\u003e].+,)*(.+[\u003c,\u003c=,==,\u003e=,\u003e,\u003c\u003e].+)",
"location": "query"
},
"maxResults": {
"type": "integer",
"description": "Number of activity records to be shown in each page.",
"format": "int32",
"minimum": "1",
"maximum": "1000",
"location": "query"
},
"pageToken": {
"type": "string",
"description": "Token to specify next page.",
"location": "query"
},
"startTime": {
"type": "string",
"description": "Return events which occured at or after this time.",
"pattern": "(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)T(\\d\\d):(\\d\\d):(\\d\\d)(?:\\.(\\d+))?(?:(Z)|([-+])(\\d\\d):(\\d\\d))",
"location": "query"
},
"userKey": {
"type": "string",
"description": "Represents the profile id or the user email for which the data should be filtered. When 'all' is specified as the userKey, it returns usageReports for all users.",
"required": true,
"location": "path"
}
},
"parameterOrder": [
"userKey",
"applicationName"
],
"request": {
"$ref": "Channel",
"parameterName": "resource"
},
"response": {
"$ref": "Channel"
},
"scopes": [
"https://www.googleapis.com/auth/admin.reports.audit.readonly"
],
"supportsSubscription": true
}
}
},
"channels": {
"methods": {
"stop": {
"id": "admin.channels.stop",
"path": "/admin/reports_v1/channels/stop",
"httpMethod": "POST",
"description": "Stop watching resources through this channel",
"request": {
"$ref": "Channel",
"parameterName": "resource"
},
"scopes": [
"https://www.googleapis.com/auth/admin.reports.audit.readonly"
]
}
}
},
"customerUsageReports": {
"methods": {
"get": {
"id": "reports.customerUsageReports.get",
"path": "usage/dates/{date}",
"httpMethod": "GET",
"description": "Retrieves a report which is a collection of properties / statistics for a specific customer.",
"parameters": {
"customerId": {
"type": "string",
"description": "Represents the customer for which the data is to be fetched.",
"pattern": "C.+",
"location": "query"
},
"date": {
"type": "string",
"description": "Represents the date in yyyy-mm-dd format for which the data is to be fetched.",
"required": true,
"pattern": "(\\d){4}-(\\d){2}-(\\d){2}",
"location": "path"
},
"pageToken": {
"type": "string",
"description": "Token to specify next page.",
"location": "query"
},
"parameters": {
"type": "string",
"description": "Represents the application name, parameter name pairs to fetch in csv as app_name1:param_name1, app_name2:param_name2.",
"pattern": "(((accounts)|(gmail)|(calendar)|(docs)|(gplus)):.+,)*(((accounts)|(gmail)|(calendar)|(docs)|(gplus)):.+)",
"location": "query"
}
},
"parameterOrder": [
"date"
],
"response": {
"$ref": "UsageReports"
},
"scopes": [
"https://www.googleapis.com/auth/admin.reports.usage.readonly"
]
}
}
},
"userUsageReport": {
"methods": {
"get": {
"id": "reports.userUsageReport.get",
"path": "usage/users/{userKey}/dates/{date}",
"httpMethod": "GET",
"description": "Retrieves a report which is a collection of properties / statistics for a set of users.",
"parameters": {
"customerId": {
"type": "string",
"description": "Represents the customer for which the data is to be fetched.",
"pattern": "C.+",
"location": "query"
},
"date": {
"type": "string",
"description": "Represents the date in yyyy-mm-dd format for which the data is to be fetched.",
"required": true,
"pattern": "(\\d){4}-(\\d){2}-(\\d){2}",
"location": "path"
},
"filters": {
"type": "string",
"description": "Represents the set of filters including parameter operator value.",
"pattern": "(((accounts)|(gmail)|(calendar)|(docs)|(gplus)):.+[\u003c,\u003c=,==,\u003e=,\u003e,!=].+,)*(((accounts)|(gmail)|(calendar)|(docs)|(gplus)):.+[\u003c,\u003c=,==,\u003e=,\u003e,!=].+)",
"location": "query"
},
"maxResults": {
"type": "integer",
"description": "Maximum number of results to return. Maximum allowed is 1000",
"format": "uint32",
"maximum": "1000",
"location": "query"
},
"pageToken": {
"type": "string",
"description": "Token to specify next page.",
"location": "query"
},
"parameters": {
"type": "string",
"description": "Represents the application name, parameter name pairs to fetch in csv as app_name1:param_name1, app_name2:param_name2.",
"pattern": "(((accounts)|(gmail)|(calendar)|(docs)|(gplus)):.+,)*(((accounts)|(gmail)|(calendar)|(docs)|(gplus)):.+)",
"location": "query"
},
"userKey": {
"type": "string",
"description": "Represents the profile id or the user email for which the data should be filtered.",
"required": true,
"location": "path"
}
},
"parameterOrder": [
"userKey",
"date"
],
"response": {
"$ref": "UsageReports"
},
"scopes": [
"https://www.googleapis.com/auth/admin.reports.usage.readonly"
]
}
}
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,605 @@
{
"kind": "discovery#restDescription",
"etag": "\"BgGnx7p-6wsAbOn4St99QhtBGbA/dDvqGV6BmrzgyC9htm-_zFD2_ME\"",
"discoveryVersion": "v1",
"id": "adsense:v1",
"name": "adsense",
"canonicalName": "AdSense",
"version": "v1",
"revision": "20130712",
"title": "AdSense Management API",
"description": "Gives AdSense publishers access to their inventory and the ability to generate reports",
"ownerDomain": "google.com",
"ownerName": "Google",
"icons": {
"x16": "http://www.google.com/images/icons/product/adsense-16.png",
"x32": "http://www.google.com/images/icons/product/adsense-32.png"
},
"documentationLink": "https://developers.google.com/adsense/management/",
"protocol": "rest",
"baseUrl": "https://www.googleapis.com/adsense/v1/",
"basePath": "/adsense/v1/",
"rootUrl": "https://www.googleapis.com/",
"servicePath": "adsense/v1/",
"batchPath": "batch",
"parameters": {
"alt": {
"type": "string",
"description": "Data format for the response.",
"default": "json",
"enum": [
"csv",
"json"
],
"enumDescriptions": [
"Responses with Content-Type of text/csv",
"Responses with Content-Type of application/json"
],
"location": "query"
},
"fields": {
"type": "string",
"description": "Selector specifying which fields to include in a partial response.",
"location": "query"
},
"key": {
"type": "string",
"description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.",
"location": "query"
},
"oauth_token": {
"type": "string",
"description": "OAuth 2.0 token for the current user.",
"location": "query"
},
"prettyPrint": {
"type": "boolean",
"description": "Returns response with indentations and line breaks.",
"default": "true",
"location": "query"
},
"quotaUser": {
"type": "string",
"description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.",
"location": "query"
},
"userIp": {
"type": "string",
"description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.",
"location": "query"
}
},
"auth": {
"oauth2": {
"scopes": {
"https://www.googleapis.com/auth/adsense": {
"description": "View and manage your AdSense data"
},
"https://www.googleapis.com/auth/adsense.readonly": {
"description": "View your AdSense data"
}
}
}
},
"schemas": {
"AdClient": {
"id": "AdClient",
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "Unique identifier of this ad client."
},
"kind": {
"type": "string",
"description": "Kind of resource this is, in this case adsense#adClient.",
"default": "adsense#adClient"
},
"productCode": {
"type": "string",
"description": "This ad client's product code, which corresponds to the PRODUCT_CODE report dimension."
},
"supportsReporting": {
"type": "boolean",
"description": "Whether this ad client supports being reported on."
}
}
},
"AdClients": {
"id": "AdClients",
"type": "object",
"properties": {
"etag": {
"type": "string",
"description": "ETag of this response for caching purposes."
},
"items": {
"type": "array",
"description": "The ad clients returned in this list response.",
"items": {
"$ref": "AdClient"
}
},
"kind": {
"type": "string",
"description": "Kind of list this is, in this case adsense#adClients.",
"default": "adsense#adClients"
},
"nextPageToken": {
"type": "string",
"description": "Continuation token used to page through ad clients. To retrieve the next page of results, set the next request's \"pageToken\" value to this."
}
}
},
"AdUnit": {
"id": "AdUnit",
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "Identity code of this ad unit, not necessarily unique across ad clients."
},
"id": {
"type": "string",
"description": "Unique identifier of this ad unit. This should be considered an opaque identifier; it is not safe to rely on it being in any particular format."
},
"kind": {
"type": "string",
"description": "Kind of resource this is, in this case adsense#adUnit.",
"default": "adsense#adUnit"
},
"name": {
"type": "string",
"description": "Name of this ad unit."
},
"status": {
"type": "string",
"description": "Status of this ad unit. Possible values are:\nNEW: Indicates that the ad unit was created within the last seven days and does not yet have any activity associated with it.\n\nACTIVE: Indicates that there has been activity on this ad unit in the last seven days.\n\nINACTIVE: Indicates that there has been no activity on this ad unit in the last seven days."
}
}
},
"AdUnits": {
"id": "AdUnits",
"type": "object",
"properties": {
"etag": {
"type": "string",
"description": "ETag of this response for caching purposes."
},
"items": {
"type": "array",
"description": "The ad units returned in this list response.",
"items": {
"$ref": "AdUnit"
}
},
"kind": {
"type": "string",
"description": "Kind of list this is, in this case adsense#adUnits.",
"default": "adsense#adUnits"
},
"nextPageToken": {
"type": "string",
"description": "Continuation token used to page through ad units. To retrieve the next page of results, set the next request's \"pageToken\" value to this."
}
}
},
"AdsenseReportsGenerateResponse": {
"id": "AdsenseReportsGenerateResponse",
"type": "object",
"properties": {
"averages": {
"type": "array",
"description": "The averages of the report. This is the same length as any other row in the report; cells corresponding to dimension columns are empty.",
"items": {
"type": "string"
}
},
"headers": {
"type": "array",
"description": "The header information of the columns requested in the report. This is a list of headers; one for each dimension in the request, followed by one for each metric in the request.",
"items": {
"type": "object",
"properties": {
"currency": {
"type": "string",
"description": "The currency of this column. Only present if the header type is METRIC_CURRENCY."
},
"name": {
"type": "string",
"description": "The name of the header."
},
"type": {
"type": "string",
"description": "The type of the header; one of DIMENSION, METRIC_TALLY, METRIC_RATIO, or METRIC_CURRENCY."
}
}
}
},
"kind": {
"type": "string",
"description": "Kind this is, in this case adsense#report.",
"default": "adsense#report"
},
"rows": {
"type": "array",
"description": "The output rows of the report. Each row is a list of cells; one for each dimension in the request, followed by one for each metric in the request. The dimension cells contain strings, and the metric cells contain numbers.",
"items": {
"type": "array",
"items": {
"type": "string"
}
}
},
"totalMatchedRows": {
"type": "string",
"description": "The total number of rows matched by the report request. Fewer rows may be returned in the response due to being limited by the row count requested or the report row limit.",
"format": "int64"
},
"totals": {
"type": "array",
"description": "The totals of the report. This is the same length as any other row in the report; cells corresponding to dimension columns are empty.",
"items": {
"type": "string"
}
},
"warnings": {
"type": "array",
"description": "Any warnings associated with generation of the report.",
"items": {
"type": "string"
}
}
}
},
"CustomChannel": {
"id": "CustomChannel",
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "Code of this custom channel, not necessarily unique across ad clients."
},
"id": {
"type": "string",
"description": "Unique identifier of this custom channel. This should be considered an opaque identifier; it is not safe to rely on it being in any particular format."
},
"kind": {
"type": "string",
"description": "Kind of resource this is, in this case adsense#customChannel.",
"default": "adsense#customChannel"
},
"name": {
"type": "string",
"description": "Name of this custom channel."
}
}
},
"CustomChannels": {
"id": "CustomChannels",
"type": "object",
"properties": {
"etag": {
"type": "string",
"description": "ETag of this response for caching purposes."
},
"items": {
"type": "array",
"description": "The custom channels returned in this list response.",
"items": {
"$ref": "CustomChannel"
}
},
"kind": {
"type": "string",
"description": "Kind of list this is, in this case adsense#customChannels.",
"default": "adsense#customChannels"
},
"nextPageToken": {
"type": "string",
"description": "Continuation token used to page through custom channels. To retrieve the next page of results, set the next request's \"pageToken\" value to this."
}
}
},
"UrlChannel": {
"id": "UrlChannel",
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "Unique identifier of this URL channel. This should be considered an opaque identifier; it is not safe to rely on it being in any particular format."
},
"kind": {
"type": "string",
"description": "Kind of resource this is, in this case adsense#urlChannel.",
"default": "adsense#urlChannel"
},
"urlPattern": {
"type": "string",
"description": "URL Pattern of this URL channel. Does not include \"http://\" or \"https://\". Example: www.example.com/home"
}
}
},
"UrlChannels": {
"id": "UrlChannels",
"type": "object",
"properties": {
"etag": {
"type": "string",
"description": "ETag of this response for caching purposes."
},
"items": {
"type": "array",
"description": "The URL channels returned in this list response.",
"items": {
"$ref": "UrlChannel"
}
},
"kind": {
"type": "string",
"description": "Kind of list this is, in this case adsense#urlChannels.",
"default": "adsense#urlChannels"
},
"nextPageToken": {
"type": "string",
"description": "Continuation token used to page through URL channels. To retrieve the next page of results, set the next request's \"pageToken\" value to this."
}
}
}
},
"resources": {
"adclients": {
"methods": {
"list": {
"id": "adsense.adclients.list",
"path": "adclients",
"httpMethod": "GET",
"description": "List all ad clients in this AdSense account.",
"parameters": {
"maxResults": {
"type": "integer",
"description": "The maximum number of ad clients to include in the response, used for paging.",
"format": "int32",
"minimum": "0",
"maximum": "10000",
"location": "query"
},
"pageToken": {
"type": "string",
"description": "A continuation token, used to page through ad clients. To retrieve the next page, set this parameter to the value of \"nextPageToken\" from the previous response.",
"location": "query"
}
},
"response": {
"$ref": "AdClients"
},
"scopes": [
"https://www.googleapis.com/auth/adsense",
"https://www.googleapis.com/auth/adsense.readonly"
]
}
}
},
"adunits": {
"methods": {
"list": {
"id": "adsense.adunits.list",
"path": "adclients/{adClientId}/adunits",
"httpMethod": "GET",
"description": "List all ad units in the specified ad client for this AdSense account.",
"parameters": {
"adClientId": {
"type": "string",
"description": "Ad client for which to list ad units.",
"required": true,
"location": "path"
},
"includeInactive": {
"type": "boolean",
"description": "Whether to include inactive ad units. Default: true.",
"location": "query"
},
"maxResults": {
"type": "integer",
"description": "The maximum number of ad units to include in the response, used for paging.",
"format": "int32",
"minimum": "0",
"maximum": "10000",
"location": "query"
},
"pageToken": {
"type": "string",
"description": "A continuation token, used to page through ad units. To retrieve the next page, set this parameter to the value of \"nextPageToken\" from the previous response.",
"location": "query"
}
},
"parameterOrder": [
"adClientId"
],
"response": {
"$ref": "AdUnits"
},
"scopes": [
"https://www.googleapis.com/auth/adsense",
"https://www.googleapis.com/auth/adsense.readonly"
]
}
}
},
"customchannels": {
"methods": {
"list": {
"id": "adsense.customchannels.list",
"path": "adclients/{adClientId}/customchannels",
"httpMethod": "GET",
"description": "List all custom channels in the specified ad client for this AdSense account.",
"parameters": {
"adClientId": {
"type": "string",
"description": "Ad client for which to list custom channels.",
"required": true,
"location": "path"
},
"maxResults": {
"type": "integer",
"description": "The maximum number of custom channels to include in the response, used for paging.",
"format": "int32",
"minimum": "0",
"maximum": "10000",
"location": "query"
},
"pageToken": {
"type": "string",
"description": "A continuation token, used to page through custom channels. To retrieve the next page, set this parameter to the value of \"nextPageToken\" from the previous response.",
"location": "query"
}
},
"parameterOrder": [
"adClientId"
],
"response": {
"$ref": "CustomChannels"
},
"scopes": [
"https://www.googleapis.com/auth/adsense",
"https://www.googleapis.com/auth/adsense.readonly"
]
}
}
},
"reports": {
"methods": {
"generate": {
"id": "adsense.reports.generate",
"path": "reports",
"httpMethod": "GET",
"description": "Generate an AdSense report based on the report request sent in the query parameters. Returns the result as JSON; to retrieve output in CSV format specify \"alt=csv\" as a query parameter.",
"parameters": {
"currency": {
"type": "string",
"description": "Optional currency to use when reporting on monetary metrics. Defaults to the account's currency if not set.",
"pattern": "[a-zA-Z]+",
"location": "query"
},
"dimension": {
"type": "string",
"description": "Dimensions to base the report on.",
"pattern": "[a-zA-Z_]+",
"repeated": true,
"location": "query"
},
"endDate": {
"type": "string",
"description": "End of the date range to report on in \"YYYY-MM-DD\" format, inclusive.",
"required": true,
"pattern": "\\d{4}-\\d{2}-\\d{2}|(today|startOfMonth|startOfYear)(([\\-\\+]\\d+[dwmy]){0,2}?)",
"location": "query"
},
"filter": {
"type": "string",
"description": "Filters to be run on the report.",
"pattern": "[a-zA-Z_]+(==|=@).+",
"repeated": true,
"location": "query"
},
"locale": {
"type": "string",
"description": "Optional locale to use for translating report output to a local language. Defaults to \"en_US\" if not specified.",
"pattern": "[a-zA-Z_]+",
"location": "query"
},
"maxResults": {
"type": "integer",
"description": "The maximum number of rows of report data to return.",
"format": "int32",
"minimum": "0",
"maximum": "50000",
"location": "query"
},
"metric": {
"type": "string",
"description": "Numeric columns to include in the report.",
"pattern": "[a-zA-Z_]+",
"repeated": true,
"location": "query"
},
"sort": {
"type": "string",
"description": "The name of a dimension or metric to sort the resulting report on, optionally prefixed with \"+\" to sort ascending or \"-\" to sort descending. If no prefix is specified, the column is sorted ascending.",
"pattern": "(\\+|-)?[a-zA-Z_]+",
"repeated": true,
"location": "query"
},
"startDate": {
"type": "string",
"description": "Start of the date range to report on in \"YYYY-MM-DD\" format, inclusive.",
"required": true,
"pattern": "\\d{4}-\\d{2}-\\d{2}|(today|startOfMonth|startOfYear)(([\\-\\+]\\d+[dwmy]){0,2}?)",
"location": "query"
},
"startIndex": {
"type": "integer",
"description": "Index of the first row of report data to return.",
"format": "int32",
"minimum": "0",
"maximum": "5000",
"location": "query"
}
},
"parameterOrder": [
"startDate",
"endDate"
],
"response": {
"$ref": "AdsenseReportsGenerateResponse"
},
"scopes": [
"https://www.googleapis.com/auth/adsense",
"https://www.googleapis.com/auth/adsense.readonly"
]
}
}
},
"urlchannels": {
"methods": {
"list": {
"id": "adsense.urlchannels.list",
"path": "adclients/{adClientId}/urlchannels",
"httpMethod": "GET",
"description": "List all URL channels in the specified ad client for this AdSense account.",
"parameters": {
"adClientId": {
"type": "string",
"description": "Ad client for which to list URL channels.",
"required": true,
"location": "path"
},
"maxResults": {
"type": "integer",
"description": "The maximum number of URL channels to include in the response, used for paging.",
"format": "int32",
"minimum": "0",
"maximum": "10000",
"location": "query"
},
"pageToken": {
"type": "string",
"description": "A continuation token, used to page through URL channels. To retrieve the next page, set this parameter to the value of \"nextPageToken\" from the previous response.",
"location": "query"
}
},
"parameterOrder": [
"adClientId"
],
"response": {
"$ref": "UrlChannels"
},
"scopes": [
"https://www.googleapis.com/auth/adsense",
"https://www.googleapis.com/auth/adsense.readonly"
]
}
}
}
}
}

View File

@ -0,0 +1,934 @@
// Package adsense provides access to the AdSense Management API.
//
// See https://developers.google.com/adsense/management/
//
// Usage example:
//
// import "code.google.com/p/google-api-go-client/adsense/v1"
// ...
// adsenseService, err := adsense.New(oauthHttpClient)
package adsense
import (
"bytes"
"code.google.com/p/google-api-go-client/googleapi"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
)
// Always reference these packages, just in case the auto-generated code
// below doesn't.
var _ = bytes.NewBuffer
var _ = strconv.Itoa
var _ = fmt.Sprintf
var _ = json.NewDecoder
var _ = io.Copy
var _ = url.Parse
var _ = googleapi.Version
var _ = errors.New
var _ = strings.Replace
const apiId = "adsense:v1"
const apiName = "adsense"
const apiVersion = "v1"
const basePath = "https://www.googleapis.com/adsense/v1/"
// OAuth2 scopes used by this API.
const (
// View and manage your AdSense data
AdsenseScope = "https://www.googleapis.com/auth/adsense"
// View your AdSense data
AdsenseReadonlyScope = "https://www.googleapis.com/auth/adsense.readonly"
)
func New(client *http.Client) (*Service, error) {
if client == nil {
return nil, errors.New("client is nil")
}
s := &Service{client: client}
s.Adclients = NewAdclientsService(s)
s.Adunits = NewAdunitsService(s)
s.Customchannels = NewCustomchannelsService(s)
s.Reports = NewReportsService(s)
s.Urlchannels = NewUrlchannelsService(s)
return s, nil
}
type Service struct {
client *http.Client
Adclients *AdclientsService
Adunits *AdunitsService
Customchannels *CustomchannelsService
Reports *ReportsService
Urlchannels *UrlchannelsService
}
func NewAdclientsService(s *Service) *AdclientsService {
rs := &AdclientsService{s: s}
return rs
}
type AdclientsService struct {
s *Service
}
func NewAdunitsService(s *Service) *AdunitsService {
rs := &AdunitsService{s: s}
return rs
}
type AdunitsService struct {
s *Service
}
func NewCustomchannelsService(s *Service) *CustomchannelsService {
rs := &CustomchannelsService{s: s}
return rs
}
type CustomchannelsService struct {
s *Service
}
func NewReportsService(s *Service) *ReportsService {
rs := &ReportsService{s: s}
return rs
}
type ReportsService struct {
s *Service
}
func NewUrlchannelsService(s *Service) *UrlchannelsService {
rs := &UrlchannelsService{s: s}
return rs
}
type UrlchannelsService struct {
s *Service
}
type AdClient struct {
// Id: Unique identifier of this ad client.
Id string `json:"id,omitempty"`
// Kind: Kind of resource this is, in this case adsense#adClient.
Kind string `json:"kind,omitempty"`
// ProductCode: This ad client's product code, which corresponds to the
// PRODUCT_CODE report dimension.
ProductCode string `json:"productCode,omitempty"`
// SupportsReporting: Whether this ad client supports being reported on.
SupportsReporting bool `json:"supportsReporting,omitempty"`
}
type AdClients struct {
// Etag: ETag of this response for caching purposes.
Etag string `json:"etag,omitempty"`
// Items: The ad clients returned in this list response.
Items []*AdClient `json:"items,omitempty"`
// Kind: Kind of list this is, in this case adsense#adClients.
Kind string `json:"kind,omitempty"`
// NextPageToken: Continuation token used to page through ad clients. To
// retrieve the next page of results, set the next request's "pageToken"
// value to this.
NextPageToken string `json:"nextPageToken,omitempty"`
}
type AdUnit struct {
// Code: Identity code of this ad unit, not necessarily unique across ad
// clients.
Code string `json:"code,omitempty"`
// Id: Unique identifier of this ad unit. This should be considered an
// opaque identifier; it is not safe to rely on it being in any
// particular format.
Id string `json:"id,omitempty"`
// Kind: Kind of resource this is, in this case adsense#adUnit.
Kind string `json:"kind,omitempty"`
// Name: Name of this ad unit.
Name string `json:"name,omitempty"`
// Status: Status of this ad unit. Possible values are:
// NEW: Indicates
// that the ad unit was created within the last seven days and does not
// yet have any activity associated with it.
//
// ACTIVE: Indicates that
// there has been activity on this ad unit in the last seven
// days.
//
// INACTIVE: Indicates that there has been no activity on this ad
// unit in the last seven days.
Status string `json:"status,omitempty"`
}
type AdUnits struct {
// Etag: ETag of this response for caching purposes.
Etag string `json:"etag,omitempty"`
// Items: The ad units returned in this list response.
Items []*AdUnit `json:"items,omitempty"`
// Kind: Kind of list this is, in this case adsense#adUnits.
Kind string `json:"kind,omitempty"`
// NextPageToken: Continuation token used to page through ad units. To
// retrieve the next page of results, set the next request's "pageToken"
// value to this.
NextPageToken string `json:"nextPageToken,omitempty"`
}
type AdsenseReportsGenerateResponse struct {
// Averages: The averages of the report. This is the same length as any
// other row in the report; cells corresponding to dimension columns are
// empty.
Averages []string `json:"averages,omitempty"`
// Headers: The header information of the columns requested in the
// report. This is a list of headers; one for each dimension in the
// request, followed by one for each metric in the request.
Headers []*AdsenseReportsGenerateResponseHeaders `json:"headers,omitempty"`
// Kind: Kind this is, in this case adsense#report.
Kind string `json:"kind,omitempty"`
// Rows: The output rows of the report. Each row is a list of cells; one
// for each dimension in the request, followed by one for each metric in
// the request. The dimension cells contain strings, and the metric
// cells contain numbers.
Rows [][]string `json:"rows,omitempty"`
// TotalMatchedRows: The total number of rows matched by the report
// request. Fewer rows may be returned in the response due to being
// limited by the row count requested or the report row limit.
TotalMatchedRows int64 `json:"totalMatchedRows,omitempty,string"`
// Totals: The totals of the report. This is the same length as any
// other row in the report; cells corresponding to dimension columns are
// empty.
Totals []string `json:"totals,omitempty"`
// Warnings: Any warnings associated with generation of the report.
Warnings []string `json:"warnings,omitempty"`
}
type AdsenseReportsGenerateResponseHeaders struct {
// Currency: The currency of this column. Only present if the header
// type is METRIC_CURRENCY.
Currency string `json:"currency,omitempty"`
// Name: The name of the header.
Name string `json:"name,omitempty"`
// Type: The type of the header; one of DIMENSION, METRIC_TALLY,
// METRIC_RATIO, or METRIC_CURRENCY.
Type string `json:"type,omitempty"`
}
type CustomChannel struct {
// Code: Code of this custom channel, not necessarily unique across ad
// clients.
Code string `json:"code,omitempty"`
// Id: Unique identifier of this custom channel. This should be
// considered an opaque identifier; it is not safe to rely on it being
// in any particular format.
Id string `json:"id,omitempty"`
// Kind: Kind of resource this is, in this case adsense#customChannel.
Kind string `json:"kind,omitempty"`
// Name: Name of this custom channel.
Name string `json:"name,omitempty"`
}
type CustomChannels struct {
// Etag: ETag of this response for caching purposes.
Etag string `json:"etag,omitempty"`
// Items: The custom channels returned in this list response.
Items []*CustomChannel `json:"items,omitempty"`
// Kind: Kind of list this is, in this case adsense#customChannels.
Kind string `json:"kind,omitempty"`
// NextPageToken: Continuation token used to page through custom
// channels. To retrieve the next page of results, set the next
// request's "pageToken" value to this.
NextPageToken string `json:"nextPageToken,omitempty"`
}
type UrlChannel struct {
// Id: Unique identifier of this URL channel. This should be considered
// an opaque identifier; it is not safe to rely on it being in any
// particular format.
Id string `json:"id,omitempty"`
// Kind: Kind of resource this is, in this case adsense#urlChannel.
Kind string `json:"kind,omitempty"`
// UrlPattern: URL Pattern of this URL channel. Does not include
// "http://" or "https://". Example: www.example.com/home
UrlPattern string `json:"urlPattern,omitempty"`
}
type UrlChannels struct {
// Etag: ETag of this response for caching purposes.
Etag string `json:"etag,omitempty"`
// Items: The URL channels returned in this list response.
Items []*UrlChannel `json:"items,omitempty"`
// Kind: Kind of list this is, in this case adsense#urlChannels.
Kind string `json:"kind,omitempty"`
// NextPageToken: Continuation token used to page through URL channels.
// To retrieve the next page of results, set the next request's
// "pageToken" value to this.
NextPageToken string `json:"nextPageToken,omitempty"`
}
// method id "adsense.adclients.list":
type AdclientsListCall struct {
s *Service
opt_ map[string]interface{}
}
// List: List all ad clients in this AdSense account.
func (r *AdclientsService) List() *AdclientsListCall {
c := &AdclientsListCall{s: r.s, opt_: make(map[string]interface{})}
return c
}
// MaxResults sets the optional parameter "maxResults": The maximum
// number of ad clients to include in the response, used for paging.
func (c *AdclientsListCall) MaxResults(maxResults int64) *AdclientsListCall {
c.opt_["maxResults"] = maxResults
return c
}
// PageToken sets the optional parameter "pageToken": A continuation
// token, used to page through ad clients. To retrieve the next page,
// set this parameter to the value of "nextPageToken" from the previous
// response.
func (c *AdclientsListCall) PageToken(pageToken string) *AdclientsListCall {
c.opt_["pageToken"] = pageToken
return c
}
func (c *AdclientsListCall) Do() (*AdClients, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["maxResults"]; ok {
params.Set("maxResults", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["pageToken"]; ok {
params.Set("pageToken", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative("https://www.googleapis.com/adsense/v1/", "adclients")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(AdClients)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "List all ad clients in this AdSense account.",
// "httpMethod": "GET",
// "id": "adsense.adclients.list",
// "parameters": {
// "maxResults": {
// "description": "The maximum number of ad clients to include in the response, used for paging.",
// "format": "int32",
// "location": "query",
// "maximum": "10000",
// "minimum": "0",
// "type": "integer"
// },
// "pageToken": {
// "description": "A continuation token, used to page through ad clients. To retrieve the next page, set this parameter to the value of \"nextPageToken\" from the previous response.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "adclients",
// "response": {
// "$ref": "AdClients"
// },
// "scopes": [
// "https://www.googleapis.com/auth/adsense",
// "https://www.googleapis.com/auth/adsense.readonly"
// ]
// }
}
// method id "adsense.adunits.list":
type AdunitsListCall struct {
s *Service
adClientId string
opt_ map[string]interface{}
}
// List: List all ad units in the specified ad client for this AdSense
// account.
func (r *AdunitsService) List(adClientId string) *AdunitsListCall {
c := &AdunitsListCall{s: r.s, opt_: make(map[string]interface{})}
c.adClientId = adClientId
return c
}
// IncludeInactive sets the optional parameter "includeInactive":
// Whether to include inactive ad units. Default: true.
func (c *AdunitsListCall) IncludeInactive(includeInactive bool) *AdunitsListCall {
c.opt_["includeInactive"] = includeInactive
return c
}
// MaxResults sets the optional parameter "maxResults": The maximum
// number of ad units to include in the response, used for paging.
func (c *AdunitsListCall) MaxResults(maxResults int64) *AdunitsListCall {
c.opt_["maxResults"] = maxResults
return c
}
// PageToken sets the optional parameter "pageToken": A continuation
// token, used to page through ad units. To retrieve the next page, set
// this parameter to the value of "nextPageToken" from the previous
// response.
func (c *AdunitsListCall) PageToken(pageToken string) *AdunitsListCall {
c.opt_["pageToken"] = pageToken
return c
}
func (c *AdunitsListCall) Do() (*AdUnits, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["includeInactive"]; ok {
params.Set("includeInactive", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["maxResults"]; ok {
params.Set("maxResults", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["pageToken"]; ok {
params.Set("pageToken", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative("https://www.googleapis.com/adsense/v1/", "adclients/{adClientId}/adunits")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{adClientId}", url.QueryEscape(c.adClientId), 1)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(AdUnits)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "List all ad units in the specified ad client for this AdSense account.",
// "httpMethod": "GET",
// "id": "adsense.adunits.list",
// "parameterOrder": [
// "adClientId"
// ],
// "parameters": {
// "adClientId": {
// "description": "Ad client for which to list ad units.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "includeInactive": {
// "description": "Whether to include inactive ad units. Default: true.",
// "location": "query",
// "type": "boolean"
// },
// "maxResults": {
// "description": "The maximum number of ad units to include in the response, used for paging.",
// "format": "int32",
// "location": "query",
// "maximum": "10000",
// "minimum": "0",
// "type": "integer"
// },
// "pageToken": {
// "description": "A continuation token, used to page through ad units. To retrieve the next page, set this parameter to the value of \"nextPageToken\" from the previous response.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "adclients/{adClientId}/adunits",
// "response": {
// "$ref": "AdUnits"
// },
// "scopes": [
// "https://www.googleapis.com/auth/adsense",
// "https://www.googleapis.com/auth/adsense.readonly"
// ]
// }
}
// method id "adsense.customchannels.list":
type CustomchannelsListCall struct {
s *Service
adClientId string
opt_ map[string]interface{}
}
// List: List all custom channels in the specified ad client for this
// AdSense account.
func (r *CustomchannelsService) List(adClientId string) *CustomchannelsListCall {
c := &CustomchannelsListCall{s: r.s, opt_: make(map[string]interface{})}
c.adClientId = adClientId
return c
}
// MaxResults sets the optional parameter "maxResults": The maximum
// number of custom channels to include in the response, used for
// paging.
func (c *CustomchannelsListCall) MaxResults(maxResults int64) *CustomchannelsListCall {
c.opt_["maxResults"] = maxResults
return c
}
// PageToken sets the optional parameter "pageToken": A continuation
// token, used to page through custom channels. To retrieve the next
// page, set this parameter to the value of "nextPageToken" from the
// previous response.
func (c *CustomchannelsListCall) PageToken(pageToken string) *CustomchannelsListCall {
c.opt_["pageToken"] = pageToken
return c
}
func (c *CustomchannelsListCall) Do() (*CustomChannels, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["maxResults"]; ok {
params.Set("maxResults", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["pageToken"]; ok {
params.Set("pageToken", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative("https://www.googleapis.com/adsense/v1/", "adclients/{adClientId}/customchannels")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{adClientId}", url.QueryEscape(c.adClientId), 1)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(CustomChannels)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "List all custom channels in the specified ad client for this AdSense account.",
// "httpMethod": "GET",
// "id": "adsense.customchannels.list",
// "parameterOrder": [
// "adClientId"
// ],
// "parameters": {
// "adClientId": {
// "description": "Ad client for which to list custom channels.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "maxResults": {
// "description": "The maximum number of custom channels to include in the response, used for paging.",
// "format": "int32",
// "location": "query",
// "maximum": "10000",
// "minimum": "0",
// "type": "integer"
// },
// "pageToken": {
// "description": "A continuation token, used to page through custom channels. To retrieve the next page, set this parameter to the value of \"nextPageToken\" from the previous response.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "adclients/{adClientId}/customchannels",
// "response": {
// "$ref": "CustomChannels"
// },
// "scopes": [
// "https://www.googleapis.com/auth/adsense",
// "https://www.googleapis.com/auth/adsense.readonly"
// ]
// }
}
// method id "adsense.reports.generate":
type ReportsGenerateCall struct {
s *Service
startDate string
endDate string
opt_ map[string]interface{}
}
// Generate: Generate an AdSense report based on the report request sent
// in the query parameters. Returns the result as JSON; to retrieve
// output in CSV format specify "alt=csv" as a query parameter.
func (r *ReportsService) Generate(startDate string, endDate string) *ReportsGenerateCall {
c := &ReportsGenerateCall{s: r.s, opt_: make(map[string]interface{})}
c.startDate = startDate
c.endDate = endDate
return c
}
// Currency sets the optional parameter "currency": Optional currency to
// use when reporting on monetary metrics. Defaults to the account's
// currency if not set.
func (c *ReportsGenerateCall) Currency(currency string) *ReportsGenerateCall {
c.opt_["currency"] = currency
return c
}
// Dimension sets the optional parameter "dimension": Dimensions to base
// the report on.
func (c *ReportsGenerateCall) Dimension(dimension string) *ReportsGenerateCall {
c.opt_["dimension"] = dimension
return c
}
// Filter sets the optional parameter "filter": Filters to be run on the
// report.
func (c *ReportsGenerateCall) Filter(filter string) *ReportsGenerateCall {
c.opt_["filter"] = filter
return c
}
// Locale sets the optional parameter "locale": Optional locale to use
// for translating report output to a local language. Defaults to
// "en_US" if not specified.
func (c *ReportsGenerateCall) Locale(locale string) *ReportsGenerateCall {
c.opt_["locale"] = locale
return c
}
// MaxResults sets the optional parameter "maxResults": The maximum
// number of rows of report data to return.
func (c *ReportsGenerateCall) MaxResults(maxResults int64) *ReportsGenerateCall {
c.opt_["maxResults"] = maxResults
return c
}
// Metric sets the optional parameter "metric": Numeric columns to
// include in the report.
func (c *ReportsGenerateCall) Metric(metric string) *ReportsGenerateCall {
c.opt_["metric"] = metric
return c
}
// Sort sets the optional parameter "sort": The name of a dimension or
// metric to sort the resulting report on, optionally prefixed with "+"
// to sort ascending or "-" to sort descending. If no prefix is
// specified, the column is sorted ascending.
func (c *ReportsGenerateCall) Sort(sort string) *ReportsGenerateCall {
c.opt_["sort"] = sort
return c
}
// StartIndex sets the optional parameter "startIndex": Index of the
// first row of report data to return.
func (c *ReportsGenerateCall) StartIndex(startIndex int64) *ReportsGenerateCall {
c.opt_["startIndex"] = startIndex
return c
}
func (c *ReportsGenerateCall) Do() (*AdsenseReportsGenerateResponse, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
params.Set("endDate", fmt.Sprintf("%v", c.endDate))
params.Set("startDate", fmt.Sprintf("%v", c.startDate))
if v, ok := c.opt_["currency"]; ok {
params.Set("currency", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["dimension"]; ok {
params.Set("dimension", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["filter"]; ok {
params.Set("filter", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["locale"]; ok {
params.Set("locale", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["maxResults"]; ok {
params.Set("maxResults", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["metric"]; ok {
params.Set("metric", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["sort"]; ok {
params.Set("sort", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["startIndex"]; ok {
params.Set("startIndex", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative("https://www.googleapis.com/adsense/v1/", "reports")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(AdsenseReportsGenerateResponse)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Generate an AdSense report based on the report request sent in the query parameters. Returns the result as JSON; to retrieve output in CSV format specify \"alt=csv\" as a query parameter.",
// "httpMethod": "GET",
// "id": "adsense.reports.generate",
// "parameterOrder": [
// "startDate",
// "endDate"
// ],
// "parameters": {
// "currency": {
// "description": "Optional currency to use when reporting on monetary metrics. Defaults to the account's currency if not set.",
// "location": "query",
// "pattern": "[a-zA-Z]+",
// "type": "string"
// },
// "dimension": {
// "description": "Dimensions to base the report on.",
// "location": "query",
// "pattern": "[a-zA-Z_]+",
// "repeated": true,
// "type": "string"
// },
// "endDate": {
// "description": "End of the date range to report on in \"YYYY-MM-DD\" format, inclusive.",
// "location": "query",
// "pattern": "\\d{4}-\\d{2}-\\d{2}|(today|startOfMonth|startOfYear)(([\\-\\+]\\d+[dwmy]){0,2}?)",
// "required": true,
// "type": "string"
// },
// "filter": {
// "description": "Filters to be run on the report.",
// "location": "query",
// "pattern": "[a-zA-Z_]+(==|=@).+",
// "repeated": true,
// "type": "string"
// },
// "locale": {
// "description": "Optional locale to use for translating report output to a local language. Defaults to \"en_US\" if not specified.",
// "location": "query",
// "pattern": "[a-zA-Z_]+",
// "type": "string"
// },
// "maxResults": {
// "description": "The maximum number of rows of report data to return.",
// "format": "int32",
// "location": "query",
// "maximum": "50000",
// "minimum": "0",
// "type": "integer"
// },
// "metric": {
// "description": "Numeric columns to include in the report.",
// "location": "query",
// "pattern": "[a-zA-Z_]+",
// "repeated": true,
// "type": "string"
// },
// "sort": {
// "description": "The name of a dimension or metric to sort the resulting report on, optionally prefixed with \"+\" to sort ascending or \"-\" to sort descending. If no prefix is specified, the column is sorted ascending.",
// "location": "query",
// "pattern": "(\\+|-)?[a-zA-Z_]+",
// "repeated": true,
// "type": "string"
// },
// "startDate": {
// "description": "Start of the date range to report on in \"YYYY-MM-DD\" format, inclusive.",
// "location": "query",
// "pattern": "\\d{4}-\\d{2}-\\d{2}|(today|startOfMonth|startOfYear)(([\\-\\+]\\d+[dwmy]){0,2}?)",
// "required": true,
// "type": "string"
// },
// "startIndex": {
// "description": "Index of the first row of report data to return.",
// "format": "int32",
// "location": "query",
// "maximum": "5000",
// "minimum": "0",
// "type": "integer"
// }
// },
// "path": "reports",
// "response": {
// "$ref": "AdsenseReportsGenerateResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/adsense",
// "https://www.googleapis.com/auth/adsense.readonly"
// ]
// }
}
// method id "adsense.urlchannels.list":
type UrlchannelsListCall struct {
s *Service
adClientId string
opt_ map[string]interface{}
}
// List: List all URL channels in the specified ad client for this
// AdSense account.
func (r *UrlchannelsService) List(adClientId string) *UrlchannelsListCall {
c := &UrlchannelsListCall{s: r.s, opt_: make(map[string]interface{})}
c.adClientId = adClientId
return c
}
// MaxResults sets the optional parameter "maxResults": The maximum
// number of URL channels to include in the response, used for paging.
func (c *UrlchannelsListCall) MaxResults(maxResults int64) *UrlchannelsListCall {
c.opt_["maxResults"] = maxResults
return c
}
// PageToken sets the optional parameter "pageToken": A continuation
// token, used to page through URL channels. To retrieve the next page,
// set this parameter to the value of "nextPageToken" from the previous
// response.
func (c *UrlchannelsListCall) PageToken(pageToken string) *UrlchannelsListCall {
c.opt_["pageToken"] = pageToken
return c
}
func (c *UrlchannelsListCall) Do() (*UrlChannels, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["maxResults"]; ok {
params.Set("maxResults", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["pageToken"]; ok {
params.Set("pageToken", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative("https://www.googleapis.com/adsense/v1/", "adclients/{adClientId}/urlchannels")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{adClientId}", url.QueryEscape(c.adClientId), 1)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(UrlChannels)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "List all URL channels in the specified ad client for this AdSense account.",
// "httpMethod": "GET",
// "id": "adsense.urlchannels.list",
// "parameterOrder": [
// "adClientId"
// ],
// "parameters": {
// "adClientId": {
// "description": "Ad client for which to list URL channels.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "maxResults": {
// "description": "The maximum number of URL channels to include in the response, used for paging.",
// "format": "int32",
// "location": "query",
// "maximum": "10000",
// "minimum": "0",
// "type": "integer"
// },
// "pageToken": {
// "description": "A continuation token, used to page through URL channels. To retrieve the next page, set this parameter to the value of \"nextPageToken\" from the previous response.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "adclients/{adClientId}/urlchannels",
// "response": {
// "$ref": "UrlChannels"
// },
// "scopes": [
// "https://www.googleapis.com/auth/adsense",
// "https://www.googleapis.com/auth/adsense.readonly"
// ]
// }
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,365 @@
{
"kind": "discovery#restDescription",
"etag": "\"kEk3sFj6Ef5_yR1-H3bAO6qw9mI/g0dlAqv19pD_cw5NLrQ2z9eB7ig\"",
"discoveryVersion": "v1",
"id": "analytics:v2.4",
"name": "analytics",
"version": "v2.4",
"title": "Google Analytics API",
"description": "View and manage your Google Analytics data",
"ownerDomain": "google.com",
"ownerName": "Google",
"icons": {
"x16": "http://www.google.com/images/icons/product/analytics-16.png",
"x32": "http://www.google.com/images/icons/product/analytics-32.png"
},
"documentationLink": "https://developers.google.com/analytics/",
"protocol": "rest",
"baseUrl": "https://www.googleapis.com/analytics/v2.4/",
"basePath": "/analytics/v2.4/",
"rootUrl": "https://www.googleapis.com/",
"servicePath": "analytics/v2.4/",
"batchPath": "batch",
"parameters": {
"alt": {
"type": "string",
"description": "Data format for the response.",
"default": "atom",
"enum": [
"atom"
],
"enumDescriptions": [
"Responses with Content-Type of application/atom+xml"
],
"location": "query"
},
"fields": {
"type": "string",
"description": "Selector specifying which fields to include in a partial response.",
"location": "query"
},
"key": {
"type": "string",
"description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.",
"location": "query"
},
"oauth_token": {
"type": "string",
"description": "OAuth 2.0 token for the current user.",
"location": "query"
},
"prettyPrint": {
"type": "boolean",
"description": "Returns response with indentations and line breaks.",
"default": "false",
"location": "query"
},
"quotaUser": {
"type": "string",
"description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.",
"location": "query"
},
"userIp": {
"type": "string",
"description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.",
"location": "query"
}
},
"auth": {
"oauth2": {
"scopes": {
"https://www.googleapis.com/auth/analytics": {
"description": "View and manage your Google Analytics data"
},
"https://www.googleapis.com/auth/analytics.readonly": {
"description": "View your Google Analytics data"
}
}
}
},
"resources": {
"data": {
"methods": {
"get": {
"id": "analytics.data.get",
"path": "data",
"httpMethod": "GET",
"description": "Returns Analytics report data for a view (profile).",
"parameters": {
"dimensions": {
"type": "string",
"description": "A comma-separated list of Analytics dimensions. E.g., 'ga:browser,ga:city'.",
"pattern": "(ga:.+)?",
"location": "query"
},
"end-date": {
"type": "string",
"description": "End date for fetching report data. All requests should specify an end date formatted as YYYY-MM-DD.",
"required": true,
"pattern": "[0-9]{4}-[0-9]{2}-[0-9]{2}",
"location": "query"
},
"filters": {
"type": "string",
"description": "A comma-separated list of dimension or metric filters to be applied to the report data.",
"pattern": "ga:.+",
"location": "query"
},
"ids": {
"type": "string",
"description": "Unique table ID for retrieving report data. Table ID is of the form ga:XXXX, where XXXX is the Analytics view (profile) ID.",
"required": true,
"pattern": "ga:[0-9]+",
"location": "query"
},
"max-results": {
"type": "integer",
"description": "The maximum number of entries to include in this feed.",
"format": "int32",
"location": "query"
},
"metrics": {
"type": "string",
"description": "A comma-separated list of Analytics metrics. E.g., 'ga:visits,ga:pageviews'. At least one metric must be specified to retrieve a valid Analytics report.",
"required": true,
"pattern": "ga:.+",
"location": "query"
},
"segment": {
"type": "string",
"description": "An Analytics advanced segment to be applied to the report data.",
"location": "query"
},
"sort": {
"type": "string",
"description": "A comma-separated list of dimensions or metrics that determine the sort order for the report data.",
"pattern": "(-)?ga:.+",
"location": "query"
},
"start-date": {
"type": "string",
"description": "Start date for fetching report data. All requests should specify a start date formatted as YYYY-MM-DD.",
"required": true,
"pattern": "[0-9]{4}-[0-9]{2}-[0-9]{2}",
"location": "query"
},
"start-index": {
"type": "integer",
"description": "An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.",
"format": "int32",
"minimum": "1",
"location": "query"
}
},
"parameterOrder": [
"ids",
"start-date",
"end-date",
"metrics"
],
"scopes": [
"https://www.googleapis.com/auth/analytics",
"https://www.googleapis.com/auth/analytics.readonly"
]
}
}
},
"management": {
"resources": {
"accounts": {
"methods": {
"list": {
"id": "analytics.management.accounts.list",
"path": "management/accounts",
"httpMethod": "GET",
"description": "Lists all accounts to which the user has access.",
"parameters": {
"max-results": {
"type": "integer",
"description": "The maximum number of accounts to include in this response.",
"format": "int32",
"location": "query"
},
"start-index": {
"type": "integer",
"description": "An index of the first account to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.",
"format": "int32",
"minimum": "1",
"location": "query"
}
},
"scopes": [
"https://www.googleapis.com/auth/analytics",
"https://www.googleapis.com/auth/analytics.readonly"
]
}
}
},
"goals": {
"methods": {
"list": {
"id": "analytics.management.goals.list",
"path": "management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/goals",
"httpMethod": "GET",
"description": "Lists goals to which the user has access.",
"parameters": {
"accountId": {
"type": "string",
"description": "Account ID to retrieve goals for. Can either be a specific account ID or '~all', which refers to all the accounts that user has access to.",
"required": true,
"location": "path"
},
"max-results": {
"type": "integer",
"description": "The maximum number of goals to include in this response.",
"format": "int32",
"location": "query"
},
"profileId": {
"type": "string",
"description": "View (Profile) ID to retrieve goals for. Can either be a specific view (profile) ID or '~all', which refers to all the views (profiles) that user has access to.",
"required": true,
"location": "path"
},
"start-index": {
"type": "integer",
"description": "An index of the first goal to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.",
"format": "int32",
"minimum": "1",
"location": "query"
},
"webPropertyId": {
"type": "string",
"description": "Web property ID to retrieve goals for. Can either be a specific web property ID or '~all', which refers to all the web properties that user has access to.",
"required": true,
"location": "path"
}
},
"parameterOrder": [
"accountId",
"webPropertyId",
"profileId"
],
"scopes": [
"https://www.googleapis.com/auth/analytics",
"https://www.googleapis.com/auth/analytics.readonly"
]
}
}
},
"profiles": {
"methods": {
"list": {
"id": "analytics.management.profiles.list",
"path": "management/accounts/{accountId}/webproperties/{webPropertyId}/profiles",
"httpMethod": "GET",
"description": "Lists views (profiles) to which the user has access.",
"parameters": {
"accountId": {
"type": "string",
"description": "Account ID for the views (profiles) to retrieve. Can either be a specific account ID or '~all', which refers to all the accounts to which the user has access.",
"required": true,
"location": "path"
},
"max-results": {
"type": "integer",
"description": "The maximum number of views (profiles) to include in this response.",
"format": "int32",
"location": "query"
},
"start-index": {
"type": "integer",
"description": "An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.",
"format": "int32",
"minimum": "1",
"location": "query"
},
"webPropertyId": {
"type": "string",
"description": "Web property ID for the views (profiles) to retrieve. Can either be a specific web property ID or '~all', which refers to all the web properties to which the user has access.",
"required": true,
"location": "path"
}
},
"parameterOrder": [
"accountId",
"webPropertyId"
],
"scopes": [
"https://www.googleapis.com/auth/analytics",
"https://www.googleapis.com/auth/analytics.readonly"
]
}
}
},
"segments": {
"methods": {
"list": {
"id": "analytics.management.segments.list",
"path": "management/segments",
"httpMethod": "GET",
"description": "Lists advanced segments to which the user has access.",
"parameters": {
"max-results": {
"type": "integer",
"description": "The maximum number of advanced segments to include in this response.",
"format": "int32",
"location": "query"
},
"start-index": {
"type": "integer",
"description": "An index of the first advanced segment to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.",
"format": "int32",
"minimum": "1",
"location": "query"
}
},
"scopes": [
"https://www.googleapis.com/auth/analytics",
"https://www.googleapis.com/auth/analytics.readonly"
]
}
}
},
"webproperties": {
"methods": {
"list": {
"id": "analytics.management.webproperties.list",
"path": "management/accounts/{accountId}/webproperties",
"httpMethod": "GET",
"description": "Lists web properties to which the user has access.",
"parameters": {
"accountId": {
"type": "string",
"description": "Account ID to retrieve web properties for. Can either be a specific account ID or '~all', which refers to all the accounts that user has access to.",
"required": true,
"location": "path"
},
"max-results": {
"type": "integer",
"description": "The maximum number of web properties to include in this response.",
"format": "int32",
"location": "query"
},
"start-index": {
"type": "integer",
"description": "An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.",
"format": "int32",
"minimum": "1",
"location": "query"
}
},
"parameterOrder": [
"accountId"
],
"scopes": [
"https://www.googleapis.com/auth/analytics",
"https://www.googleapis.com/auth/analytics.readonly"
]
}
}
}
}
}
}
}

View File

@ -0,0 +1,803 @@
// Package analytics provides access to the Google Analytics API.
//
// See https://developers.google.com/analytics/
//
// Usage example:
//
// import "code.google.com/p/google-api-go-client/analytics/v2.4"
// ...
// analyticsService, err := analytics.New(oauthHttpClient)
package analytics
import (
"bytes"
"code.google.com/p/google-api-go-client/googleapi"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
)
// Always reference these packages, just in case the auto-generated code
// below doesn't.
var _ = bytes.NewBuffer
var _ = strconv.Itoa
var _ = fmt.Sprintf
var _ = json.NewDecoder
var _ = io.Copy
var _ = url.Parse
var _ = googleapi.Version
var _ = errors.New
var _ = strings.Replace
const apiId = "analytics:v2.4"
const apiName = "analytics"
const apiVersion = "v2.4"
const basePath = "https://www.googleapis.com/analytics/v2.4/"
// OAuth2 scopes used by this API.
const (
// View and manage your Google Analytics data
AnalyticsScope = "https://www.googleapis.com/auth/analytics"
// View your Google Analytics data
AnalyticsReadonlyScope = "https://www.googleapis.com/auth/analytics.readonly"
)
func New(client *http.Client) (*Service, error) {
if client == nil {
return nil, errors.New("client is nil")
}
s := &Service{client: client, BasePath: basePath}
s.Data = NewDataService(s)
s.Management = NewManagementService(s)
return s, nil
}
type Service struct {
client *http.Client
BasePath string // API endpoint base URL
Data *DataService
Management *ManagementService
}
func NewDataService(s *Service) *DataService {
rs := &DataService{s: s}
return rs
}
type DataService struct {
s *Service
}
func NewManagementService(s *Service) *ManagementService {
rs := &ManagementService{s: s}
rs.Accounts = NewManagementAccountsService(s)
rs.Goals = NewManagementGoalsService(s)
rs.Profiles = NewManagementProfilesService(s)
rs.Segments = NewManagementSegmentsService(s)
rs.Webproperties = NewManagementWebpropertiesService(s)
return rs
}
type ManagementService struct {
s *Service
Accounts *ManagementAccountsService
Goals *ManagementGoalsService
Profiles *ManagementProfilesService
Segments *ManagementSegmentsService
Webproperties *ManagementWebpropertiesService
}
func NewManagementAccountsService(s *Service) *ManagementAccountsService {
rs := &ManagementAccountsService{s: s}
return rs
}
type ManagementAccountsService struct {
s *Service
}
func NewManagementGoalsService(s *Service) *ManagementGoalsService {
rs := &ManagementGoalsService{s: s}
return rs
}
type ManagementGoalsService struct {
s *Service
}
func NewManagementProfilesService(s *Service) *ManagementProfilesService {
rs := &ManagementProfilesService{s: s}
return rs
}
type ManagementProfilesService struct {
s *Service
}
func NewManagementSegmentsService(s *Service) *ManagementSegmentsService {
rs := &ManagementSegmentsService{s: s}
return rs
}
type ManagementSegmentsService struct {
s *Service
}
func NewManagementWebpropertiesService(s *Service) *ManagementWebpropertiesService {
rs := &ManagementWebpropertiesService{s: s}
return rs
}
type ManagementWebpropertiesService struct {
s *Service
}
// method id "analytics.data.get":
type DataGetCall struct {
s *Service
ids string
startDate string
endDate string
metrics string
opt_ map[string]interface{}
}
// Get: Returns Analytics report data for a view (profile).
func (r *DataService) Get(ids string, startDate string, endDate string, metrics string) *DataGetCall {
c := &DataGetCall{s: r.s, opt_: make(map[string]interface{})}
c.ids = ids
c.startDate = startDate
c.endDate = endDate
c.metrics = metrics
return c
}
// Dimensions sets the optional parameter "dimensions": A
// comma-separated list of Analytics dimensions. E.g.,
// 'ga:browser,ga:city'.
func (c *DataGetCall) Dimensions(dimensions string) *DataGetCall {
c.opt_["dimensions"] = dimensions
return c
}
// Filters sets the optional parameter "filters": A comma-separated list
// of dimension or metric filters to be applied to the report data.
func (c *DataGetCall) Filters(filters string) *DataGetCall {
c.opt_["filters"] = filters
return c
}
// MaxResults sets the optional parameter "max-results": The maximum
// number of entries to include in this feed.
func (c *DataGetCall) MaxResults(maxResults int64) *DataGetCall {
c.opt_["max-results"] = maxResults
return c
}
// Segment sets the optional parameter "segment": An Analytics advanced
// segment to be applied to the report data.
func (c *DataGetCall) Segment(segment string) *DataGetCall {
c.opt_["segment"] = segment
return c
}
// Sort sets the optional parameter "sort": A comma-separated list of
// dimensions or metrics that determine the sort order for the report
// data.
func (c *DataGetCall) Sort(sort string) *DataGetCall {
c.opt_["sort"] = sort
return c
}
// StartIndex sets the optional parameter "start-index": An index of the
// first entity to retrieve. Use this parameter as a pagination
// mechanism along with the max-results parameter.
func (c *DataGetCall) StartIndex(startIndex int64) *DataGetCall {
c.opt_["start-index"] = startIndex
return c
}
func (c *DataGetCall) Do() error {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
params.Set("end-date", fmt.Sprintf("%v", c.endDate))
params.Set("ids", fmt.Sprintf("%v", c.ids))
params.Set("metrics", fmt.Sprintf("%v", c.metrics))
params.Set("start-date", fmt.Sprintf("%v", c.startDate))
if v, ok := c.opt_["dimensions"]; ok {
params.Set("dimensions", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["filters"]; ok {
params.Set("filters", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["max-results"]; ok {
params.Set("max-results", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["segment"]; ok {
params.Set("segment", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["sort"]; ok {
params.Set("sort", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["start-index"]; ok {
params.Set("start-index", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "data")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Returns Analytics report data for a view (profile).",
// "httpMethod": "GET",
// "id": "analytics.data.get",
// "parameterOrder": [
// "ids",
// "start-date",
// "end-date",
// "metrics"
// ],
// "parameters": {
// "dimensions": {
// "description": "A comma-separated list of Analytics dimensions. E.g., 'ga:browser,ga:city'.",
// "location": "query",
// "pattern": "(ga:.+)?",
// "type": "string"
// },
// "end-date": {
// "description": "End date for fetching report data. All requests should specify an end date formatted as YYYY-MM-DD.",
// "location": "query",
// "pattern": "[0-9]{4}-[0-9]{2}-[0-9]{2}",
// "required": true,
// "type": "string"
// },
// "filters": {
// "description": "A comma-separated list of dimension or metric filters to be applied to the report data.",
// "location": "query",
// "pattern": "ga:.+",
// "type": "string"
// },
// "ids": {
// "description": "Unique table ID for retrieving report data. Table ID is of the form ga:XXXX, where XXXX is the Analytics view (profile) ID.",
// "location": "query",
// "pattern": "ga:[0-9]+",
// "required": true,
// "type": "string"
// },
// "max-results": {
// "description": "The maximum number of entries to include in this feed.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "metrics": {
// "description": "A comma-separated list of Analytics metrics. E.g., 'ga:visits,ga:pageviews'. At least one metric must be specified to retrieve a valid Analytics report.",
// "location": "query",
// "pattern": "ga:.+",
// "required": true,
// "type": "string"
// },
// "segment": {
// "description": "An Analytics advanced segment to be applied to the report data.",
// "location": "query",
// "type": "string"
// },
// "sort": {
// "description": "A comma-separated list of dimensions or metrics that determine the sort order for the report data.",
// "location": "query",
// "pattern": "(-)?ga:.+",
// "type": "string"
// },
// "start-date": {
// "description": "Start date for fetching report data. All requests should specify a start date formatted as YYYY-MM-DD.",
// "location": "query",
// "pattern": "[0-9]{4}-[0-9]{2}-[0-9]{2}",
// "required": true,
// "type": "string"
// },
// "start-index": {
// "description": "An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.",
// "format": "int32",
// "location": "query",
// "minimum": "1",
// "type": "integer"
// }
// },
// "path": "data",
// "scopes": [
// "https://www.googleapis.com/auth/analytics",
// "https://www.googleapis.com/auth/analytics.readonly"
// ]
// }
}
// method id "analytics.management.accounts.list":
type ManagementAccountsListCall struct {
s *Service
opt_ map[string]interface{}
}
// List: Lists all accounts to which the user has access.
func (r *ManagementAccountsService) List() *ManagementAccountsListCall {
c := &ManagementAccountsListCall{s: r.s, opt_: make(map[string]interface{})}
return c
}
// MaxResults sets the optional parameter "max-results": The maximum
// number of accounts to include in this response.
func (c *ManagementAccountsListCall) MaxResults(maxResults int64) *ManagementAccountsListCall {
c.opt_["max-results"] = maxResults
return c
}
// StartIndex sets the optional parameter "start-index": An index of the
// first account to retrieve. Use this parameter as a pagination
// mechanism along with the max-results parameter.
func (c *ManagementAccountsListCall) StartIndex(startIndex int64) *ManagementAccountsListCall {
c.opt_["start-index"] = startIndex
return c
}
func (c *ManagementAccountsListCall) Do() error {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["max-results"]; ok {
params.Set("max-results", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["start-index"]; ok {
params.Set("start-index", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "management/accounts")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Lists all accounts to which the user has access.",
// "httpMethod": "GET",
// "id": "analytics.management.accounts.list",
// "parameters": {
// "max-results": {
// "description": "The maximum number of accounts to include in this response.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "start-index": {
// "description": "An index of the first account to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.",
// "format": "int32",
// "location": "query",
// "minimum": "1",
// "type": "integer"
// }
// },
// "path": "management/accounts",
// "scopes": [
// "https://www.googleapis.com/auth/analytics",
// "https://www.googleapis.com/auth/analytics.readonly"
// ]
// }
}
// method id "analytics.management.goals.list":
type ManagementGoalsListCall struct {
s *Service
accountId string
webPropertyId string
profileId string
opt_ map[string]interface{}
}
// List: Lists goals to which the user has access.
func (r *ManagementGoalsService) List(accountId string, webPropertyId string, profileId string) *ManagementGoalsListCall {
c := &ManagementGoalsListCall{s: r.s, opt_: make(map[string]interface{})}
c.accountId = accountId
c.webPropertyId = webPropertyId
c.profileId = profileId
return c
}
// MaxResults sets the optional parameter "max-results": The maximum
// number of goals to include in this response.
func (c *ManagementGoalsListCall) MaxResults(maxResults int64) *ManagementGoalsListCall {
c.opt_["max-results"] = maxResults
return c
}
// StartIndex sets the optional parameter "start-index": An index of the
// first goal to retrieve. Use this parameter as a pagination mechanism
// along with the max-results parameter.
func (c *ManagementGoalsListCall) StartIndex(startIndex int64) *ManagementGoalsListCall {
c.opt_["start-index"] = startIndex
return c
}
func (c *ManagementGoalsListCall) Do() error {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["max-results"]; ok {
params.Set("max-results", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["start-index"]; ok {
params.Set("start-index", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/goals")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{accountId}", url.QueryEscape(c.accountId), 1)
req.URL.Path = strings.Replace(req.URL.Path, "{webPropertyId}", url.QueryEscape(c.webPropertyId), 1)
req.URL.Path = strings.Replace(req.URL.Path, "{profileId}", url.QueryEscape(c.profileId), 1)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Lists goals to which the user has access.",
// "httpMethod": "GET",
// "id": "analytics.management.goals.list",
// "parameterOrder": [
// "accountId",
// "webPropertyId",
// "profileId"
// ],
// "parameters": {
// "accountId": {
// "description": "Account ID to retrieve goals for. Can either be a specific account ID or '~all', which refers to all the accounts that user has access to.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "max-results": {
// "description": "The maximum number of goals to include in this response.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "profileId": {
// "description": "View (Profile) ID to retrieve goals for. Can either be a specific view (profile) ID or '~all', which refers to all the views (profiles) that user has access to.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "start-index": {
// "description": "An index of the first goal to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.",
// "format": "int32",
// "location": "query",
// "minimum": "1",
// "type": "integer"
// },
// "webPropertyId": {
// "description": "Web property ID to retrieve goals for. Can either be a specific web property ID or '~all', which refers to all the web properties that user has access to.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/goals",
// "scopes": [
// "https://www.googleapis.com/auth/analytics",
// "https://www.googleapis.com/auth/analytics.readonly"
// ]
// }
}
// method id "analytics.management.profiles.list":
type ManagementProfilesListCall struct {
s *Service
accountId string
webPropertyId string
opt_ map[string]interface{}
}
// List: Lists views (profiles) to which the user has access.
func (r *ManagementProfilesService) List(accountId string, webPropertyId string) *ManagementProfilesListCall {
c := &ManagementProfilesListCall{s: r.s, opt_: make(map[string]interface{})}
c.accountId = accountId
c.webPropertyId = webPropertyId
return c
}
// MaxResults sets the optional parameter "max-results": The maximum
// number of views (profiles) to include in this response.
func (c *ManagementProfilesListCall) MaxResults(maxResults int64) *ManagementProfilesListCall {
c.opt_["max-results"] = maxResults
return c
}
// StartIndex sets the optional parameter "start-index": An index of the
// first entity to retrieve. Use this parameter as a pagination
// mechanism along with the max-results parameter.
func (c *ManagementProfilesListCall) StartIndex(startIndex int64) *ManagementProfilesListCall {
c.opt_["start-index"] = startIndex
return c
}
func (c *ManagementProfilesListCall) Do() error {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["max-results"]; ok {
params.Set("max-results", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["start-index"]; ok {
params.Set("start-index", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "management/accounts/{accountId}/webproperties/{webPropertyId}/profiles")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{accountId}", url.QueryEscape(c.accountId), 1)
req.URL.Path = strings.Replace(req.URL.Path, "{webPropertyId}", url.QueryEscape(c.webPropertyId), 1)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Lists views (profiles) to which the user has access.",
// "httpMethod": "GET",
// "id": "analytics.management.profiles.list",
// "parameterOrder": [
// "accountId",
// "webPropertyId"
// ],
// "parameters": {
// "accountId": {
// "description": "Account ID for the views (profiles) to retrieve. Can either be a specific account ID or '~all', which refers to all the accounts to which the user has access.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "max-results": {
// "description": "The maximum number of views (profiles) to include in this response.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "start-index": {
// "description": "An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.",
// "format": "int32",
// "location": "query",
// "minimum": "1",
// "type": "integer"
// },
// "webPropertyId": {
// "description": "Web property ID for the views (profiles) to retrieve. Can either be a specific web property ID or '~all', which refers to all the web properties to which the user has access.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "management/accounts/{accountId}/webproperties/{webPropertyId}/profiles",
// "scopes": [
// "https://www.googleapis.com/auth/analytics",
// "https://www.googleapis.com/auth/analytics.readonly"
// ]
// }
}
// method id "analytics.management.segments.list":
type ManagementSegmentsListCall struct {
s *Service
opt_ map[string]interface{}
}
// List: Lists advanced segments to which the user has access.
func (r *ManagementSegmentsService) List() *ManagementSegmentsListCall {
c := &ManagementSegmentsListCall{s: r.s, opt_: make(map[string]interface{})}
return c
}
// MaxResults sets the optional parameter "max-results": The maximum
// number of advanced segments to include in this response.
func (c *ManagementSegmentsListCall) MaxResults(maxResults int64) *ManagementSegmentsListCall {
c.opt_["max-results"] = maxResults
return c
}
// StartIndex sets the optional parameter "start-index": An index of the
// first advanced segment to retrieve. Use this parameter as a
// pagination mechanism along with the max-results parameter.
func (c *ManagementSegmentsListCall) StartIndex(startIndex int64) *ManagementSegmentsListCall {
c.opt_["start-index"] = startIndex
return c
}
func (c *ManagementSegmentsListCall) Do() error {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["max-results"]; ok {
params.Set("max-results", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["start-index"]; ok {
params.Set("start-index", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "management/segments")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Lists advanced segments to which the user has access.",
// "httpMethod": "GET",
// "id": "analytics.management.segments.list",
// "parameters": {
// "max-results": {
// "description": "The maximum number of advanced segments to include in this response.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "start-index": {
// "description": "An index of the first advanced segment to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.",
// "format": "int32",
// "location": "query",
// "minimum": "1",
// "type": "integer"
// }
// },
// "path": "management/segments",
// "scopes": [
// "https://www.googleapis.com/auth/analytics",
// "https://www.googleapis.com/auth/analytics.readonly"
// ]
// }
}
// method id "analytics.management.webproperties.list":
type ManagementWebpropertiesListCall struct {
s *Service
accountId string
opt_ map[string]interface{}
}
// List: Lists web properties to which the user has access.
func (r *ManagementWebpropertiesService) List(accountId string) *ManagementWebpropertiesListCall {
c := &ManagementWebpropertiesListCall{s: r.s, opt_: make(map[string]interface{})}
c.accountId = accountId
return c
}
// MaxResults sets the optional parameter "max-results": The maximum
// number of web properties to include in this response.
func (c *ManagementWebpropertiesListCall) MaxResults(maxResults int64) *ManagementWebpropertiesListCall {
c.opt_["max-results"] = maxResults
return c
}
// StartIndex sets the optional parameter "start-index": An index of the
// first entity to retrieve. Use this parameter as a pagination
// mechanism along with the max-results parameter.
func (c *ManagementWebpropertiesListCall) StartIndex(startIndex int64) *ManagementWebpropertiesListCall {
c.opt_["start-index"] = startIndex
return c
}
func (c *ManagementWebpropertiesListCall) Do() error {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["max-results"]; ok {
params.Set("max-results", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["start-index"]; ok {
params.Set("start-index", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "management/accounts/{accountId}/webproperties")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{accountId}", url.QueryEscape(c.accountId), 1)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Lists web properties to which the user has access.",
// "httpMethod": "GET",
// "id": "analytics.management.webproperties.list",
// "parameterOrder": [
// "accountId"
// ],
// "parameters": {
// "accountId": {
// "description": "Account ID to retrieve web properties for. Can either be a specific account ID or '~all', which refers to all the accounts that user has access to.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "max-results": {
// "description": "The maximum number of web properties to include in this response.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "start-index": {
// "description": "An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.",
// "format": "int32",
// "location": "query",
// "minimum": "1",
// "type": "integer"
// }
// },
// "path": "management/accounts/{accountId}/webproperties",
// "scopes": [
// "https://www.googleapis.com/auth/analytics",
// "https://www.googleapis.com/auth/analytics.readonly"
// ]
// }
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,255 @@
{
"kind": "discovery#restDescription",
"etag": "\"kEk3sFj6Ef5_yR1-H3bAO6qw9mI/i7ndXglQkcB7KPR_-HCYBmUKBRE\"",
"discoveryVersion": "v1",
"id": "androidpublisher:v1.1",
"name": "androidpublisher",
"canonicalName": "Android Publisher",
"version": "v1.1",
"title": "Google Play Android Developer API",
"description": "Lets Android application developers access their Google Play accounts.",
"ownerDomain": "google.com",
"ownerName": "Google",
"icons": {
"x16": "http://www.google.com/images/icons/product/android-16.png",
"x32": "http://www.google.com/images/icons/product/android-32.png"
},
"documentationLink": "https://developers.google.com/android-publisher",
"protocol": "rest",
"baseUrl": "https://www.googleapis.com/androidpublisher/v1.1/applications/",
"basePath": "/androidpublisher/v1.1/applications/",
"rootUrl": "https://www.googleapis.com/",
"servicePath": "androidpublisher/v1.1/applications/",
"batchPath": "batch",
"parameters": {
"alt": {
"type": "string",
"description": "Data format for the response.",
"default": "json",
"enum": [
"json"
],
"enumDescriptions": [
"Responses with Content-Type of application/json"
],
"location": "query"
},
"fields": {
"type": "string",
"description": "Selector specifying which fields to include in a partial response.",
"location": "query"
},
"key": {
"type": "string",
"description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.",
"location": "query"
},
"oauth_token": {
"type": "string",
"description": "OAuth 2.0 token for the current user.",
"location": "query"
},
"prettyPrint": {
"type": "boolean",
"description": "Returns response with indentations and line breaks.",
"default": "true",
"location": "query"
},
"quotaUser": {
"type": "string",
"description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.",
"location": "query"
},
"userIp": {
"type": "string",
"description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.",
"location": "query"
}
},
"auth": {
"oauth2": {
"scopes": {
"https://www.googleapis.com/auth/androidpublisher": {
"description": "View and manage your Google Play Android Developer account"
}
}
}
},
"schemas": {
"InappPurchase": {
"id": "InappPurchase",
"type": "object",
"description": "A Purchase resource indicates the status of a user's subscription purchase.",
"properties": {
"consumptionState": {
"type": "integer",
"description": "The consumption state of the inapp product. Possible values are: \n- Yet to be consumed \n- Consumed",
"format": "int32"
},
"developerPayload": {
"type": "string",
"description": "A developer-specified string that contains supplemental information about an order."
},
"kind": {
"type": "string",
"description": "This kind represents a inappPurchase object in the androidpublisher service.",
"default": "androidpublisher#inappPurchase"
},
"purchaseState": {
"type": "integer",
"description": "The purchase state of the order. Possible values are: \n- Purchased \n- Cancelled",
"format": "int32"
},
"purchaseTime": {
"type": "string",
"description": "The time the product was purchased, in milliseconds since the epoch (Jan 1, 1970).",
"format": "int64"
}
}
},
"SubscriptionPurchase": {
"id": "SubscriptionPurchase",
"type": "object",
"description": "A Purchase resource indicates the status of a user's subscription purchase.",
"properties": {
"autoRenewing": {
"type": "boolean",
"description": "Whether the subscription will automatically be renewed when it reaches its current expiry time."
},
"initiationTimestampMsec": {
"type": "string",
"description": "Time at which the subscription was granted, in milliseconds since Epoch.",
"format": "int64"
},
"kind": {
"type": "string",
"description": "This kind represents a subscriptionPurchase object in the androidpublisher service.",
"default": "androidpublisher#subscriptionPurchase"
},
"validUntilTimestampMsec": {
"type": "string",
"description": "Time at which the subscription will expire, in milliseconds since Epoch.",
"format": "int64"
}
}
}
},
"resources": {
"inapppurchases": {
"methods": {
"get": {
"id": "androidpublisher.inapppurchases.get",
"path": "{packageName}/inapp/{productId}/purchases/{token}",
"httpMethod": "GET",
"description": "Checks the purchase and consumption status of an inapp item.",
"parameters": {
"packageName": {
"type": "string",
"description": "The package name of the application the inapp product was sold in (for example, 'com.some.thing').",
"required": true,
"location": "path"
},
"productId": {
"type": "string",
"description": "The inapp product SKU (for example, 'com.some.thing.inapp1').",
"required": true,
"location": "path"
},
"token": {
"type": "string",
"description": "The token provided to the user's device when the inapp product was purchased.",
"required": true,
"location": "path"
}
},
"parameterOrder": [
"packageName",
"productId",
"token"
],
"response": {
"$ref": "InappPurchase"
},
"scopes": [
"https://www.googleapis.com/auth/androidpublisher"
]
}
}
},
"purchases": {
"methods": {
"cancel": {
"id": "androidpublisher.purchases.cancel",
"path": "{packageName}/subscriptions/{subscriptionId}/purchases/{token}/cancel",
"httpMethod": "POST",
"description": "Cancels a user's subscription purchase. The subscription remains valid until its expiration time.",
"parameters": {
"packageName": {
"type": "string",
"description": "The package name of the application for which this subscription was purchased (for example, 'com.some.thing').",
"required": true,
"location": "path"
},
"subscriptionId": {
"type": "string",
"description": "The purchased subscription ID (for example, 'monthly001').",
"required": true,
"location": "path"
},
"token": {
"type": "string",
"description": "The token provided to the user's device when the subscription was purchased.",
"required": true,
"location": "path"
}
},
"parameterOrder": [
"packageName",
"subscriptionId",
"token"
],
"scopes": [
"https://www.googleapis.com/auth/androidpublisher"
]
},
"get": {
"id": "androidpublisher.purchases.get",
"path": "{packageName}/subscriptions/{subscriptionId}/purchases/{token}",
"httpMethod": "GET",
"description": "Checks whether a user's subscription purchase is valid and returns its expiry time.",
"parameters": {
"packageName": {
"type": "string",
"description": "The package name of the application for which this subscription was purchased (for example, 'com.some.thing').",
"required": true,
"location": "path"
},
"subscriptionId": {
"type": "string",
"description": "The purchased subscription ID (for example, 'monthly001').",
"required": true,
"location": "path"
},
"token": {
"type": "string",
"description": "The token provided to the user's device when the subscription was purchased.",
"required": true,
"location": "path"
}
},
"parameterOrder": [
"packageName",
"subscriptionId",
"token"
],
"response": {
"$ref": "SubscriptionPurchase"
},
"scopes": [
"https://www.googleapis.com/auth/androidpublisher"
]
}
}
}
}
}

View File

@ -0,0 +1,374 @@
// Package androidpublisher provides access to the Google Play Android Developer API.
//
// See https://developers.google.com/android-publisher
//
// Usage example:
//
// import "code.google.com/p/google-api-go-client/androidpublisher/v1.1"
// ...
// androidpublisherService, err := androidpublisher.New(oauthHttpClient)
package androidpublisher
import (
"bytes"
"code.google.com/p/google-api-go-client/googleapi"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
)
// Always reference these packages, just in case the auto-generated code
// below doesn't.
var _ = bytes.NewBuffer
var _ = strconv.Itoa
var _ = fmt.Sprintf
var _ = json.NewDecoder
var _ = io.Copy
var _ = url.Parse
var _ = googleapi.Version
var _ = errors.New
var _ = strings.Replace
const apiId = "androidpublisher:v1.1"
const apiName = "androidpublisher"
const apiVersion = "v1.1"
const basePath = "https://www.googleapis.com/androidpublisher/v1.1/applications/"
// OAuth2 scopes used by this API.
const (
// View and manage your Google Play Android Developer account
AndroidpublisherScope = "https://www.googleapis.com/auth/androidpublisher"
)
func New(client *http.Client) (*Service, error) {
if client == nil {
return nil, errors.New("client is nil")
}
s := &Service{client: client, BasePath: basePath}
s.Inapppurchases = NewInapppurchasesService(s)
s.Purchases = NewPurchasesService(s)
return s, nil
}
type Service struct {
client *http.Client
BasePath string // API endpoint base URL
Inapppurchases *InapppurchasesService
Purchases *PurchasesService
}
func NewInapppurchasesService(s *Service) *InapppurchasesService {
rs := &InapppurchasesService{s: s}
return rs
}
type InapppurchasesService struct {
s *Service
}
func NewPurchasesService(s *Service) *PurchasesService {
rs := &PurchasesService{s: s}
return rs
}
type PurchasesService struct {
s *Service
}
type InappPurchase struct {
// ConsumptionState: The consumption state of the inapp product.
// Possible values are:
// - Yet to be consumed
// - Consumed
ConsumptionState int64 `json:"consumptionState,omitempty"`
// DeveloperPayload: A developer-specified string that contains
// supplemental information about an order.
DeveloperPayload string `json:"developerPayload,omitempty"`
// Kind: This kind represents a inappPurchase object in the
// androidpublisher service.
Kind string `json:"kind,omitempty"`
// PurchaseState: The purchase state of the order. Possible values are:
//
// - Purchased
// - Cancelled
PurchaseState int64 `json:"purchaseState,omitempty"`
// PurchaseTime: The time the product was purchased, in milliseconds
// since the epoch (Jan 1, 1970).
PurchaseTime int64 `json:"purchaseTime,omitempty,string"`
}
type SubscriptionPurchase struct {
// AutoRenewing: Whether the subscription will automatically be renewed
// when it reaches its current expiry time.
AutoRenewing bool `json:"autoRenewing,omitempty"`
// InitiationTimestampMsec: Time at which the subscription was granted,
// in milliseconds since Epoch.
InitiationTimestampMsec int64 `json:"initiationTimestampMsec,omitempty,string"`
// Kind: This kind represents a subscriptionPurchase object in the
// androidpublisher service.
Kind string `json:"kind,omitempty"`
// ValidUntilTimestampMsec: Time at which the subscription will expire,
// in milliseconds since Epoch.
ValidUntilTimestampMsec int64 `json:"validUntilTimestampMsec,omitempty,string"`
}
// method id "androidpublisher.inapppurchases.get":
type InapppurchasesGetCall struct {
s *Service
packageName string
productId string
token string
opt_ map[string]interface{}
}
// Get: Checks the purchase and consumption status of an inapp item.
func (r *InapppurchasesService) Get(packageName string, productId string, token string) *InapppurchasesGetCall {
c := &InapppurchasesGetCall{s: r.s, opt_: make(map[string]interface{})}
c.packageName = packageName
c.productId = productId
c.token = token
return c
}
func (c *InapppurchasesGetCall) Do() (*InappPurchase, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
urls := googleapi.ResolveRelative(c.s.BasePath, "{packageName}/inapp/{productId}/purchases/{token}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{packageName}", url.QueryEscape(c.packageName), 1)
req.URL.Path = strings.Replace(req.URL.Path, "{productId}", url.QueryEscape(c.productId), 1)
req.URL.Path = strings.Replace(req.URL.Path, "{token}", url.QueryEscape(c.token), 1)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(InappPurchase)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Checks the purchase and consumption status of an inapp item.",
// "httpMethod": "GET",
// "id": "androidpublisher.inapppurchases.get",
// "parameterOrder": [
// "packageName",
// "productId",
// "token"
// ],
// "parameters": {
// "packageName": {
// "description": "The package name of the application the inapp product was sold in (for example, 'com.some.thing').",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "productId": {
// "description": "The inapp product SKU (for example, 'com.some.thing.inapp1').",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "token": {
// "description": "The token provided to the user's device when the inapp product was purchased.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "{packageName}/inapp/{productId}/purchases/{token}",
// "response": {
// "$ref": "InappPurchase"
// },
// "scopes": [
// "https://www.googleapis.com/auth/androidpublisher"
// ]
// }
}
// method id "androidpublisher.purchases.cancel":
type PurchasesCancelCall struct {
s *Service
packageName string
subscriptionId string
token string
opt_ map[string]interface{}
}
// Cancel: Cancels a user's subscription purchase. The subscription
// remains valid until its expiration time.
func (r *PurchasesService) Cancel(packageName string, subscriptionId string, token string) *PurchasesCancelCall {
c := &PurchasesCancelCall{s: r.s, opt_: make(map[string]interface{})}
c.packageName = packageName
c.subscriptionId = subscriptionId
c.token = token
return c
}
func (c *PurchasesCancelCall) Do() error {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
urls := googleapi.ResolveRelative(c.s.BasePath, "{packageName}/subscriptions/{subscriptionId}/purchases/{token}/cancel")
urls += "?" + params.Encode()
req, _ := http.NewRequest("POST", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{packageName}", url.QueryEscape(c.packageName), 1)
req.URL.Path = strings.Replace(req.URL.Path, "{subscriptionId}", url.QueryEscape(c.subscriptionId), 1)
req.URL.Path = strings.Replace(req.URL.Path, "{token}", url.QueryEscape(c.token), 1)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Cancels a user's subscription purchase. The subscription remains valid until its expiration time.",
// "httpMethod": "POST",
// "id": "androidpublisher.purchases.cancel",
// "parameterOrder": [
// "packageName",
// "subscriptionId",
// "token"
// ],
// "parameters": {
// "packageName": {
// "description": "The package name of the application for which this subscription was purchased (for example, 'com.some.thing').",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "subscriptionId": {
// "description": "The purchased subscription ID (for example, 'monthly001').",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "token": {
// "description": "The token provided to the user's device when the subscription was purchased.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "{packageName}/subscriptions/{subscriptionId}/purchases/{token}/cancel",
// "scopes": [
// "https://www.googleapis.com/auth/androidpublisher"
// ]
// }
}
// method id "androidpublisher.purchases.get":
type PurchasesGetCall struct {
s *Service
packageName string
subscriptionId string
token string
opt_ map[string]interface{}
}
// Get: Checks whether a user's subscription purchase is valid and
// returns its expiry time.
func (r *PurchasesService) Get(packageName string, subscriptionId string, token string) *PurchasesGetCall {
c := &PurchasesGetCall{s: r.s, opt_: make(map[string]interface{})}
c.packageName = packageName
c.subscriptionId = subscriptionId
c.token = token
return c
}
func (c *PurchasesGetCall) Do() (*SubscriptionPurchase, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
urls := googleapi.ResolveRelative(c.s.BasePath, "{packageName}/subscriptions/{subscriptionId}/purchases/{token}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{packageName}", url.QueryEscape(c.packageName), 1)
req.URL.Path = strings.Replace(req.URL.Path, "{subscriptionId}", url.QueryEscape(c.subscriptionId), 1)
req.URL.Path = strings.Replace(req.URL.Path, "{token}", url.QueryEscape(c.token), 1)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(SubscriptionPurchase)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Checks whether a user's subscription purchase is valid and returns its expiry time.",
// "httpMethod": "GET",
// "id": "androidpublisher.purchases.get",
// "parameterOrder": [
// "packageName",
// "subscriptionId",
// "token"
// ],
// "parameters": {
// "packageName": {
// "description": "The package name of the application for which this subscription was purchased (for example, 'com.some.thing').",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "subscriptionId": {
// "description": "The purchased subscription ID (for example, 'monthly001').",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "token": {
// "description": "The token provided to the user's device when the subscription was purchased.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "{packageName}/subscriptions/{subscriptionId}/purchases/{token}",
// "response": {
// "$ref": "SubscriptionPurchase"
// },
// "scopes": [
// "https://www.googleapis.com/auth/androidpublisher"
// ]
// }
}

View File

@ -0,0 +1,183 @@
{
"kind": "discovery#restDescription",
"etag": "\"kEk3sFj6Ef5_yR1-H3bAO6qw9mI/7feCcsSBHiSVKUXs7gmA_Rg25gw\"",
"discoveryVersion": "v1",
"id": "androidpublisher:v1",
"name": "androidpublisher",
"canonicalName": "Android Publisher",
"version": "v1",
"title": "Google Play Android Developer API",
"description": "Lets Android application developers access their Google Play accounts.",
"ownerDomain": "google.com",
"ownerName": "Google",
"icons": {
"x16": "http://www.google.com/images/icons/product/android-16.png",
"x32": "http://www.google.com/images/icons/product/android-32.png"
},
"documentationLink": "https://developers.google.com/android-publisher",
"protocol": "rest",
"baseUrl": "https://www.googleapis.com/androidpublisher/v1/applications/",
"basePath": "/androidpublisher/v1/applications/",
"rootUrl": "https://www.googleapis.com/",
"servicePath": "androidpublisher/v1/applications/",
"batchPath": "batch",
"parameters": {
"alt": {
"type": "string",
"description": "Data format for the response.",
"default": "json",
"enum": [
"json"
],
"enumDescriptions": [
"Responses with Content-Type of application/json"
],
"location": "query"
},
"fields": {
"type": "string",
"description": "Selector specifying which fields to include in a partial response.",
"location": "query"
},
"key": {
"type": "string",
"description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.",
"location": "query"
},
"oauth_token": {
"type": "string",
"description": "OAuth 2.0 token for the current user.",
"location": "query"
},
"prettyPrint": {
"type": "boolean",
"description": "Returns response with indentations and line breaks.",
"default": "true",
"location": "query"
},
"quotaUser": {
"type": "string",
"description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.",
"location": "query"
},
"userIp": {
"type": "string",
"description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.",
"location": "query"
}
},
"auth": {
"oauth2": {
"scopes": {
"https://www.googleapis.com/auth/androidpublisher": {
"description": "View and manage your Google Play Android Developer account"
}
}
}
},
"schemas": {
"SubscriptionPurchase": {
"id": "SubscriptionPurchase",
"type": "object",
"description": "A Purchase resource indicates the status of a user's subscription purchase.",
"properties": {
"autoRenewing": {
"type": "boolean",
"description": "Whether the subscription will automatically be renewed when it reaches its current expiry time."
},
"initiationTimestampMsec": {
"type": "string",
"description": "Time at which the subscription was granted, in milliseconds since Epoch.",
"format": "int64"
},
"kind": {
"type": "string",
"description": "This kind represents a subscriptionPurchase object in the androidpublisher service.",
"default": "androidpublisher#subscriptionPurchase"
},
"validUntilTimestampMsec": {
"type": "string",
"description": "Time at which the subscription will expire, in milliseconds since Epoch.",
"format": "int64"
}
}
}
},
"resources": {
"purchases": {
"methods": {
"cancel": {
"id": "androidpublisher.purchases.cancel",
"path": "{packageName}/subscriptions/{subscriptionId}/purchases/{token}/cancel",
"httpMethod": "POST",
"description": "Cancels a user's subscription purchase. The subscription remains valid until its expiration time.",
"parameters": {
"packageName": {
"type": "string",
"description": "The package name of the application for which this subscription was purchased (for example, 'com.some.thing').",
"required": true,
"location": "path"
},
"subscriptionId": {
"type": "string",
"description": "The purchased subscription ID (for example, 'monthly001').",
"required": true,
"location": "path"
},
"token": {
"type": "string",
"description": "The token provided to the user's device when the subscription was purchased.",
"required": true,
"location": "path"
}
},
"parameterOrder": [
"packageName",
"subscriptionId",
"token"
],
"scopes": [
"https://www.googleapis.com/auth/androidpublisher"
]
},
"get": {
"id": "androidpublisher.purchases.get",
"path": "{packageName}/subscriptions/{subscriptionId}/purchases/{token}",
"httpMethod": "GET",
"description": "Checks whether a user's subscription purchase is valid and returns its expiry time.",
"parameters": {
"packageName": {
"type": "string",
"description": "The package name of the application for which this subscription was purchased (for example, 'com.some.thing').",
"required": true,
"location": "path"
},
"subscriptionId": {
"type": "string",
"description": "The purchased subscription ID (for example, 'monthly001').",
"required": true,
"location": "path"
},
"token": {
"type": "string",
"description": "The token provided to the user's device when the subscription was purchased.",
"required": true,
"location": "path"
}
},
"parameterOrder": [
"packageName",
"subscriptionId",
"token"
],
"response": {
"$ref": "SubscriptionPurchase"
},
"scopes": [
"https://www.googleapis.com/auth/androidpublisher"
]
}
}
}
}
}

View File

@ -0,0 +1,252 @@
// Package androidpublisher provides access to the Google Play Android Developer API.
//
// See https://developers.google.com/android-publisher
//
// Usage example:
//
// import "code.google.com/p/google-api-go-client/androidpublisher/v1"
// ...
// androidpublisherService, err := androidpublisher.New(oauthHttpClient)
package androidpublisher
import (
"bytes"
"code.google.com/p/google-api-go-client/googleapi"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
)
// Always reference these packages, just in case the auto-generated code
// below doesn't.
var _ = bytes.NewBuffer
var _ = strconv.Itoa
var _ = fmt.Sprintf
var _ = json.NewDecoder
var _ = io.Copy
var _ = url.Parse
var _ = googleapi.Version
var _ = errors.New
var _ = strings.Replace
const apiId = "androidpublisher:v1"
const apiName = "androidpublisher"
const apiVersion = "v1"
const basePath = "https://www.googleapis.com/androidpublisher/v1/applications/"
// OAuth2 scopes used by this API.
const (
// View and manage your Google Play Android Developer account
AndroidpublisherScope = "https://www.googleapis.com/auth/androidpublisher"
)
func New(client *http.Client) (*Service, error) {
if client == nil {
return nil, errors.New("client is nil")
}
s := &Service{client: client, BasePath: basePath}
s.Purchases = NewPurchasesService(s)
return s, nil
}
type Service struct {
client *http.Client
BasePath string // API endpoint base URL
Purchases *PurchasesService
}
func NewPurchasesService(s *Service) *PurchasesService {
rs := &PurchasesService{s: s}
return rs
}
type PurchasesService struct {
s *Service
}
type SubscriptionPurchase struct {
// AutoRenewing: Whether the subscription will automatically be renewed
// when it reaches its current expiry time.
AutoRenewing bool `json:"autoRenewing,omitempty"`
// InitiationTimestampMsec: Time at which the subscription was granted,
// in milliseconds since Epoch.
InitiationTimestampMsec int64 `json:"initiationTimestampMsec,omitempty,string"`
// Kind: This kind represents a subscriptionPurchase object in the
// androidpublisher service.
Kind string `json:"kind,omitempty"`
// ValidUntilTimestampMsec: Time at which the subscription will expire,
// in milliseconds since Epoch.
ValidUntilTimestampMsec int64 `json:"validUntilTimestampMsec,omitempty,string"`
}
// method id "androidpublisher.purchases.cancel":
type PurchasesCancelCall struct {
s *Service
packageName string
subscriptionId string
token string
opt_ map[string]interface{}
}
// Cancel: Cancels a user's subscription purchase. The subscription
// remains valid until its expiration time.
func (r *PurchasesService) Cancel(packageName string, subscriptionId string, token string) *PurchasesCancelCall {
c := &PurchasesCancelCall{s: r.s, opt_: make(map[string]interface{})}
c.packageName = packageName
c.subscriptionId = subscriptionId
c.token = token
return c
}
func (c *PurchasesCancelCall) Do() error {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
urls := googleapi.ResolveRelative(c.s.BasePath, "{packageName}/subscriptions/{subscriptionId}/purchases/{token}/cancel")
urls += "?" + params.Encode()
req, _ := http.NewRequest("POST", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{packageName}", url.QueryEscape(c.packageName), 1)
req.URL.Path = strings.Replace(req.URL.Path, "{subscriptionId}", url.QueryEscape(c.subscriptionId), 1)
req.URL.Path = strings.Replace(req.URL.Path, "{token}", url.QueryEscape(c.token), 1)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Cancels a user's subscription purchase. The subscription remains valid until its expiration time.",
// "httpMethod": "POST",
// "id": "androidpublisher.purchases.cancel",
// "parameterOrder": [
// "packageName",
// "subscriptionId",
// "token"
// ],
// "parameters": {
// "packageName": {
// "description": "The package name of the application for which this subscription was purchased (for example, 'com.some.thing').",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "subscriptionId": {
// "description": "The purchased subscription ID (for example, 'monthly001').",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "token": {
// "description": "The token provided to the user's device when the subscription was purchased.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "{packageName}/subscriptions/{subscriptionId}/purchases/{token}/cancel",
// "scopes": [
// "https://www.googleapis.com/auth/androidpublisher"
// ]
// }
}
// method id "androidpublisher.purchases.get":
type PurchasesGetCall struct {
s *Service
packageName string
subscriptionId string
token string
opt_ map[string]interface{}
}
// Get: Checks whether a user's subscription purchase is valid and
// returns its expiry time.
func (r *PurchasesService) Get(packageName string, subscriptionId string, token string) *PurchasesGetCall {
c := &PurchasesGetCall{s: r.s, opt_: make(map[string]interface{})}
c.packageName = packageName
c.subscriptionId = subscriptionId
c.token = token
return c
}
func (c *PurchasesGetCall) Do() (*SubscriptionPurchase, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
urls := googleapi.ResolveRelative(c.s.BasePath, "{packageName}/subscriptions/{subscriptionId}/purchases/{token}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{packageName}", url.QueryEscape(c.packageName), 1)
req.URL.Path = strings.Replace(req.URL.Path, "{subscriptionId}", url.QueryEscape(c.subscriptionId), 1)
req.URL.Path = strings.Replace(req.URL.Path, "{token}", url.QueryEscape(c.token), 1)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(SubscriptionPurchase)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Checks whether a user's subscription purchase is valid and returns its expiry time.",
// "httpMethod": "GET",
// "id": "androidpublisher.purchases.get",
// "parameterOrder": [
// "packageName",
// "subscriptionId",
// "token"
// ],
// "parameters": {
// "packageName": {
// "description": "The package name of the application for which this subscription was purchased (for example, 'com.some.thing').",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "subscriptionId": {
// "description": "The purchased subscription ID (for example, 'monthly001').",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "token": {
// "description": "The token provided to the user's device when the subscription was purchased.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "{packageName}/subscriptions/{subscriptionId}/purchases/{token}",
// "response": {
// "$ref": "SubscriptionPurchase"
// },
// "scopes": [
// "https://www.googleapis.com/auth/androidpublisher"
// ]
// }
}

View File

@ -0,0 +1,306 @@
{
"kind": "discovery#restDescription",
"etag": "\"5M1WkxnZyJhziV-cW1kdtwscs8E/EnSZa1SHLGZEekBcq4ZvbeJLWQE\"",
"discoveryVersion": "v1",
"id": "appstate:v1",
"name": "appstate",
"canonicalName": "App State",
"version": "v1",
"title": "Google App State API",
"description": "The Google App State API.",
"ownerDomain": "google.com",
"ownerName": "Google",
"icons": {
"x16": "http://www.google.com/images/icons/product/search-16.gif",
"x32": "http://www.google.com/images/icons/product/search-32.gif"
},
"documentationLink": "https://developers.google.com/games/services/web/api/states",
"protocol": "rest",
"baseUrl": "https://www.googleapis.com/appstate/v1/",
"basePath": "/appstate/v1/",
"rootUrl": "https://www.googleapis.com/",
"servicePath": "appstate/v1/",
"batchPath": "batch",
"parameters": {
"alt": {
"type": "string",
"description": "Data format for the response.",
"default": "json",
"enum": [
"json"
],
"enumDescriptions": [
"Responses with Content-Type of application/json"
],
"location": "query"
},
"fields": {
"type": "string",
"description": "Selector specifying which fields to include in a partial response.",
"location": "query"
},
"key": {
"type": "string",
"description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.",
"location": "query"
},
"oauth_token": {
"type": "string",
"description": "OAuth 2.0 token for the current user.",
"location": "query"
},
"prettyPrint": {
"type": "boolean",
"description": "Returns response with indentations and line breaks.",
"default": "true",
"location": "query"
},
"quotaUser": {
"type": "string",
"description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.",
"location": "query"
},
"userIp": {
"type": "string",
"description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.",
"location": "query"
}
},
"auth": {
"oauth2": {
"scopes": {
"https://www.googleapis.com/auth/appstate": {
"description": "View and manage your data for this application"
}
}
}
},
"schemas": {
"GetResponse": {
"id": "GetResponse",
"type": "object",
"description": "This is a JSON template for an app state resource.",
"properties": {
"currentStateVersion": {
"type": "string",
"description": "The current app state version."
},
"data": {
"type": "string",
"description": "The requested data."
},
"kind": {
"type": "string",
"description": "Uniquely identifies the type of this resource. Value is always the fixed string appstate#getResponse.",
"default": "appstate#getResponse"
},
"stateKey": {
"type": "integer",
"description": "The key for the data.",
"format": "int32"
}
}
},
"ListResponse": {
"id": "ListResponse",
"type": "object",
"description": "This is a JSON template to convert a list-response for app state.",
"properties": {
"items": {
"type": "array",
"description": "The app state data.",
"items": {
"$ref": "GetResponse"
}
},
"kind": {
"type": "string",
"description": "Uniquely identifies the type of this resource. Value is always the fixed string appstate#listResponse.",
"default": "appstate#listResponse"
},
"maximumKeyCount": {
"type": "integer",
"description": "The maximum number of keys allowed for this user.",
"format": "int32"
}
}
},
"UpdateRequest": {
"id": "UpdateRequest",
"type": "object",
"description": "This is a JSON template for a requests which update app state",
"properties": {
"data": {
"type": "string",
"description": "The new app state data that your application is trying to update with."
},
"kind": {
"type": "string",
"description": "Uniquely identifies the type of this resource. Value is always the fixed string appstate#updateRequest.",
"default": "appstate#updateRequest"
}
}
},
"WriteResult": {
"id": "WriteResult",
"type": "object",
"description": "This is a JSON template for an app state write result.",
"properties": {
"currentStateVersion": {
"type": "string",
"description": "The version of the data for this key on the server."
},
"kind": {
"type": "string",
"description": "Uniquely identifies the type of this resource. Value is always the fixed string appstate#writeResult.",
"default": "appstate#writeResult"
},
"stateKey": {
"type": "integer",
"description": "The written key.",
"format": "int32"
}
}
}
},
"resources": {
"states": {
"methods": {
"clear": {
"id": "appstate.states.clear",
"path": "states/{stateKey}/clear",
"httpMethod": "POST",
"description": "Clears (sets to empty) the data for the passed key if and only if the passed version matches the currently stored version. This method results in a conflict error on version mismatch.",
"parameters": {
"currentDataVersion": {
"type": "string",
"description": "The version of the data to be cleared. Version strings are returned by the server.",
"location": "query"
},
"stateKey": {
"type": "integer",
"description": "The key for the data to be retrieved.",
"required": true,
"format": "int32",
"minimum": "0",
"maximum": "3",
"location": "path"
}
},
"parameterOrder": [
"stateKey"
],
"response": {
"$ref": "WriteResult"
},
"scopes": [
"https://www.googleapis.com/auth/appstate"
]
},
"delete": {
"id": "appstate.states.delete",
"path": "states/{stateKey}",
"httpMethod": "DELETE",
"description": "Deletes a key and the data associated with it. The key is removed and no longer counts against the key quota. Note that since this method is not safe in the face of concurrent modifications, it should only be used for development and testing purposes. Invoking this method in shipping code can result in data loss and data corruption.",
"parameters": {
"stateKey": {
"type": "integer",
"description": "The key for the data to be retrieved.",
"required": true,
"format": "int32",
"minimum": "0",
"maximum": "3",
"location": "path"
}
},
"parameterOrder": [
"stateKey"
],
"scopes": [
"https://www.googleapis.com/auth/appstate"
]
},
"get": {
"id": "appstate.states.get",
"path": "states/{stateKey}",
"httpMethod": "GET",
"description": "Retrieves the data corresponding to the passed key. If the key does not exist on the server, an HTTP 404 will be returned.",
"parameters": {
"stateKey": {
"type": "integer",
"description": "The key for the data to be retrieved.",
"required": true,
"format": "int32",
"minimum": "0",
"maximum": "3",
"location": "path"
}
},
"parameterOrder": [
"stateKey"
],
"response": {
"$ref": "GetResponse"
},
"scopes": [
"https://www.googleapis.com/auth/appstate"
]
},
"list": {
"id": "appstate.states.list",
"path": "states",
"httpMethod": "GET",
"description": "Lists all the states keys, and optionally the state data.",
"parameters": {
"includeData": {
"type": "boolean",
"description": "Whether to include the full data in addition to the version number",
"default": "false",
"location": "query"
}
},
"response": {
"$ref": "ListResponse"
},
"scopes": [
"https://www.googleapis.com/auth/appstate"
]
},
"update": {
"id": "appstate.states.update",
"path": "states/{stateKey}",
"httpMethod": "PUT",
"description": "Update the data associated with the input key if and only if the passed version matches the currently stored version. This method is safe in the face of concurrent writes. Maximum per-key size is 128KB.",
"parameters": {
"currentStateVersion": {
"type": "string",
"description": "The version of the app state your application is attempting to update. If this does not match the current version, this method will return a conflict error. If there is no data stored on the server for this key, the update will succeed irrespective of the value of this parameter.",
"location": "query"
},
"stateKey": {
"type": "integer",
"description": "The key for the data to be retrieved.",
"required": true,
"format": "int32",
"minimum": "0",
"maximum": "3",
"location": "path"
}
},
"parameterOrder": [
"stateKey"
],
"request": {
"$ref": "UpdateRequest"
},
"response": {
"$ref": "WriteResult"
},
"scopes": [
"https://www.googleapis.com/auth/appstate"
]
}
}
}
}
}

View File

@ -0,0 +1,507 @@
// Package appstate provides access to the Google App State API.
//
// See https://developers.google.com/games/services/web/api/states
//
// Usage example:
//
// import "code.google.com/p/google-api-go-client/appstate/v1"
// ...
// appstateService, err := appstate.New(oauthHttpClient)
package appstate
import (
"bytes"
"code.google.com/p/google-api-go-client/googleapi"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
)
// Always reference these packages, just in case the auto-generated code
// below doesn't.
var _ = bytes.NewBuffer
var _ = strconv.Itoa
var _ = fmt.Sprintf
var _ = json.NewDecoder
var _ = io.Copy
var _ = url.Parse
var _ = googleapi.Version
var _ = errors.New
var _ = strings.Replace
const apiId = "appstate:v1"
const apiName = "appstate"
const apiVersion = "v1"
const basePath = "https://www.googleapis.com/appstate/v1/"
// OAuth2 scopes used by this API.
const (
// View and manage your data for this application
AppstateScope = "https://www.googleapis.com/auth/appstate"
)
func New(client *http.Client) (*Service, error) {
if client == nil {
return nil, errors.New("client is nil")
}
s := &Service{client: client, BasePath: basePath}
s.States = NewStatesService(s)
return s, nil
}
type Service struct {
client *http.Client
BasePath string // API endpoint base URL
States *StatesService
}
func NewStatesService(s *Service) *StatesService {
rs := &StatesService{s: s}
return rs
}
type StatesService struct {
s *Service
}
type GetResponse struct {
// CurrentStateVersion: The current app state version.
CurrentStateVersion string `json:"currentStateVersion,omitempty"`
// Data: The requested data.
Data string `json:"data,omitempty"`
// Kind: Uniquely identifies the type of this resource. Value is always
// the fixed string appstate#getResponse.
Kind string `json:"kind,omitempty"`
// StateKey: The key for the data.
StateKey int64 `json:"stateKey,omitempty"`
}
type ListResponse struct {
// Items: The app state data.
Items []*GetResponse `json:"items,omitempty"`
// Kind: Uniquely identifies the type of this resource. Value is always
// the fixed string appstate#listResponse.
Kind string `json:"kind,omitempty"`
// MaximumKeyCount: The maximum number of keys allowed for this user.
MaximumKeyCount int64 `json:"maximumKeyCount,omitempty"`
}
type UpdateRequest struct {
// Data: The new app state data that your application is trying to
// update with.
Data string `json:"data,omitempty"`
// Kind: Uniquely identifies the type of this resource. Value is always
// the fixed string appstate#updateRequest.
Kind string `json:"kind,omitempty"`
}
type WriteResult struct {
// CurrentStateVersion: The version of the data for this key on the
// server.
CurrentStateVersion string `json:"currentStateVersion,omitempty"`
// Kind: Uniquely identifies the type of this resource. Value is always
// the fixed string appstate#writeResult.
Kind string `json:"kind,omitempty"`
// StateKey: The written key.
StateKey int64 `json:"stateKey,omitempty"`
}
// method id "appstate.states.clear":
type StatesClearCall struct {
s *Service
stateKey int64
opt_ map[string]interface{}
}
// Clear: Clears (sets to empty) the data for the passed key if and only
// if the passed version matches the currently stored version. This
// method results in a conflict error on version mismatch.
func (r *StatesService) Clear(stateKey int64) *StatesClearCall {
c := &StatesClearCall{s: r.s, opt_: make(map[string]interface{})}
c.stateKey = stateKey
return c
}
// CurrentDataVersion sets the optional parameter "currentDataVersion":
// The version of the data to be cleared. Version strings are returned
// by the server.
func (c *StatesClearCall) CurrentDataVersion(currentDataVersion string) *StatesClearCall {
c.opt_["currentDataVersion"] = currentDataVersion
return c
}
func (c *StatesClearCall) Do() (*WriteResult, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["currentDataVersion"]; ok {
params.Set("currentDataVersion", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "states/{stateKey}/clear")
urls += "?" + params.Encode()
req, _ := http.NewRequest("POST", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{stateKey}", strconv.FormatInt(c.stateKey, 10), 1)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(WriteResult)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Clears (sets to empty) the data for the passed key if and only if the passed version matches the currently stored version. This method results in a conflict error on version mismatch.",
// "httpMethod": "POST",
// "id": "appstate.states.clear",
// "parameterOrder": [
// "stateKey"
// ],
// "parameters": {
// "currentDataVersion": {
// "description": "The version of the data to be cleared. Version strings are returned by the server.",
// "location": "query",
// "type": "string"
// },
// "stateKey": {
// "description": "The key for the data to be retrieved.",
// "format": "int32",
// "location": "path",
// "maximum": "3",
// "minimum": "0",
// "required": true,
// "type": "integer"
// }
// },
// "path": "states/{stateKey}/clear",
// "response": {
// "$ref": "WriteResult"
// },
// "scopes": [
// "https://www.googleapis.com/auth/appstate"
// ]
// }
}
// method id "appstate.states.delete":
type StatesDeleteCall struct {
s *Service
stateKey int64
opt_ map[string]interface{}
}
// Delete: Deletes a key and the data associated with it. The key is
// removed and no longer counts against the key quota. Note that since
// this method is not safe in the face of concurrent modifications, it
// should only be used for development and testing purposes. Invoking
// this method in shipping code can result in data loss and data
// corruption.
func (r *StatesService) Delete(stateKey int64) *StatesDeleteCall {
c := &StatesDeleteCall{s: r.s, opt_: make(map[string]interface{})}
c.stateKey = stateKey
return c
}
func (c *StatesDeleteCall) Do() error {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
urls := googleapi.ResolveRelative(c.s.BasePath, "states/{stateKey}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("DELETE", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{stateKey}", strconv.FormatInt(c.stateKey, 10), 1)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Deletes a key and the data associated with it. The key is removed and no longer counts against the key quota. Note that since this method is not safe in the face of concurrent modifications, it should only be used for development and testing purposes. Invoking this method in shipping code can result in data loss and data corruption.",
// "httpMethod": "DELETE",
// "id": "appstate.states.delete",
// "parameterOrder": [
// "stateKey"
// ],
// "parameters": {
// "stateKey": {
// "description": "The key for the data to be retrieved.",
// "format": "int32",
// "location": "path",
// "maximum": "3",
// "minimum": "0",
// "required": true,
// "type": "integer"
// }
// },
// "path": "states/{stateKey}",
// "scopes": [
// "https://www.googleapis.com/auth/appstate"
// ]
// }
}
// method id "appstate.states.get":
type StatesGetCall struct {
s *Service
stateKey int64
opt_ map[string]interface{}
}
// Get: Retrieves the data corresponding to the passed key. If the key
// does not exist on the server, an HTTP 404 will be returned.
func (r *StatesService) Get(stateKey int64) *StatesGetCall {
c := &StatesGetCall{s: r.s, opt_: make(map[string]interface{})}
c.stateKey = stateKey
return c
}
func (c *StatesGetCall) Do() (*GetResponse, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
urls := googleapi.ResolveRelative(c.s.BasePath, "states/{stateKey}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{stateKey}", strconv.FormatInt(c.stateKey, 10), 1)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(GetResponse)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves the data corresponding to the passed key. If the key does not exist on the server, an HTTP 404 will be returned.",
// "httpMethod": "GET",
// "id": "appstate.states.get",
// "parameterOrder": [
// "stateKey"
// ],
// "parameters": {
// "stateKey": {
// "description": "The key for the data to be retrieved.",
// "format": "int32",
// "location": "path",
// "maximum": "3",
// "minimum": "0",
// "required": true,
// "type": "integer"
// }
// },
// "path": "states/{stateKey}",
// "response": {
// "$ref": "GetResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/appstate"
// ]
// }
}
// method id "appstate.states.list":
type StatesListCall struct {
s *Service
opt_ map[string]interface{}
}
// List: Lists all the states keys, and optionally the state data.
func (r *StatesService) List() *StatesListCall {
c := &StatesListCall{s: r.s, opt_: make(map[string]interface{})}
return c
}
// IncludeData sets the optional parameter "includeData": Whether to
// include the full data in addition to the version number
func (c *StatesListCall) IncludeData(includeData bool) *StatesListCall {
c.opt_["includeData"] = includeData
return c
}
func (c *StatesListCall) Do() (*ListResponse, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["includeData"]; ok {
params.Set("includeData", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "states")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(ListResponse)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists all the states keys, and optionally the state data.",
// "httpMethod": "GET",
// "id": "appstate.states.list",
// "parameters": {
// "includeData": {
// "default": "false",
// "description": "Whether to include the full data in addition to the version number",
// "location": "query",
// "type": "boolean"
// }
// },
// "path": "states",
// "response": {
// "$ref": "ListResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/appstate"
// ]
// }
}
// method id "appstate.states.update":
type StatesUpdateCall struct {
s *Service
stateKey int64
updaterequest *UpdateRequest
opt_ map[string]interface{}
}
// Update: Update the data associated with the input key if and only if
// the passed version matches the currently stored version. This method
// is safe in the face of concurrent writes. Maximum per-key size is
// 128KB.
func (r *StatesService) Update(stateKey int64, updaterequest *UpdateRequest) *StatesUpdateCall {
c := &StatesUpdateCall{s: r.s, opt_: make(map[string]interface{})}
c.stateKey = stateKey
c.updaterequest = updaterequest
return c
}
// CurrentStateVersion sets the optional parameter
// "currentStateVersion": The version of the app state your application
// is attempting to update. If this does not match the current version,
// this method will return a conflict error. If there is no data stored
// on the server for this key, the update will succeed irrespective of
// the value of this parameter.
func (c *StatesUpdateCall) CurrentStateVersion(currentStateVersion string) *StatesUpdateCall {
c.opt_["currentStateVersion"] = currentStateVersion
return c
}
func (c *StatesUpdateCall) Do() (*WriteResult, error) {
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.updaterequest)
if err != nil {
return nil, err
}
ctype := "application/json"
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["currentStateVersion"]; ok {
params.Set("currentStateVersion", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "states/{stateKey}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("PUT", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{stateKey}", strconv.FormatInt(c.stateKey, 10), 1)
googleapi.SetOpaque(req.URL)
req.Header.Set("Content-Type", ctype)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(WriteResult)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Update the data associated with the input key if and only if the passed version matches the currently stored version. This method is safe in the face of concurrent writes. Maximum per-key size is 128KB.",
// "httpMethod": "PUT",
// "id": "appstate.states.update",
// "parameterOrder": [
// "stateKey"
// ],
// "parameters": {
// "currentStateVersion": {
// "description": "The version of the app state your application is attempting to update. If this does not match the current version, this method will return a conflict error. If there is no data stored on the server for this key, the update will succeed irrespective of the value of this parameter.",
// "location": "query",
// "type": "string"
// },
// "stateKey": {
// "description": "The key for the data to be retrieved.",
// "format": "int32",
// "location": "path",
// "maximum": "3",
// "minimum": "0",
// "required": true,
// "type": "integer"
// }
// },
// "path": "states/{stateKey}",
// "request": {
// "$ref": "UpdateRequest"
// },
// "response": {
// "$ref": "WriteResult"
// },
// "scopes": [
// "https://www.googleapis.com/auth/appstate"
// ]
// }
}

View File

@ -0,0 +1,287 @@
{
"kind": "discovery#restDescription",
"etag": "\"kEk3sFj6Ef5_yR1-H3bAO6qw9mI/FnodQzLqRh_xHIkICK4PBBoHaLA\"",
"discoveryVersion": "v1",
"id": "audit:v1",
"name": "audit",
"version": "v1",
"title": "Enterprise Audit API",
"description": "Lets you access user activities in your enterprise made through various applications.",
"ownerDomain": "google.com",
"ownerName": "Google",
"icons": {
"x16": "http://www.google.com/images/icons/product/search-16.gif",
"x32": "http://www.google.com/images/icons/product/search-32.gif"
},
"documentationLink": "https://developers.google.com/google-apps/admin-audit/get_started",
"protocol": "rest",
"baseUrl": "https://www.googleapis.com/apps/reporting/audit/v1/",
"basePath": "/apps/reporting/audit/v1/",
"rootUrl": "https://www.googleapis.com/",
"servicePath": "apps/reporting/audit/v1/",
"batchPath": "batch",
"parameters": {
"alt": {
"type": "string",
"description": "Data format for the response.",
"default": "json",
"enum": [
"atom",
"json"
],
"enumDescriptions": [
"Responses with Content-Type of application/atom+xml",
"Responses with Content-Type of application/json"
],
"location": "query"
},
"fields": {
"type": "string",
"description": "Selector specifying which fields to include in a partial response.",
"location": "query"
},
"key": {
"type": "string",
"description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.",
"location": "query"
},
"oauth_token": {
"type": "string",
"description": "OAuth 2.0 token for the current user.",
"location": "query"
},
"prettyPrint": {
"type": "boolean",
"description": "Returns response with indentations and line breaks.",
"default": "true",
"location": "query"
},
"quotaUser": {
"type": "string",
"description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.",
"location": "query"
},
"userIp": {
"type": "string",
"description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.",
"location": "query"
}
},
"schemas": {
"Activities": {
"id": "Activities",
"type": "object",
"properties": {
"items": {
"type": "array",
"description": "Each record in read response.",
"items": {
"$ref": "Activity"
}
},
"kind": {
"type": "string",
"description": "Kind of list response this is.",
"default": "audit#activities"
},
"next": {
"type": "string",
"description": "Next page URL."
}
}
},
"Activity": {
"id": "Activity",
"type": "object",
"properties": {
"actor": {
"type": "object",
"description": "User doing the action.",
"properties": {
"applicationId": {
"type": "string",
"description": "ID of application which interacted on behalf of the user.",
"format": "int64"
},
"callerType": {
"type": "string",
"description": "User or OAuth 2LO request."
},
"email": {
"type": "string",
"description": "Email address of the user."
},
"key": {
"type": "string",
"description": "For OAuth 2LO API requests, consumer_key of the requestor."
}
}
},
"events": {
"type": "array",
"description": "Activity events.",
"items": {
"type": "object",
"properties": {
"eventType": {
"type": "string",
"description": "Type of event."
},
"name": {
"type": "string",
"description": "Name of event."
},
"parameters": {
"type": "array",
"description": "Event parameters.",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Name of the parameter."
},
"value": {
"type": "string",
"description": "Value of the parameter."
}
}
}
}
}
}
},
"id": {
"type": "object",
"description": "Unique identifier for each activity record.",
"properties": {
"applicationId": {
"type": "string",
"description": "Application ID of the source application.",
"format": "int64"
},
"customerId": {
"type": "string",
"description": "Obfuscated customer ID of the source customer."
},
"time": {
"type": "string",
"description": "Time of occurrence of the activity.",
"format": "date-time"
},
"uniqQualifier": {
"type": "string",
"description": "Unique qualifier if multiple events have the same time.",
"format": "int64"
}
}
},
"ipAddress": {
"type": "string",
"description": "IP Address of the user doing the action."
},
"kind": {
"type": "string",
"description": "Kind of resource this is.",
"default": "audit#activity"
},
"ownerDomain": {
"type": "string",
"description": "Domain of source customer."
}
}
}
},
"resources": {
"activities": {
"methods": {
"list": {
"id": "audit.activities.list",
"path": "{customerId}/{applicationId}",
"httpMethod": "GET",
"description": "Retrieves a list of activities for a specific customer and application.",
"parameters": {
"actorApplicationId": {
"type": "string",
"description": "Application ID of the application which interacted on behalf of the user while performing the event.",
"format": "int64",
"location": "query"
},
"actorEmail": {
"type": "string",
"description": "Email address of the user who performed the action.",
"location": "query"
},
"actorIpAddress": {
"type": "string",
"description": "IP Address of host where the event was performed. Supports both IPv4 and IPv6 addresses.",
"location": "query"
},
"applicationId": {
"type": "string",
"description": "Application ID of the application on which the event was performed.",
"required": true,
"format": "int64",
"location": "path"
},
"caller": {
"type": "string",
"description": "Type of the caller.",
"enum": [
"application_owner",
"customer"
],
"enumDescriptions": [
"Caller is an application owner.",
"Caller is a customer."
],
"location": "query"
},
"continuationToken": {
"type": "string",
"description": "Next page URL.",
"location": "query"
},
"customerId": {
"type": "string",
"description": "Represents the customer who is the owner of target object on which action was performed.",
"required": true,
"pattern": "C.+",
"location": "path"
},
"endTime": {
"type": "string",
"description": "Return events which occured at or before this time.",
"location": "query"
},
"eventName": {
"type": "string",
"description": "Name of the event being queried.",
"location": "query"
},
"maxResults": {
"type": "integer",
"description": "Number of activity records to be shown in each page.",
"format": "int32",
"minimum": "1",
"maximum": "1000",
"location": "query"
},
"startTime": {
"type": "string",
"description": "Return events which occured at or after this time.",
"location": "query"
}
},
"parameterOrder": [
"customerId",
"applicationId"
],
"response": {
"$ref": "Activities"
}
}
}
}
}
}

View File

@ -0,0 +1,367 @@
// Package audit provides access to the Enterprise Audit API.
//
// See https://developers.google.com/google-apps/admin-audit/get_started
//
// Usage example:
//
// import "code.google.com/p/google-api-go-client/audit/v1"
// ...
// auditService, err := audit.New(oauthHttpClient)
package audit
import (
"bytes"
"code.google.com/p/google-api-go-client/googleapi"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
)
// Always reference these packages, just in case the auto-generated code
// below doesn't.
var _ = bytes.NewBuffer
var _ = strconv.Itoa
var _ = fmt.Sprintf
var _ = json.NewDecoder
var _ = io.Copy
var _ = url.Parse
var _ = googleapi.Version
var _ = errors.New
var _ = strings.Replace
const apiId = "audit:v1"
const apiName = "audit"
const apiVersion = "v1"
const basePath = "https://www.googleapis.com/apps/reporting/audit/v1/"
func New(client *http.Client) (*Service, error) {
if client == nil {
return nil, errors.New("client is nil")
}
s := &Service{client: client, BasePath: basePath}
s.Activities = NewActivitiesService(s)
return s, nil
}
type Service struct {
client *http.Client
BasePath string // API endpoint base URL
Activities *ActivitiesService
}
func NewActivitiesService(s *Service) *ActivitiesService {
rs := &ActivitiesService{s: s}
return rs
}
type ActivitiesService struct {
s *Service
}
type Activities struct {
// Items: Each record in read response.
Items []*Activity `json:"items,omitempty"`
// Kind: Kind of list response this is.
Kind string `json:"kind,omitempty"`
// Next: Next page URL.
Next string `json:"next,omitempty"`
}
type Activity struct {
// Actor: User doing the action.
Actor *ActivityActor `json:"actor,omitempty"`
// Events: Activity events.
Events []*ActivityEvents `json:"events,omitempty"`
// Id: Unique identifier for each activity record.
Id *ActivityId `json:"id,omitempty"`
// IpAddress: IP Address of the user doing the action.
IpAddress string `json:"ipAddress,omitempty"`
// Kind: Kind of resource this is.
Kind string `json:"kind,omitempty"`
// OwnerDomain: Domain of source customer.
OwnerDomain string `json:"ownerDomain,omitempty"`
}
type ActivityActor struct {
// ApplicationId: ID of application which interacted on behalf of the
// user.
ApplicationId int64 `json:"applicationId,omitempty,string"`
// CallerType: User or OAuth 2LO request.
CallerType string `json:"callerType,omitempty"`
// Email: Email address of the user.
Email string `json:"email,omitempty"`
// Key: For OAuth 2LO API requests, consumer_key of the requestor.
Key string `json:"key,omitempty"`
}
type ActivityEvents struct {
// EventType: Type of event.
EventType string `json:"eventType,omitempty"`
// Name: Name of event.
Name string `json:"name,omitempty"`
// Parameters: Event parameters.
Parameters []*ActivityEventsParameters `json:"parameters,omitempty"`
}
type ActivityEventsParameters struct {
// Name: Name of the parameter.
Name string `json:"name,omitempty"`
// Value: Value of the parameter.
Value string `json:"value,omitempty"`
}
type ActivityId struct {
// ApplicationId: Application ID of the source application.
ApplicationId int64 `json:"applicationId,omitempty,string"`
// CustomerId: Obfuscated customer ID of the source customer.
CustomerId string `json:"customerId,omitempty"`
// Time: Time of occurrence of the activity.
Time string `json:"time,omitempty"`
// UniqQualifier: Unique qualifier if multiple events have the same
// time.
UniqQualifier int64 `json:"uniqQualifier,omitempty,string"`
}
// method id "audit.activities.list":
type ActivitiesListCall struct {
s *Service
customerId string
applicationId int64
opt_ map[string]interface{}
}
// List: Retrieves a list of activities for a specific customer and
// application.
func (r *ActivitiesService) List(customerId string, applicationId int64) *ActivitiesListCall {
c := &ActivitiesListCall{s: r.s, opt_: make(map[string]interface{})}
c.customerId = customerId
c.applicationId = applicationId
return c
}
// ActorApplicationId sets the optional parameter "actorApplicationId":
// Application ID of the application which interacted on behalf of the
// user while performing the event.
func (c *ActivitiesListCall) ActorApplicationId(actorApplicationId int64) *ActivitiesListCall {
c.opt_["actorApplicationId"] = actorApplicationId
return c
}
// ActorEmail sets the optional parameter "actorEmail": Email address of
// the user who performed the action.
func (c *ActivitiesListCall) ActorEmail(actorEmail string) *ActivitiesListCall {
c.opt_["actorEmail"] = actorEmail
return c
}
// ActorIpAddress sets the optional parameter "actorIpAddress": IP
// Address of host where the event was performed. Supports both IPv4 and
// IPv6 addresses.
func (c *ActivitiesListCall) ActorIpAddress(actorIpAddress string) *ActivitiesListCall {
c.opt_["actorIpAddress"] = actorIpAddress
return c
}
// Caller sets the optional parameter "caller": Type of the caller.
func (c *ActivitiesListCall) Caller(caller string) *ActivitiesListCall {
c.opt_["caller"] = caller
return c
}
// ContinuationToken sets the optional parameter "continuationToken":
// Next page URL.
func (c *ActivitiesListCall) ContinuationToken(continuationToken string) *ActivitiesListCall {
c.opt_["continuationToken"] = continuationToken
return c
}
// EndTime sets the optional parameter "endTime": Return events which
// occured at or before this time.
func (c *ActivitiesListCall) EndTime(endTime string) *ActivitiesListCall {
c.opt_["endTime"] = endTime
return c
}
// EventName sets the optional parameter "eventName": Name of the event
// being queried.
func (c *ActivitiesListCall) EventName(eventName string) *ActivitiesListCall {
c.opt_["eventName"] = eventName
return c
}
// MaxResults sets the optional parameter "maxResults": Number of
// activity records to be shown in each page.
func (c *ActivitiesListCall) MaxResults(maxResults int64) *ActivitiesListCall {
c.opt_["maxResults"] = maxResults
return c
}
// StartTime sets the optional parameter "startTime": Return events
// which occured at or after this time.
func (c *ActivitiesListCall) StartTime(startTime string) *ActivitiesListCall {
c.opt_["startTime"] = startTime
return c
}
func (c *ActivitiesListCall) Do() (*Activities, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["actorApplicationId"]; ok {
params.Set("actorApplicationId", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["actorEmail"]; ok {
params.Set("actorEmail", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["actorIpAddress"]; ok {
params.Set("actorIpAddress", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["caller"]; ok {
params.Set("caller", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["continuationToken"]; ok {
params.Set("continuationToken", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["endTime"]; ok {
params.Set("endTime", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["eventName"]; ok {
params.Set("eventName", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["maxResults"]; ok {
params.Set("maxResults", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["startTime"]; ok {
params.Set("startTime", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "{customerId}/{applicationId}")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{customerId}", url.QueryEscape(c.customerId), 1)
req.URL.Path = strings.Replace(req.URL.Path, "{applicationId}", strconv.FormatInt(c.applicationId, 10), 1)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(Activities)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves a list of activities for a specific customer and application.",
// "httpMethod": "GET",
// "id": "audit.activities.list",
// "parameterOrder": [
// "customerId",
// "applicationId"
// ],
// "parameters": {
// "actorApplicationId": {
// "description": "Application ID of the application which interacted on behalf of the user while performing the event.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "actorEmail": {
// "description": "Email address of the user who performed the action.",
// "location": "query",
// "type": "string"
// },
// "actorIpAddress": {
// "description": "IP Address of host where the event was performed. Supports both IPv4 and IPv6 addresses.",
// "location": "query",
// "type": "string"
// },
// "applicationId": {
// "description": "Application ID of the application on which the event was performed.",
// "format": "int64",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "caller": {
// "description": "Type of the caller.",
// "enum": [
// "application_owner",
// "customer"
// ],
// "enumDescriptions": [
// "Caller is an application owner.",
// "Caller is a customer."
// ],
// "location": "query",
// "type": "string"
// },
// "continuationToken": {
// "description": "Next page URL.",
// "location": "query",
// "type": "string"
// },
// "customerId": {
// "description": "Represents the customer who is the owner of target object on which action was performed.",
// "location": "path",
// "pattern": "C.+",
// "required": true,
// "type": "string"
// },
// "endTime": {
// "description": "Return events which occured at or before this time.",
// "location": "query",
// "type": "string"
// },
// "eventName": {
// "description": "Name of the event being queried.",
// "location": "query",
// "type": "string"
// },
// "maxResults": {
// "description": "Number of activity records to be shown in each page.",
// "format": "int32",
// "location": "query",
// "maximum": "1000",
// "minimum": "1",
// "type": "integer"
// },
// "startTime": {
// "description": "Return events which occured at or after this time.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "{customerId}/{applicationId}",
// "response": {
// "$ref": "Activities"
// }
// }
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,922 @@
{
"kind": "discovery#restDescription",
"etag": "\"kEk3sFj6Ef5_yR1-H3bAO6qw9mI/7OUX8PWQu-_Ueqls9RjxxnFExMI\"",
"discoveryVersion": "v1",
"id": "blogger:v2",
"name": "blogger",
"version": "v2",
"title": "Blogger API",
"description": "API for access to the data within Blogger.",
"ownerDomain": "google.com",
"ownerName": "Google",
"icons": {
"x16": "http://www.google.com/images/icons/product/blogger-16.png",
"x32": "http://www.google.com/images/icons/product/blogger-32.png"
},
"documentationLink": "https://developers.google.com/blogger/docs/2.0/json/getting_started",
"labels": [
"limited_availability"
],
"protocol": "rest",
"baseUrl": "https://www.googleapis.com/blogger/v2/",
"basePath": "/blogger/v2/",
"rootUrl": "https://www.googleapis.com/",
"servicePath": "blogger/v2/",
"batchPath": "batch",
"parameters": {
"alt": {
"type": "string",
"description": "Data format for the response.",
"default": "json",
"enum": [
"json"
],
"enumDescriptions": [
"Responses with Content-Type of application/json"
],
"location": "query"
},
"fields": {
"type": "string",
"description": "Selector specifying which fields to include in a partial response.",
"location": "query"
},
"key": {
"type": "string",
"description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.",
"location": "query"
},
"oauth_token": {
"type": "string",
"description": "OAuth 2.0 token for the current user.",
"location": "query"
},
"prettyPrint": {
"type": "boolean",
"description": "Returns response with indentations and line breaks.",
"default": "true",
"location": "query"
},
"quotaUser": {
"type": "string",
"description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.",
"location": "query"
},
"userIp": {
"type": "string",
"description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.",
"location": "query"
}
},
"auth": {
"oauth2": {
"scopes": {
"https://www.googleapis.com/auth/blogger": {
"description": "Manage your Blogger account"
}
}
}
},
"schemas": {
"Blog": {
"id": "Blog",
"type": "object",
"properties": {
"description": {
"type": "string",
"description": "The description of this blog. This is displayed underneath the title."
},
"id": {
"type": "string",
"description": "The identifier for this resource.",
"format": "int64"
},
"kind": {
"type": "string",
"description": "The kind of this entry. Always blogger#blog",
"default": "blogger#blog"
},
"locale": {
"type": "object",
"description": "The locale this Blog is set to.",
"properties": {
"country": {
"type": "string",
"description": "The country this blog's locale is set to."
},
"language": {
"type": "string",
"description": "The language this blog is authored in."
},
"variant": {
"type": "string",
"description": "The language variant this blog is authored in."
}
}
},
"name": {
"type": "string",
"description": "The name of this blog. This is displayed as the title."
},
"pages": {
"type": "object",
"description": "The container of pages in this blog.",
"properties": {
"selfLink": {
"type": "string",
"description": "The URL of the container for pages in this blog."
},
"totalItems": {
"type": "integer",
"description": "The count of pages in this blog.",
"format": "int32"
}
}
},
"posts": {
"type": "object",
"description": "The container of posts in this blog.",
"properties": {
"selfLink": {
"type": "string",
"description": "The URL of the container for posts in this blog."
},
"totalItems": {
"type": "integer",
"description": "The count of posts in this blog.",
"format": "int32"
}
}
},
"published": {
"type": "string",
"description": "RFC 3339 date-time when this blog was published.",
"format": "date-time"
},
"selfLink": {
"type": "string",
"description": "The API REST URL to fetch this resource from."
},
"updated": {
"type": "string",
"description": "RFC 3339 date-time when this blog was last updated.",
"format": "date-time"
},
"url": {
"type": "string",
"description": "The URL where this blog is published."
}
}
},
"BlogList": {
"id": "BlogList",
"type": "object",
"properties": {
"items": {
"type": "array",
"description": "The list of Blogs this user has Authorship or Admin rights over.",
"items": {
"$ref": "Blog"
}
},
"kind": {
"type": "string",
"description": "The kind of this entity. Always blogger#blogList",
"default": "blogger#blogList"
}
}
},
"Comment": {
"id": "Comment",
"type": "object",
"properties": {
"author": {
"type": "object",
"description": "The author of this Comment.",
"properties": {
"displayName": {
"type": "string",
"description": "The display name."
},
"id": {
"type": "string",
"description": "The identifier of the Comment creator."
},
"image": {
"type": "object",
"description": "The comment creator's avatar.",
"properties": {
"url": {
"type": "string",
"description": "The comment creator's avatar URL."
}
}
},
"url": {
"type": "string",
"description": "The URL of the Comment creator's Profile page."
}
}
},
"blog": {
"type": "object",
"description": "Data about the blog containing this comment.",
"properties": {
"id": {
"type": "string",
"description": "The identifier of the blog containing this comment.",
"format": "int64"
}
}
},
"content": {
"type": "string",
"description": "The actual content of the comment. May include HTML markup."
},
"id": {
"type": "string",
"description": "The identifier for this resource.",
"format": "int64"
},
"inReplyTo": {
"type": "object",
"description": "Data about the comment this is in reply to.",
"properties": {
"id": {
"type": "string",
"description": "The identified of the parent of this comment.",
"format": "int64"
}
}
},
"kind": {
"type": "string",
"description": "The kind of this entry. Always blogger#comment",
"default": "blogger#comment"
},
"post": {
"type": "object",
"description": "Data about the post containing this comment.",
"properties": {
"id": {
"type": "string",
"description": "The identifier of the post containing this comment.",
"format": "int64"
}
}
},
"published": {
"type": "string",
"description": "RFC 3339 date-time when this comment was published.",
"format": "date-time"
},
"selfLink": {
"type": "string",
"description": "The API REST URL to fetch this resource from."
},
"updated": {
"type": "string",
"description": "RFC 3339 date-time when this comment was last updated.",
"format": "date-time"
}
}
},
"CommentList": {
"id": "CommentList",
"type": "object",
"properties": {
"items": {
"type": "array",
"description": "The List of Comments for a Post.",
"items": {
"$ref": "Comment"
}
},
"kind": {
"type": "string",
"description": "The kind of this entry. Always blogger#commentList",
"default": "blogger#commentList"
},
"nextPageToken": {
"type": "string",
"description": "Pagination token to fetch the next page, if one exists."
},
"prevPageToken": {
"type": "string",
"description": "Pagination token to fetch the previous page, if one exists."
}
}
},
"Page": {
"id": "Page",
"type": "object",
"properties": {
"author": {
"type": "object",
"description": "The author of this Page.",
"properties": {
"displayName": {
"type": "string",
"description": "The display name."
},
"id": {
"type": "string",
"description": "The identifier of the Page creator."
},
"image": {
"type": "object",
"description": "The page author's avatar.",
"properties": {
"url": {
"type": "string",
"description": "The page author's avatar URL."
}
}
},
"url": {
"type": "string",
"description": "The URL of the Page creator's Profile page."
}
}
},
"blog": {
"type": "object",
"description": "Data about the blog containing this Page.",
"properties": {
"id": {
"type": "string",
"description": "The identifier of the blog containing this page.",
"format": "int64"
}
}
},
"content": {
"type": "string",
"description": "The body content of this Page, in HTML."
},
"id": {
"type": "string",
"description": "The identifier for this resource.",
"format": "int64"
},
"kind": {
"type": "string",
"description": "The kind of this entity. Always blogger#page",
"default": "blogger#page"
},
"published": {
"type": "string",
"description": "RFC 3339 date-time when this Page was published.",
"format": "date-time"
},
"selfLink": {
"type": "string",
"description": "The API REST URL to fetch this resource from."
},
"title": {
"type": "string",
"description": "The title of this entity. This is the name displayed in the Admin user interface."
},
"updated": {
"type": "string",
"description": "RFC 3339 date-time when this Page was last updated.",
"format": "date-time"
},
"url": {
"type": "string",
"description": "The URL that this Page is displayed at."
}
}
},
"PageList": {
"id": "PageList",
"type": "object",
"properties": {
"items": {
"type": "array",
"description": "The list of Pages for a Blog.",
"items": {
"$ref": "Page"
}
},
"kind": {
"type": "string",
"description": "The kind of this entity. Always blogger#pageList",
"default": "blogger#pageList"
}
}
},
"Post": {
"id": "Post",
"type": "object",
"properties": {
"author": {
"type": "object",
"description": "The author of this Post.",
"properties": {
"displayName": {
"type": "string",
"description": "The display name."
},
"id": {
"type": "string",
"description": "The identifier of the Post creator."
},
"image": {
"type": "object",
"description": "The Post author's avatar.",
"properties": {
"url": {
"type": "string",
"description": "The Post author's avatar URL."
}
}
},
"url": {
"type": "string",
"description": "The URL of the Post creator's Profile page."
}
}
},
"blog": {
"type": "object",
"description": "Data about the blog containing this Post.",
"properties": {
"id": {
"type": "string",
"description": "The identifier of the Blog that contains this Post.",
"format": "int64"
}
}
},
"content": {
"type": "string",
"description": "The content of the Post. May contain HTML markup."
},
"id": {
"type": "string",
"description": "The identifier of this Post.",
"format": "int64"
},
"kind": {
"type": "string",
"description": "The kind of this entity. Always blogger#post",
"default": "blogger#post"
},
"labels": {
"type": "array",
"description": "The list of labels this Post was tagged with.",
"items": {
"type": "string"
}
},
"published": {
"type": "string",
"description": "RFC 3339 date-time when this Post was published.",
"format": "date-time"
},
"replies": {
"type": "object",
"description": "The container of comments on this Post.",
"properties": {
"selfLink": {
"type": "string",
"description": "The URL of the comments on this post."
},
"totalItems": {
"type": "string",
"description": "The count of comments on this post.",
"format": "int64"
}
}
},
"selfLink": {
"type": "string",
"description": "The API REST URL to fetch this resource from."
},
"title": {
"type": "string",
"description": "The title of the Post."
},
"updated": {
"type": "string",
"description": "RFC 3339 date-time when this Post was last updated.",
"format": "date-time"
},
"url": {
"type": "string",
"description": "The URL where this Post is displayed."
}
}
},
"PostList": {
"id": "PostList",
"type": "object",
"properties": {
"items": {
"type": "array",
"description": "The list of Posts for this Blog.",
"items": {
"$ref": "Post"
}
},
"kind": {
"type": "string",
"description": "The kind of this entity. Always blogger#postList",
"default": "blogger#postList"
},
"nextPageToken": {
"type": "string",
"description": "Pagination token to fetch the next page, if one exists."
},
"prevPageToken": {
"type": "string",
"description": "Pagination token to fetch the previous page, if one exists."
}
}
},
"User": {
"id": "User",
"type": "object",
"properties": {
"about": {
"type": "string",
"description": "Profile summary information."
},
"blogs": {
"type": "object",
"description": "The container of blogs for this user.",
"properties": {
"selfLink": {
"type": "string",
"description": "The URL of the Blogs for this user."
}
}
},
"created": {
"type": "string",
"description": "The timestamp of when this profile was created, in seconds since epoch.",
"format": "date-time"
},
"displayName": {
"type": "string",
"description": "The display name."
},
"id": {
"type": "string",
"description": "The identifier for this User."
},
"kind": {
"type": "string",
"description": "The kind of this entity. Always blogger#user",
"default": "blogger#user"
},
"locale": {
"type": "object",
"description": "This user's locale",
"properties": {
"country": {
"type": "string",
"description": "The user's country setting."
},
"language": {
"type": "string",
"description": "The user's language setting."
},
"variant": {
"type": "string",
"description": "The user's language variant setting."
}
}
},
"selfLink": {
"type": "string",
"description": "The API REST URL to fetch this resource from."
},
"url": {
"type": "string",
"description": "The user's profile page."
}
}
}
},
"resources": {
"blogs": {
"methods": {
"get": {
"id": "blogger.blogs.get",
"path": "blogs/{blogId}",
"httpMethod": "GET",
"description": "Gets one blog by id.",
"parameters": {
"blogId": {
"type": "string",
"description": "The ID of the blog to get.",
"required": true,
"location": "path"
}
},
"parameterOrder": [
"blogId"
],
"response": {
"$ref": "Blog"
},
"scopes": [
"https://www.googleapis.com/auth/blogger"
]
}
}
},
"comments": {
"methods": {
"get": {
"id": "blogger.comments.get",
"path": "blogs/{blogId}/posts/{postId}/comments/{commentId}",
"httpMethod": "GET",
"description": "Gets one comment by id.",
"parameters": {
"blogId": {
"type": "string",
"description": "ID of the blog to containing the comment.",
"required": true,
"location": "path"
},
"commentId": {
"type": "string",
"description": "The ID of the comment to get.",
"required": true,
"location": "path"
},
"postId": {
"type": "string",
"description": "ID of the post to fetch posts from.",
"required": true,
"location": "path"
}
},
"parameterOrder": [
"blogId",
"postId",
"commentId"
],
"response": {
"$ref": "Comment"
},
"scopes": [
"https://www.googleapis.com/auth/blogger"
]
},
"list": {
"id": "blogger.comments.list",
"path": "blogs/{blogId}/posts/{postId}/comments",
"httpMethod": "GET",
"description": "Retrieves the comments for a blog, possibly filtered.",
"parameters": {
"blogId": {
"type": "string",
"description": "ID of the blog to fetch comments from.",
"required": true,
"location": "path"
},
"fetchBodies": {
"type": "boolean",
"description": "Whether the body content of the comments is included.",
"location": "query"
},
"maxResults": {
"type": "integer",
"description": "Maximum number of comments to include in the result.",
"format": "uint32",
"location": "query"
},
"pageToken": {
"type": "string",
"description": "Continuation token if request is paged.",
"location": "query"
},
"postId": {
"type": "string",
"description": "ID of the post to fetch posts from.",
"required": true,
"location": "path"
},
"startDate": {
"type": "string",
"description": "Earliest date of comment to fetch, a date-time with RFC 3339 formatting.",
"format": "date-time",
"location": "query"
}
},
"parameterOrder": [
"blogId",
"postId"
],
"response": {
"$ref": "CommentList"
},
"scopes": [
"https://www.googleapis.com/auth/blogger"
]
}
}
},
"pages": {
"methods": {
"get": {
"id": "blogger.pages.get",
"path": "blogs/{blogId}/pages/{pageId}",
"httpMethod": "GET",
"description": "Gets one blog page by id.",
"parameters": {
"blogId": {
"type": "string",
"description": "ID of the blog containing the page.",
"required": true,
"location": "path"
},
"pageId": {
"type": "string",
"description": "The ID of the page to get.",
"required": true,
"location": "path"
}
},
"parameterOrder": [
"blogId",
"pageId"
],
"response": {
"$ref": "Page"
},
"scopes": [
"https://www.googleapis.com/auth/blogger"
]
},
"list": {
"id": "blogger.pages.list",
"path": "blogs/{blogId}/pages",
"httpMethod": "GET",
"description": "Retrieves pages for a blog, possibly filtered.",
"parameters": {
"blogId": {
"type": "string",
"description": "ID of the blog to fetch pages from.",
"required": true,
"location": "path"
},
"fetchBodies": {
"type": "boolean",
"description": "Whether to retrieve the Page bodies.",
"location": "query"
}
},
"parameterOrder": [
"blogId"
],
"response": {
"$ref": "PageList"
},
"scopes": [
"https://www.googleapis.com/auth/blogger"
]
}
}
},
"posts": {
"methods": {
"get": {
"id": "blogger.posts.get",
"path": "blogs/{blogId}/posts/{postId}",
"httpMethod": "GET",
"description": "Get a post by id.",
"parameters": {
"blogId": {
"type": "string",
"description": "ID of the blog to fetch the post from.",
"required": true,
"location": "path"
},
"postId": {
"type": "string",
"description": "The ID of the post",
"required": true,
"location": "path"
}
},
"parameterOrder": [
"blogId",
"postId"
],
"response": {
"$ref": "Post"
},
"scopes": [
"https://www.googleapis.com/auth/blogger"
]
},
"list": {
"id": "blogger.posts.list",
"path": "blogs/{blogId}/posts",
"httpMethod": "GET",
"description": "Retrieves a list of posts, possibly filtered.",
"parameters": {
"blogId": {
"type": "string",
"description": "ID of the blog to fetch posts from.",
"required": true,
"location": "path"
},
"fetchBodies": {
"type": "boolean",
"description": "Whether the body content of posts is included.",
"location": "query"
},
"maxResults": {
"type": "integer",
"description": "Maximum number of posts to fetch.",
"format": "uint32",
"location": "query"
},
"pageToken": {
"type": "string",
"description": "Continuation token if the request is paged.",
"location": "query"
},
"startDate": {
"type": "string",
"description": "Earliest post date to fetch, a date-time with RFC 3339 formatting.",
"format": "date-time",
"location": "query"
}
},
"parameterOrder": [
"blogId"
],
"response": {
"$ref": "PostList"
},
"scopes": [
"https://www.googleapis.com/auth/blogger"
]
}
}
},
"users": {
"methods": {
"get": {
"id": "blogger.users.get",
"path": "users/{userId}",
"httpMethod": "GET",
"description": "Gets one user by id.",
"parameters": {
"userId": {
"type": "string",
"description": "The ID of the user to get.",
"required": true,
"location": "path"
}
},
"parameterOrder": [
"userId"
],
"response": {
"$ref": "User"
},
"scopes": [
"https://www.googleapis.com/auth/blogger"
]
}
},
"resources": {
"blogs": {
"methods": {
"list": {
"id": "blogger.users.blogs.list",
"path": "users/{userId}/blogs",
"httpMethod": "GET",
"description": "Retrieves a list of blogs, possibly filtered.",
"parameters": {
"userId": {
"type": "string",
"description": "ID of the user whose blogs are to be fetched. Either the word 'self' (sans quote marks) or the user's profile identifier.",
"required": true,
"location": "path"
}
},
"parameterOrder": [
"userId"
],
"response": {
"$ref": "BlogList"
},
"scopes": [
"https://www.googleapis.com/auth/blogger"
]
}
}
}
}
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,11 @@
#!/bin/sh
set -e
make -C google-api install
make -C google-api-go-generator install
google-api-go-generator/google-api-go-gen -cache -api=tasks:v1
google-api-go-generator/google-api-go-gen -cache -api=urlshortener:v1
make -C tasks/v1 install
make -C urlshortener/v1 install
make -C examples

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,839 @@
{
"kind": "discovery#restDescription",
"etag": "\"kEk3sFj6Ef5_yR1-H3bAO6qw9mI/fgmSCrAaA7mxBfjU-xmYlE1C4zQ\"",
"discoveryVersion": "v1",
"id": "civicinfo:us_v1",
"name": "civicinfo",
"canonicalName": "Civic Info",
"version": "us_v1",
"title": "Google Civic Information API",
"description": "An API for accessing civic information.",
"ownerDomain": "google.com",
"ownerName": "Google",
"icons": {
"x16": "http://www.google.com/images/icons/product/search-16.gif",
"x32": "http://www.google.com/images/icons/product/search-32.gif"
},
"documentationLink": "https://developers.google.com/civic-information",
"protocol": "rest",
"baseUrl": "https://www.googleapis.com/civicinfo/us_v1/",
"basePath": "/civicinfo/us_v1/",
"rootUrl": "https://www.googleapis.com/",
"servicePath": "civicinfo/us_v1/",
"batchPath": "batch",
"parameters": {
"alt": {
"type": "string",
"description": "Data format for the response.",
"default": "json",
"enum": [
"json"
],
"enumDescriptions": [
"Responses with Content-Type of application/json"
],
"location": "query"
},
"fields": {
"type": "string",
"description": "Selector specifying which fields to include in a partial response.",
"location": "query"
},
"key": {
"type": "string",
"description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.",
"location": "query"
},
"oauth_token": {
"type": "string",
"description": "OAuth 2.0 token for the current user.",
"location": "query"
},
"prettyPrint": {
"type": "boolean",
"description": "Returns response with indentations and line breaks.",
"default": "true",
"location": "query"
},
"quotaUser": {
"type": "string",
"description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.",
"location": "query"
},
"userIp": {
"type": "string",
"description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.",
"location": "query"
}
},
"schemas": {
"AdministrationRegion": {
"id": "AdministrationRegion",
"type": "object",
"description": "Describes information about a regional election administrative area.",
"properties": {
"electionAdministrationBody": {
"$ref": "AdministrativeBody",
"description": "The election administration body for this area."
},
"id": {
"type": "string",
"description": "An ID for this object. IDs may change in future requests and should not be cached. Access to this field requires special access that can be requested from the Request more link on the Quotas page."
},
"local_jurisdiction": {
"$ref": "AdministrationRegion",
"description": "The city or county that provides election information for this voter. This object can have the same elements as state."
},
"name": {
"type": "string",
"description": "The name of the jurisdiction."
},
"sources": {
"type": "array",
"description": "A list of sources for this area. If multiple sources are listed the data has been aggregated from those sources.",
"items": {
"$ref": "Source"
}
}
}
},
"AdministrativeBody": {
"id": "AdministrativeBody",
"type": "object",
"description": "Information about an election administrative body (e.g. County Board of Elections).",
"properties": {
"absenteeVotingInfoUrl": {
"type": "string",
"description": "A URL provided by this administrative body for information on absentee voting."
},
"ballotInfoUrl": {
"type": "string",
"description": "A URL provided by this administrative body to give contest information to the voter."
},
"correspondenceAddress": {
"$ref": "SimpleAddressType",
"description": "The mailing address of this administrative body."
},
"electionInfoUrl": {
"type": "string",
"description": "A URL provided by this administrative body for looking up general election information."
},
"electionOfficials": {
"type": "array",
"description": "The election officials for this election administrative body.",
"items": {
"$ref": "ElectionOfficial"
}
},
"electionRegistrationConfirmationUrl": {
"type": "string",
"description": "A URL provided by this administrative body for confirming that the voter is registered to vote."
},
"electionRegistrationUrl": {
"type": "string",
"description": "A URL provided by this administrative body for looking up how to register to vote."
},
"electionRulesUrl": {
"type": "string",
"description": "A URL provided by this administrative body describing election rules to the voter."
},
"hoursOfOperation": {
"type": "string",
"description": "A description of the hours of operation for this administrative body."
},
"name": {
"type": "string",
"description": "The name of this election administrative body."
},
"physicalAddress": {
"$ref": "SimpleAddressType",
"description": "The physical address of this administrative body."
},
"voter_services": {
"type": "array",
"description": "A description of the services this administrative body may provide.",
"items": {
"type": "string"
}
},
"votingLocationFinderUrl": {
"type": "string",
"description": "A URL provided by this administrative body for looking up where to vote."
}
}
},
"Candidate": {
"id": "Candidate",
"type": "object",
"description": "Information about a candidate running for elected office.",
"properties": {
"candidateUrl": {
"type": "string",
"description": "The URL for the candidate's campaign web site."
},
"channels": {
"type": "array",
"description": "A list of known (social) media channels for this candidate.",
"items": {
"$ref": "Channel"
}
},
"email": {
"type": "string",
"description": "The email address for the candidate's campaign."
},
"name": {
"type": "string",
"description": "The candidate's name."
},
"orderOnBallot": {
"type": "string",
"description": "The order the candidate appears on the ballot for this contest.",
"format": "int64"
},
"party": {
"type": "string",
"description": "The full name of the party the candidate is a member of."
},
"phone": {
"type": "string",
"description": "The voice phone number for the candidate's campaign office."
},
"photoUrl": {
"type": "string",
"description": "A URL for a photo of the candidate."
}
}
},
"Channel": {
"id": "Channel",
"type": "object",
"description": "A social media or web channel for a candidate.",
"properties": {
"id": {
"type": "string",
"description": "The unique public identifier for the candidate's channel."
},
"type": {
"type": "string",
"description": "The type of channel. The following is a list of types of channels, but is not exhaustive. More channel types may be added at a later time. One of: GooglePlus, YouTube, Facebook, Twitter"
}
}
},
"Contest": {
"id": "Contest",
"type": "object",
"description": "Information about a contest that appears on a voter's ballot.",
"properties": {
"ballotPlacement": {
"type": "string",
"description": "A number specifying the position of this contest on the voter's ballot.",
"format": "int64"
},
"candidates": {
"type": "array",
"description": "The candidate choices for this contest.",
"items": {
"$ref": "Candidate"
}
},
"district": {
"$ref": "ElectoralDistrict",
"description": "Information about the electoral district that this contest is in."
},
"electorateSpecifications": {
"type": "string",
"description": "A description of any additional eligibility requirements for voting in this contest."
},
"id": {
"type": "string",
"description": "An ID for this object. IDs may change in future requests and should not be cached. Access to this field requires special access that can be requested from the Request more link on the Quotas page."
},
"level": {
"type": "string",
"description": "The level of office for this contest. One of: federal, state, county, city, other"
},
"numberElected": {
"type": "string",
"description": "The number of candidates that will be elected to office in this contest.",
"format": "int64"
},
"numberVotingFor": {
"type": "string",
"description": "The number of candidates that a voter may vote for in this contest.",
"format": "int64"
},
"office": {
"type": "string",
"description": "The name of the office for this contest."
},
"primaryParty": {
"type": "string",
"description": "If this is a partisan election, the name of the party it is for."
},
"referendumSubtitle": {
"type": "string",
"description": "A brief description of the referendum. This field is only populated for contests of type 'Referendum'."
},
"referendumTitle": {
"type": "string",
"description": "The title of the referendum (e.g. 'Proposition 42'). This field is only populated for contests of type 'Referendum'."
},
"referendumUrl": {
"type": "string",
"description": "A link to the referendum. This field is only populated for contests of type 'Referendum'."
},
"sources": {
"type": "array",
"description": "A list of sources for this contest. If multiple sources are listed, the data has been aggregated from those sources.",
"items": {
"$ref": "Source"
}
},
"special": {
"type": "string",
"description": "\"Yes\" or \"No\" depending on whether this a contest being held outside the normal election cycle."
},
"type": {
"type": "string",
"description": "The type of contest. Usually this will be 'General', 'Primary', or 'Run-off' for contests with candidates. For referenda this will be 'Referendum'."
}
}
},
"DivisionSearchResponse": {
"id": "DivisionSearchResponse",
"type": "object",
"description": "The result of a division search query.",
"properties": {
"kind": {
"type": "string",
"description": "Identifies what kind of resource this is. Value: the fixed string \"civicinfo#divisionSearchResponse\".",
"default": "civicinfo#divisionSearchResponse"
},
"results": {
"type": "array",
"items": {
"$ref": "DivisionSearchResult"
}
},
"status": {
"type": "string",
"description": "The result of the request. One of: success, addressUnparseable, noAddressParameter, internalLookupFailure"
}
}
},
"DivisionSearchResult": {
"id": "DivisionSearchResult",
"type": "object",
"description": "Represents a political geographic division that matches the requested query.",
"properties": {
"name": {
"type": "string",
"description": "The name of the division."
},
"ocdId": {
"type": "string",
"description": "The unique Open Civic Data identifier for this division."
}
}
},
"Election": {
"id": "Election",
"type": "object",
"description": "Information about the election that was queried.",
"properties": {
"electionDay": {
"type": "string",
"description": "Day of the election in YYYY-MM-DD format."
},
"id": {
"type": "string",
"description": "The unique ID of this election.",
"format": "int64"
},
"name": {
"type": "string",
"description": "A displayable name for the election."
}
}
},
"ElectionOfficial": {
"id": "ElectionOfficial",
"type": "object",
"description": "Information about individual election officials.",
"properties": {
"emailAddress": {
"type": "string",
"description": "The email address of the election official."
},
"faxNumber": {
"type": "string",
"description": "The fax number of the election official."
},
"name": {
"type": "string",
"description": "The full name of the election official."
},
"officePhoneNumber": {
"type": "string",
"description": "The office phone number of the election official."
},
"title": {
"type": "string",
"description": "The title of the election official."
}
}
},
"ElectionsQueryResponse": {
"id": "ElectionsQueryResponse",
"type": "object",
"description": "The list of elections available for this version of the API.",
"properties": {
"elections": {
"type": "array",
"description": "A list of available elections",
"items": {
"$ref": "Election"
}
},
"kind": {
"type": "string",
"description": "Identifies what kind of resource this is. Value: the fixed string \"civicinfo#electionsQueryResponse\".",
"default": "civicinfo#electionsQueryResponse"
}
}
},
"ElectoralDistrict": {
"id": "ElectoralDistrict",
"type": "object",
"description": "Describes the geographic scope of a contest.",
"properties": {
"id": {
"type": "string",
"description": "An identifier for this district, relative to its scope. For example, the 34th State Senate district would have id \"34\" and a scope of stateUpper."
},
"name": {
"type": "string",
"description": "The name of the district."
},
"scope": {
"type": "string",
"description": "The geographic scope of this district. If unspecified the district's geography is not known. One of: national, statewide, congressional, stateUpper, stateLower, countywide, judicial, schoolBoard, cityWide, township, countyCouncil, cityCouncil, ward, special"
}
}
},
"GeographicDivision": {
"id": "GeographicDivision",
"type": "object",
"description": "Describes a political geography.",
"properties": {
"name": {
"type": "string",
"description": "The name of the division."
},
"officeIds": {
"type": "array",
"description": "List of keys in the offices object, one for each office elected from this division. Will only be present if includeOffices was true (or absent) in the request.",
"items": {
"type": "string"
}
},
"scope": {
"type": "string",
"description": "The geographic scope of the division. If unspecified, the division's geography is not known. One of: national, statewide, congressional, stateUpper, stateLower, countywide, judicial, schoolBoard, cityWide, township, countyCouncil, cityCouncil, ward, special"
}
}
},
"Office": {
"id": "Office",
"type": "object",
"description": "Information about an Office held by one or more Officials.",
"properties": {
"level": {
"type": "string",
"description": "The level of this elected office. One of: federal, state, county, city, other"
},
"name": {
"type": "string",
"description": "The human-readable name of the office."
},
"officialIds": {
"type": "array",
"description": "List of people who presently hold the office.",
"items": {
"type": "string"
}
},
"sources": {
"type": "array",
"description": "A list of sources for this office. If multiple sources are listed, the data has been aggregated from those sources.",
"items": {
"$ref": "Source"
}
}
}
},
"Official": {
"id": "Official",
"type": "object",
"description": "Information about a official holding an elected office.",
"properties": {
"address": {
"type": "array",
"description": "Addresses at which to contact the official.",
"items": {
"$ref": "SimpleAddressType"
}
},
"channels": {
"type": "array",
"description": "A list of known (social) media channels for this official.",
"items": {
"$ref": "Channel"
}
},
"emails": {
"type": "array",
"description": "The direct email addresses for the official.",
"items": {
"type": "string"
}
},
"name": {
"type": "string",
"description": "The official's name."
},
"party": {
"type": "string",
"description": "The full name of the party the official belongs to."
},
"phones": {
"type": "array",
"description": "The official's public contact phone numbers.",
"items": {
"type": "string"
}
},
"photoUrl": {
"type": "string",
"description": "A URL for a photo of the official."
},
"urls": {
"type": "array",
"description": "The official's public website URLs.",
"items": {
"type": "string"
}
}
}
},
"PollingLocation": {
"id": "PollingLocation",
"type": "object",
"description": "A location where a voter can vote. This may be an early vote site or an election day voting location.",
"properties": {
"address": {
"$ref": "SimpleAddressType",
"description": "The address of the location"
},
"endDate": {
"type": "string",
"description": "The last date that this early vote site may be used. This field is not populated for polling locations."
},
"id": {
"type": "string",
"description": "An ID for this object. IDs may change in future requests and should not be cached. Access to this field requires special access that can be requested from the Request more link on the Quotas page."
},
"name": {
"type": "string",
"description": "The name of the early vote site. This field is not populated for polling locations."
},
"notes": {
"type": "string",
"description": "Notes about this location (e.g. accessibility ramp or entrance to use)"
},
"pollingHours": {
"type": "string",
"description": "A description of when this location is open."
},
"sources": {
"type": "array",
"description": "A list of sources for this location. If multiple sources are listed the data has been aggregated from those sources.",
"items": {
"$ref": "Source"
}
},
"startDate": {
"type": "string",
"description": "The first date that this early vote site may be used. This field is not populated for polling locations."
},
"voterServices": {
"type": "string",
"description": "The services provided by this early vote site. This field is not populated for polling locations."
}
}
},
"RepresentativeInfoRequest": {
"id": "RepresentativeInfoRequest",
"type": "object",
"description": "A request for political geography and representative information for an address.",
"properties": {
"address": {
"type": "string",
"description": "The address to look up. May only be specified if the field ocdId is not given in the URL."
}
}
},
"RepresentativeInfoResponse": {
"id": "RepresentativeInfoResponse",
"type": "object",
"description": "The result of a representative info lookup query.",
"properties": {
"divisions": {
"type": "object",
"description": "Political geographic divisions that contain the requested address.",
"additionalProperties": {
"$ref": "GeographicDivision",
"description": "The unique Open Civic Data identifier for this division."
}
},
"kind": {
"type": "string",
"description": "Identifies what kind of resource this is. Value: the fixed string \"civicinfo#representativeInfoResponse\".",
"default": "civicinfo#representativeInfoResponse"
},
"normalizedInput": {
"$ref": "SimpleAddressType",
"description": "The normalized version of the requested address"
},
"offices": {
"type": "object",
"description": "Elected offices referenced by the divisions listed above. Will only be present if includeOffices was true in the request.",
"additionalProperties": {
"$ref": "Office",
"description": "A unique identifier for this office, within the context of this request. Identifiers are *not* long-lived: the same office may get different IDs on different requests."
}
},
"officials": {
"type": "object",
"description": "Officials holding the offices listed above. Will only be present if includeOffices was true in the request.",
"additionalProperties": {
"$ref": "Official",
"description": "A unique identifier for this official, within the context of this request. Identifiers are *not* long-lived: the same official may get different IDs on different requests."
}
},
"status": {
"type": "string",
"description": "The result of the request. One of: success, noStreetSegmentFound, addressUnparseable, noAddressParameter, multipleStreetSegmentsFound, electionOver, electionUnknown, internalLookupFailure, RequestedBothAddressAndOcdId"
}
}
},
"SimpleAddressType": {
"id": "SimpleAddressType",
"type": "object",
"description": "A simple representation of an address.",
"properties": {
"city": {
"type": "string",
"description": "The city or town for the address."
},
"line1": {
"type": "string",
"description": "The street name and number of this address."
},
"line2": {
"type": "string",
"description": "The second line the address, if needed."
},
"line3": {
"type": "string",
"description": "The third line of the address, if needed."
},
"locationName": {
"type": "string",
"description": "The name of the location."
},
"state": {
"type": "string",
"description": "The US two letter state abbreviation of the address."
},
"zip": {
"type": "string",
"description": "The US Postal Zip Code of the address."
}
}
},
"Source": {
"id": "Source",
"type": "object",
"description": "Contains information about the data source for the element containing it.",
"properties": {
"name": {
"type": "string",
"description": "The name of the data source."
},
"official": {
"type": "boolean",
"description": "Whether this data comes from an official government source."
}
}
},
"VoterInfoRequest": {
"id": "VoterInfoRequest",
"type": "object",
"description": "A request for information about a voter.",
"properties": {
"address": {
"type": "string",
"description": "The registered address of the voter to look up."
}
}
},
"VoterInfoResponse": {
"id": "VoterInfoResponse",
"type": "object",
"description": "The result of a voter info lookup query.",
"properties": {
"contests": {
"type": "array",
"description": "Contests that will appear on the voter's ballot",
"items": {
"$ref": "Contest"
}
},
"earlyVoteSites": {
"type": "array",
"description": "Locations where the voter is eligible to vote early, prior to election day",
"items": {
"$ref": "PollingLocation"
}
},
"election": {
"$ref": "Election",
"description": "The election that was queried."
},
"kind": {
"type": "string",
"description": "Identifies what kind of resource this is. Value: the fixed string \"civicinfo#voterInfoResponse\".",
"default": "civicinfo#voterInfoResponse"
},
"normalizedInput": {
"$ref": "SimpleAddressType",
"description": "The normalized version of the requested address"
},
"pollingLocations": {
"type": "array",
"description": "Locations where the voter is eligible to vote on election day. For states with mail-in voting only, these locations will be nearby drop box locations. Drop box locations are free to the voter and may be used instead of placing the ballot in the mail.",
"items": {
"$ref": "PollingLocation"
}
},
"state": {
"type": "array",
"description": "Local Election Information for the state that the voter votes in. For the US, there will only be one element in this array.",
"items": {
"$ref": "AdministrationRegion"
}
},
"status": {
"type": "string",
"description": "The result of the request. One of: success, noStreetSegmentFound, addressUnparseable, noAddressParameter, multipleStreetSegmentsFound, electionOver, electionUnknown, internalLookupFailure"
}
}
}
},
"resources": {
"divisions": {
"methods": {
"search": {
"id": "civicinfo.divisions.search",
"path": "representatives/division_search",
"httpMethod": "GET",
"description": "Searches for political divisions by their natural name or OCD ID.",
"parameters": {
"query": {
"type": "string",
"description": "The search query. Queries can cover any parts of a OCD ID or a human readable division name. All words given in the query are treated as required patterns. In addition to that, most query operators of the Apache Lucene library are supported. See http://lucene.apache.org/core/2_9_4/queryparsersyntax.html",
"location": "query"
}
},
"response": {
"$ref": "DivisionSearchResponse"
}
}
}
},
"elections": {
"methods": {
"electionQuery": {
"id": "civicinfo.elections.electionQuery",
"path": "elections",
"httpMethod": "GET",
"description": "List of available elections to query.",
"response": {
"$ref": "ElectionsQueryResponse"
}
},
"voterInfoQuery": {
"id": "civicinfo.elections.voterInfoQuery",
"path": "voterinfo/{electionId}/lookup",
"httpMethod": "POST",
"description": "Looks up information relevant to a voter based on the voter's registered address.",
"parameters": {
"electionId": {
"type": "string",
"description": "The unique ID of the election to look up. A list of election IDs can be obtained at https://www.googleapis.com/civicinfo/{version}/elections",
"required": true,
"format": "int64",
"location": "path"
},
"officialOnly": {
"type": "boolean",
"description": "If set to true, only data from official state sources will be returned.",
"default": "false",
"location": "query"
}
},
"parameterOrder": [
"electionId"
],
"request": {
"$ref": "VoterInfoRequest"
},
"response": {
"$ref": "VoterInfoResponse"
}
}
}
},
"representatives": {
"methods": {
"representativeInfoQuery": {
"id": "civicinfo.representatives.representativeInfoQuery",
"path": "representatives/lookup",
"httpMethod": "POST",
"description": "Looks up political geography and (optionally) representative information based on an address.",
"parameters": {
"includeOffices": {
"type": "boolean",
"description": "Whether to return information about offices and officials. If false, only the top-level district information will be returned.",
"default": "true",
"location": "query"
},
"ocdId": {
"type": "string",
"description": "The division to look up. May only be specified if the address field is not given in the request body.",
"location": "query"
}
},
"request": {
"$ref": "RepresentativeInfoRequest"
},
"response": {
"$ref": "RepresentativeInfoResponse"
}
}
}
}
}
}

View File

@ -0,0 +1,851 @@
// Package civicinfo provides access to the Google Civic Information API.
//
// See https://developers.google.com/civic-information
//
// Usage example:
//
// import "code.google.com/p/google-api-go-client/civicinfo/us_v1"
// ...
// civicinfoService, err := civicinfo.New(oauthHttpClient)
package civicinfo
import (
"bytes"
"code.google.com/p/google-api-go-client/googleapi"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
)
// Always reference these packages, just in case the auto-generated code
// below doesn't.
var _ = bytes.NewBuffer
var _ = strconv.Itoa
var _ = fmt.Sprintf
var _ = json.NewDecoder
var _ = io.Copy
var _ = url.Parse
var _ = googleapi.Version
var _ = errors.New
var _ = strings.Replace
const apiId = "civicinfo:us_v1"
const apiName = "civicinfo"
const apiVersion = "us_v1"
const basePath = "https://www.googleapis.com/civicinfo/us_v1/"
func New(client *http.Client) (*Service, error) {
if client == nil {
return nil, errors.New("client is nil")
}
s := &Service{client: client, BasePath: basePath}
s.Divisions = NewDivisionsService(s)
s.Elections = NewElectionsService(s)
s.Representatives = NewRepresentativesService(s)
return s, nil
}
type Service struct {
client *http.Client
BasePath string // API endpoint base URL
Divisions *DivisionsService
Elections *ElectionsService
Representatives *RepresentativesService
}
func NewDivisionsService(s *Service) *DivisionsService {
rs := &DivisionsService{s: s}
return rs
}
type DivisionsService struct {
s *Service
}
func NewElectionsService(s *Service) *ElectionsService {
rs := &ElectionsService{s: s}
return rs
}
type ElectionsService struct {
s *Service
}
func NewRepresentativesService(s *Service) *RepresentativesService {
rs := &RepresentativesService{s: s}
return rs
}
type RepresentativesService struct {
s *Service
}
type AdministrationRegion struct {
// ElectionAdministrationBody: The election administration body for this
// area.
ElectionAdministrationBody *AdministrativeBody `json:"electionAdministrationBody,omitempty"`
// Id: An ID for this object. IDs may change in future requests and
// should not be cached. Access to this field requires special access
// that can be requested from the Request more link on the Quotas page.
Id string `json:"id,omitempty"`
// Local_jurisdiction: The city or county that provides election
// information for this voter. This object can have the same elements as
// state.
Local_jurisdiction *AdministrationRegion `json:"local_jurisdiction,omitempty"`
// Name: The name of the jurisdiction.
Name string `json:"name,omitempty"`
// Sources: A list of sources for this area. If multiple sources are
// listed the data has been aggregated from those sources.
Sources []*Source `json:"sources,omitempty"`
}
type AdministrativeBody struct {
// AbsenteeVotingInfoUrl: A URL provided by this administrative body for
// information on absentee voting.
AbsenteeVotingInfoUrl string `json:"absenteeVotingInfoUrl,omitempty"`
// BallotInfoUrl: A URL provided by this administrative body to give
// contest information to the voter.
BallotInfoUrl string `json:"ballotInfoUrl,omitempty"`
// CorrespondenceAddress: The mailing address of this administrative
// body.
CorrespondenceAddress *SimpleAddressType `json:"correspondenceAddress,omitempty"`
// ElectionInfoUrl: A URL provided by this administrative body for
// looking up general election information.
ElectionInfoUrl string `json:"electionInfoUrl,omitempty"`
// ElectionOfficials: The election officials for this election
// administrative body.
ElectionOfficials []*ElectionOfficial `json:"electionOfficials,omitempty"`
// ElectionRegistrationConfirmationUrl: A URL provided by this
// administrative body for confirming that the voter is registered to
// vote.
ElectionRegistrationConfirmationUrl string `json:"electionRegistrationConfirmationUrl,omitempty"`
// ElectionRegistrationUrl: A URL provided by this administrative body
// for looking up how to register to vote.
ElectionRegistrationUrl string `json:"electionRegistrationUrl,omitempty"`
// ElectionRulesUrl: A URL provided by this administrative body
// describing election rules to the voter.
ElectionRulesUrl string `json:"electionRulesUrl,omitempty"`
// HoursOfOperation: A description of the hours of operation for this
// administrative body.
HoursOfOperation string `json:"hoursOfOperation,omitempty"`
// Name: The name of this election administrative body.
Name string `json:"name,omitempty"`
// PhysicalAddress: The physical address of this administrative body.
PhysicalAddress *SimpleAddressType `json:"physicalAddress,omitempty"`
// Voter_services: A description of the services this administrative
// body may provide.
Voter_services []string `json:"voter_services,omitempty"`
// VotingLocationFinderUrl: A URL provided by this administrative body
// for looking up where to vote.
VotingLocationFinderUrl string `json:"votingLocationFinderUrl,omitempty"`
}
type Candidate struct {
// CandidateUrl: The URL for the candidate's campaign web site.
CandidateUrl string `json:"candidateUrl,omitempty"`
// Channels: A list of known (social) media channels for this candidate.
Channels []*Channel `json:"channels,omitempty"`
// Email: The email address for the candidate's campaign.
Email string `json:"email,omitempty"`
// Name: The candidate's name.
Name string `json:"name,omitempty"`
// OrderOnBallot: The order the candidate appears on the ballot for this
// contest.
OrderOnBallot int64 `json:"orderOnBallot,omitempty,string"`
// Party: The full name of the party the candidate is a member of.
Party string `json:"party,omitempty"`
// Phone: The voice phone number for the candidate's campaign office.
Phone string `json:"phone,omitempty"`
// PhotoUrl: A URL for a photo of the candidate.
PhotoUrl string `json:"photoUrl,omitempty"`
}
type Channel struct {
// Id: The unique public identifier for the candidate's channel.
Id string `json:"id,omitempty"`
// Type: The type of channel. The following is a list of types of
// channels, but is not exhaustive. More channel types may be added at a
// later time. One of: GooglePlus, YouTube, Facebook, Twitter
Type string `json:"type,omitempty"`
}
type Contest struct {
// BallotPlacement: A number specifying the position of this contest on
// the voter's ballot.
BallotPlacement int64 `json:"ballotPlacement,omitempty,string"`
// Candidates: The candidate choices for this contest.
Candidates []*Candidate `json:"candidates,omitempty"`
// District: Information about the electoral district that this contest
// is in.
District *ElectoralDistrict `json:"district,omitempty"`
// ElectorateSpecifications: A description of any additional eligibility
// requirements for voting in this contest.
ElectorateSpecifications string `json:"electorateSpecifications,omitempty"`
// Id: An ID for this object. IDs may change in future requests and
// should not be cached. Access to this field requires special access
// that can be requested from the Request more link on the Quotas page.
Id string `json:"id,omitempty"`
// Level: The level of office for this contest. One of: federal, state,
// county, city, other
Level string `json:"level,omitempty"`
// NumberElected: The number of candidates that will be elected to
// office in this contest.
NumberElected int64 `json:"numberElected,omitempty,string"`
// NumberVotingFor: The number of candidates that a voter may vote for
// in this contest.
NumberVotingFor int64 `json:"numberVotingFor,omitempty,string"`
// Office: The name of the office for this contest.
Office string `json:"office,omitempty"`
// PrimaryParty: If this is a partisan election, the name of the party
// it is for.
PrimaryParty string `json:"primaryParty,omitempty"`
// ReferendumSubtitle: A brief description of the referendum. This field
// is only populated for contests of type 'Referendum'.
ReferendumSubtitle string `json:"referendumSubtitle,omitempty"`
// ReferendumTitle: The title of the referendum (e.g. 'Proposition 42').
// This field is only populated for contests of type 'Referendum'.
ReferendumTitle string `json:"referendumTitle,omitempty"`
// ReferendumUrl: A link to the referendum. This field is only populated
// for contests of type 'Referendum'.
ReferendumUrl string `json:"referendumUrl,omitempty"`
// Sources: A list of sources for this contest. If multiple sources are
// listed, the data has been aggregated from those sources.
Sources []*Source `json:"sources,omitempty"`
// Special: "Yes" or "No" depending on whether this a contest being held
// outside the normal election cycle.
Special string `json:"special,omitempty"`
// Type: The type of contest. Usually this will be 'General', 'Primary',
// or 'Run-off' for contests with candidates. For referenda this will be
// 'Referendum'.
Type string `json:"type,omitempty"`
}
type DivisionSearchResponse struct {
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "civicinfo#divisionSearchResponse".
Kind string `json:"kind,omitempty"`
Results []*DivisionSearchResult `json:"results,omitempty"`
// Status: The result of the request. One of: success,
// addressUnparseable, noAddressParameter, internalLookupFailure
Status string `json:"status,omitempty"`
}
type DivisionSearchResult struct {
// Name: The name of the division.
Name string `json:"name,omitempty"`
// OcdId: The unique Open Civic Data identifier for this division.
OcdId string `json:"ocdId,omitempty"`
}
type Election struct {
// ElectionDay: Day of the election in YYYY-MM-DD format.
ElectionDay string `json:"electionDay,omitempty"`
// Id: The unique ID of this election.
Id int64 `json:"id,omitempty,string"`
// Name: A displayable name for the election.
Name string `json:"name,omitempty"`
}
type ElectionOfficial struct {
// EmailAddress: The email address of the election official.
EmailAddress string `json:"emailAddress,omitempty"`
// FaxNumber: The fax number of the election official.
FaxNumber string `json:"faxNumber,omitempty"`
// Name: The full name of the election official.
Name string `json:"name,omitempty"`
// OfficePhoneNumber: The office phone number of the election official.
OfficePhoneNumber string `json:"officePhoneNumber,omitempty"`
// Title: The title of the election official.
Title string `json:"title,omitempty"`
}
type ElectionsQueryResponse struct {
// Elections: A list of available elections
Elections []*Election `json:"elections,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "civicinfo#electionsQueryResponse".
Kind string `json:"kind,omitempty"`
}
type ElectoralDistrict struct {
// Id: An identifier for this district, relative to its scope. For
// example, the 34th State Senate district would have id "34" and a
// scope of stateUpper.
Id string `json:"id,omitempty"`
// Name: The name of the district.
Name string `json:"name,omitempty"`
// Scope: The geographic scope of this district. If unspecified the
// district's geography is not known. One of: national, statewide,
// congressional, stateUpper, stateLower, countywide, judicial,
// schoolBoard, cityWide, township, countyCouncil, cityCouncil, ward,
// special
Scope string `json:"scope,omitempty"`
}
type GeographicDivision struct {
// Name: The name of the division.
Name string `json:"name,omitempty"`
// OfficeIds: List of keys in the offices object, one for each office
// elected from this division. Will only be present if includeOffices
// was true (or absent) in the request.
OfficeIds []string `json:"officeIds,omitempty"`
// Scope: The geographic scope of the division. If unspecified, the
// division's geography is not known. One of: national, statewide,
// congressional, stateUpper, stateLower, countywide, judicial,
// schoolBoard, cityWide, township, countyCouncil, cityCouncil, ward,
// special
Scope string `json:"scope,omitempty"`
}
type Office struct {
// Level: The level of this elected office. One of: federal, state,
// county, city, other
Level string `json:"level,omitempty"`
// Name: The human-readable name of the office.
Name string `json:"name,omitempty"`
// OfficialIds: List of people who presently hold the office.
OfficialIds []string `json:"officialIds,omitempty"`
// Sources: A list of sources for this office. If multiple sources are
// listed, the data has been aggregated from those sources.
Sources []*Source `json:"sources,omitempty"`
}
type Official struct {
// Address: Addresses at which to contact the official.
Address []*SimpleAddressType `json:"address,omitempty"`
// Channels: A list of known (social) media channels for this official.
Channels []*Channel `json:"channels,omitempty"`
// Emails: The direct email addresses for the official.
Emails []string `json:"emails,omitempty"`
// Name: The official's name.
Name string `json:"name,omitempty"`
// Party: The full name of the party the official belongs to.
Party string `json:"party,omitempty"`
// Phones: The official's public contact phone numbers.
Phones []string `json:"phones,omitempty"`
// PhotoUrl: A URL for a photo of the official.
PhotoUrl string `json:"photoUrl,omitempty"`
// Urls: The official's public website URLs.
Urls []string `json:"urls,omitempty"`
}
type PollingLocation struct {
// Address: The address of the location
Address *SimpleAddressType `json:"address,omitempty"`
// EndDate: The last date that this early vote site may be used. This
// field is not populated for polling locations.
EndDate string `json:"endDate,omitempty"`
// Id: An ID for this object. IDs may change in future requests and
// should not be cached. Access to this field requires special access
// that can be requested from the Request more link on the Quotas page.
Id string `json:"id,omitempty"`
// Name: The name of the early vote site. This field is not populated
// for polling locations.
Name string `json:"name,omitempty"`
// Notes: Notes about this location (e.g. accessibility ramp or entrance
// to use)
Notes string `json:"notes,omitempty"`
// PollingHours: A description of when this location is open.
PollingHours string `json:"pollingHours,omitempty"`
// Sources: A list of sources for this location. If multiple sources are
// listed the data has been aggregated from those sources.
Sources []*Source `json:"sources,omitempty"`
// StartDate: The first date that this early vote site may be used. This
// field is not populated for polling locations.
StartDate string `json:"startDate,omitempty"`
// VoterServices: The services provided by this early vote site. This
// field is not populated for polling locations.
VoterServices string `json:"voterServices,omitempty"`
}
type RepresentativeInfoRequest struct {
// Address: The address to look up. May only be specified if the field
// ocdId is not given in the URL.
Address string `json:"address,omitempty"`
}
type RepresentativeInfoResponse struct {
// Divisions: Political geographic divisions that contain the requested
// address.
Divisions *RepresentativeInfoResponseDivisions `json:"divisions,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "civicinfo#representativeInfoResponse".
Kind string `json:"kind,omitempty"`
// NormalizedInput: The normalized version of the requested address
NormalizedInput *SimpleAddressType `json:"normalizedInput,omitempty"`
// Offices: Elected offices referenced by the divisions listed above.
// Will only be present if includeOffices was true in the request.
Offices *RepresentativeInfoResponseOffices `json:"offices,omitempty"`
// Officials: Officials holding the offices listed above. Will only be
// present if includeOffices was true in the request.
Officials *RepresentativeInfoResponseOfficials `json:"officials,omitempty"`
// Status: The result of the request. One of: success,
// noStreetSegmentFound, addressUnparseable, noAddressParameter,
// multipleStreetSegmentsFound, electionOver, electionUnknown,
// internalLookupFailure, RequestedBothAddressAndOcdId
Status string `json:"status,omitempty"`
}
type RepresentativeInfoResponseDivisions struct {
}
type RepresentativeInfoResponseOffices struct {
}
type RepresentativeInfoResponseOfficials struct {
}
type SimpleAddressType struct {
// City: The city or town for the address.
City string `json:"city,omitempty"`
// Line1: The street name and number of this address.
Line1 string `json:"line1,omitempty"`
// Line2: The second line the address, if needed.
Line2 string `json:"line2,omitempty"`
// Line3: The third line of the address, if needed.
Line3 string `json:"line3,omitempty"`
// LocationName: The name of the location.
LocationName string `json:"locationName,omitempty"`
// State: The US two letter state abbreviation of the address.
State string `json:"state,omitempty"`
// Zip: The US Postal Zip Code of the address.
Zip string `json:"zip,omitempty"`
}
type Source struct {
// Name: The name of the data source.
Name string `json:"name,omitempty"`
// Official: Whether this data comes from an official government source.
Official bool `json:"official,omitempty"`
}
type VoterInfoRequest struct {
// Address: The registered address of the voter to look up.
Address string `json:"address,omitempty"`
}
type VoterInfoResponse struct {
// Contests: Contests that will appear on the voter's ballot
Contests []*Contest `json:"contests,omitempty"`
// EarlyVoteSites: Locations where the voter is eligible to vote early,
// prior to election day
EarlyVoteSites []*PollingLocation `json:"earlyVoteSites,omitempty"`
// Election: The election that was queried.
Election *Election `json:"election,omitempty"`
// Kind: Identifies what kind of resource this is. Value: the fixed
// string "civicinfo#voterInfoResponse".
Kind string `json:"kind,omitempty"`
// NormalizedInput: The normalized version of the requested address
NormalizedInput *SimpleAddressType `json:"normalizedInput,omitempty"`
// PollingLocations: Locations where the voter is eligible to vote on
// election day. For states with mail-in voting only, these locations
// will be nearby drop box locations. Drop box locations are free to the
// voter and may be used instead of placing the ballot in the mail.
PollingLocations []*PollingLocation `json:"pollingLocations,omitempty"`
// State: Local Election Information for the state that the voter votes
// in. For the US, there will only be one element in this array.
State []*AdministrationRegion `json:"state,omitempty"`
// Status: The result of the request. One of: success,
// noStreetSegmentFound, addressUnparseable, noAddressParameter,
// multipleStreetSegmentsFound, electionOver, electionUnknown,
// internalLookupFailure
Status string `json:"status,omitempty"`
}
// method id "civicinfo.divisions.search":
type DivisionsSearchCall struct {
s *Service
opt_ map[string]interface{}
}
// Search: Searches for political divisions by their natural name or OCD
// ID.
func (r *DivisionsService) Search() *DivisionsSearchCall {
c := &DivisionsSearchCall{s: r.s, opt_: make(map[string]interface{})}
return c
}
// Query sets the optional parameter "query": The search query. Queries
// can cover any parts of a OCD ID or a human readable division name.
// All words given in the query are treated as required patterns. In
// addition to that, most query operators of the Apache Lucene library
// are supported. See
// http://lucene.apache.org/core/2_9_4/queryparsersyntax.html
func (c *DivisionsSearchCall) Query(query string) *DivisionsSearchCall {
c.opt_["query"] = query
return c
}
func (c *DivisionsSearchCall) Do() (*DivisionSearchResponse, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["query"]; ok {
params.Set("query", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "representatives/division_search")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(DivisionSearchResponse)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Searches for political divisions by their natural name or OCD ID.",
// "httpMethod": "GET",
// "id": "civicinfo.divisions.search",
// "parameters": {
// "query": {
// "description": "The search query. Queries can cover any parts of a OCD ID or a human readable division name. All words given in the query are treated as required patterns. In addition to that, most query operators of the Apache Lucene library are supported. See http://lucene.apache.org/core/2_9_4/queryparsersyntax.html",
// "location": "query",
// "type": "string"
// }
// },
// "path": "representatives/division_search",
// "response": {
// "$ref": "DivisionSearchResponse"
// }
// }
}
// method id "civicinfo.elections.electionQuery":
type ElectionsElectionQueryCall struct {
s *Service
opt_ map[string]interface{}
}
// ElectionQuery: List of available elections to query.
func (r *ElectionsService) ElectionQuery() *ElectionsElectionQueryCall {
c := &ElectionsElectionQueryCall{s: r.s, opt_: make(map[string]interface{})}
return c
}
func (c *ElectionsElectionQueryCall) Do() (*ElectionsQueryResponse, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", "json")
urls := googleapi.ResolveRelative(c.s.BasePath, "elections")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(ElectionsQueryResponse)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "List of available elections to query.",
// "httpMethod": "GET",
// "id": "civicinfo.elections.electionQuery",
// "path": "elections",
// "response": {
// "$ref": "ElectionsQueryResponse"
// }
// }
}
// method id "civicinfo.elections.voterInfoQuery":
type ElectionsVoterInfoQueryCall struct {
s *Service
electionId int64
voterinforequest *VoterInfoRequest
opt_ map[string]interface{}
}
// VoterInfoQuery: Looks up information relevant to a voter based on the
// voter's registered address.
func (r *ElectionsService) VoterInfoQuery(electionId int64, voterinforequest *VoterInfoRequest) *ElectionsVoterInfoQueryCall {
c := &ElectionsVoterInfoQueryCall{s: r.s, opt_: make(map[string]interface{})}
c.electionId = electionId
c.voterinforequest = voterinforequest
return c
}
// OfficialOnly sets the optional parameter "officialOnly": If set to
// true, only data from official state sources will be returned.
func (c *ElectionsVoterInfoQueryCall) OfficialOnly(officialOnly bool) *ElectionsVoterInfoQueryCall {
c.opt_["officialOnly"] = officialOnly
return c
}
func (c *ElectionsVoterInfoQueryCall) Do() (*VoterInfoResponse, error) {
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.voterinforequest)
if err != nil {
return nil, err
}
ctype := "application/json"
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["officialOnly"]; ok {
params.Set("officialOnly", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "voterinfo/{electionId}/lookup")
urls += "?" + params.Encode()
req, _ := http.NewRequest("POST", urls, body)
req.URL.Path = strings.Replace(req.URL.Path, "{electionId}", strconv.FormatInt(c.electionId, 10), 1)
googleapi.SetOpaque(req.URL)
req.Header.Set("Content-Type", ctype)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(VoterInfoResponse)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Looks up information relevant to a voter based on the voter's registered address.",
// "httpMethod": "POST",
// "id": "civicinfo.elections.voterInfoQuery",
// "parameterOrder": [
// "electionId"
// ],
// "parameters": {
// "electionId": {
// "description": "The unique ID of the election to look up. A list of election IDs can be obtained at https://www.googleapis.com/civicinfo/{version}/elections",
// "format": "int64",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "officialOnly": {
// "default": "false",
// "description": "If set to true, only data from official state sources will be returned.",
// "location": "query",
// "type": "boolean"
// }
// },
// "path": "voterinfo/{electionId}/lookup",
// "request": {
// "$ref": "VoterInfoRequest"
// },
// "response": {
// "$ref": "VoterInfoResponse"
// }
// }
}
// method id "civicinfo.representatives.representativeInfoQuery":
type RepresentativesRepresentativeInfoQueryCall struct {
s *Service
representativeinforequest *RepresentativeInfoRequest
opt_ map[string]interface{}
}
// RepresentativeInfoQuery: Looks up political geography and
// (optionally) representative information based on an address.
func (r *RepresentativesService) RepresentativeInfoQuery(representativeinforequest *RepresentativeInfoRequest) *RepresentativesRepresentativeInfoQueryCall {
c := &RepresentativesRepresentativeInfoQueryCall{s: r.s, opt_: make(map[string]interface{})}
c.representativeinforequest = representativeinforequest
return c
}
// IncludeOffices sets the optional parameter "includeOffices": Whether
// to return information about offices and officials. If false, only the
// top-level district information will be returned.
func (c *RepresentativesRepresentativeInfoQueryCall) IncludeOffices(includeOffices bool) *RepresentativesRepresentativeInfoQueryCall {
c.opt_["includeOffices"] = includeOffices
return c
}
// OcdId sets the optional parameter "ocdId": The division to look up.
// May only be specified if the address field is not given in the
// request body.
func (c *RepresentativesRepresentativeInfoQueryCall) OcdId(ocdId string) *RepresentativesRepresentativeInfoQueryCall {
c.opt_["ocdId"] = ocdId
return c
}
func (c *RepresentativesRepresentativeInfoQueryCall) Do() (*RepresentativeInfoResponse, error) {
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.representativeinforequest)
if err != nil {
return nil, err
}
ctype := "application/json"
params := make(url.Values)
params.Set("alt", "json")
if v, ok := c.opt_["includeOffices"]; ok {
params.Set("includeOffices", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["ocdId"]; ok {
params.Set("ocdId", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "representatives/lookup")
urls += "?" + params.Encode()
req, _ := http.NewRequest("POST", urls, body)
googleapi.SetOpaque(req.URL)
req.Header.Set("Content-Type", ctype)
req.Header.Set("User-Agent", "google-api-go-client/0.5")
res, err := c.s.client.Do(req)
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := new(RepresentativeInfoResponse)
if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Looks up political geography and (optionally) representative information based on an address.",
// "httpMethod": "POST",
// "id": "civicinfo.representatives.representativeInfoQuery",
// "parameters": {
// "includeOffices": {
// "default": "true",
// "description": "Whether to return information about offices and officials. If false, only the top-level district information will be returned.",
// "location": "query",
// "type": "boolean"
// },
// "ocdId": {
// "description": "The division to look up. May only be specified if the address field is not given in the request body.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "representatives/lookup",
// "request": {
// "$ref": "RepresentativeInfoRequest"
// },
// "response": {
// "$ref": "RepresentativeInfoResponse"
// }
// }
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More