t1

package module
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 25, 2020 License: Apache-2.0 Imports: 16 Imported by: 0

README

go-t1

go-t1 is a Go client for MediaMath's APIs. API Documentation is available on the developer portal.

Reference: GoDoc

Table of Contents

Installation

$ go get github.com/MediaMath/go-t1

Usage

import (
	"fmt"
	"github.com/MediaMath/go-t1"
	"github.com/MediaMath/go-t1/authenticators/cookie"
	"github.com/MediaMath/go-t1/models"
	"log"
	"time"
)

To set up authentication, use an authenticator:

	// Set up configuration from envvars
	conf := cookie.GetCredentialsFromEnv()

	// Create new *http.Client with these credentials
	c, err := cookie.New(conf, t1.ProductionURL)
	if err != nil {
		log.Fatalf("initial login: %v", err)
	}

The authenticators are just *http.Client objects that know how to authenticate. Cookie is provided in the package authenticators/cookie, and OAuth2 is supported. To use OAuth2, use Google's OAuth2 package, with a MediaMath endpoint. An example is provided in the testdata/examples directory.

Construct a new client, then use the various services on the client to access different parts of the MediaMath API.

	// Construct new t1 client
	t1Client := t1.NewClient(c, conf.APIKey, t1.ProductionURL)

	// Model object gets passed in to the various service methods
	var org models.Organization

	meta, err := t1Client.Organizations.Get(100048, &org)
	if err != nil {
		log.Fatalf("get org error: %v", err)
	}
	fmt.Printf("Meta:\t%#v\nOrg:\t%#v\n", meta, org)

This whole example is available in the testdata/examples/get_organization directory. The testdata/examples directory also has examples of listing, creating, and updating entities.

Time Types

Execution and Management API currently returns times in a format conforming to ISO 8601 but not RFC 3339. As such, there is a time package t1time that provides a time type compatible with this. This is a time.Time type, so can be converted easily:

embedmd:# (testdata/examples/get_organization/main.go /time.[^)]*)/)

time.Time(org.CreatedOn)

Documentation

Overview

Package t1 is a Go library for MediaMath's APIs.

Construct a new T1 client, then use the various services on the client to access different parts of the MediaMath API modules.

For example:

package main

import (
	"github.com/MediaMath/go-t1"
	"github.com/MediaMath/go-t1/authenticators/cookie"
	"github.com/MediaMath/go-t1/models"
)

func main() {
	conf := cookie.Config{"myusername", "mypassword", "myapikey"}
	auth := cookie.New(conf, t1.ProductionURL)
	client := t1.NewClient(auth, conf.APIKey, t1.ProductionURL)
	var orgs []models.Organization
	meta, err := client.Organizations.List(nil, &orgs)
}

The client here takes any `*http.Client` that can authenticate properly. As such, you can also use a client from the OAuth2 package:

package main

import (
	"github.com/MediaMath/go-t1"
	"github.com/MediaMath/go-t1/models"
	"golang.org/x/oauth2"
	"golang.org/x/oauth2/mediamath"
)

func main() {
	conf := oauth2.Config{
		ClientID:     os.Getenv("T1_API_CLIENT_ID"),
		ClientSecret: os.Getenv("T1_API_CLIENT_SECRET"),
		Endpoint:     mediamath.Endpoint,
		RedirectURL:  "https://www.mediamath.com/",
	}
	// get the token
	c := conf.Client(oauth2.NoContext, tok)
	t1Client := t1.NewClient(c, conf.ClientID, t1.ProductionURL)
	var org models.Organization
	meta, err := t1Client.Organizations.Get(100048, &org)
}

For API documentation, please visit https://developer.mediamath.com

Index

Constants

This section is empty.

Variables

View Source
var (
	ProductionURL, _ = url.Parse("https://api.mediamath.com")
	SandboxURL, _    = url.Parse("https://t1sandbox.mediamath.com")
)

Standard base URLs

View Source
var (
	// DefaultParams is an empty UserParams struct to use in methods when
	// no user params are set.
	DefaultParams = &UserParams{}
)

Functions

func CheckResponse

func CheckResponse(r *http.Response) error

CheckResponse checks the API response for errors, and returns them if present. A response is considered an error if it has a status code outside the 200 range. API error responses are expected to have either no response body, or a JSON response body that maps to ErrorResponse. Any other response body will be silently ignored.

The error type will be *RateLimitError for rate limit exceeded errors.

Types

type Client

type Client struct {

	// API Key to be used. This will be included as a query string
	// parameter in all requests made. API key typically will need
	// to be included in the construction of the HTTP client as well.
	// Independent of that, it must be included here.
	APIKey string

	// Base URL for API requests. Defaults to the production API endpoint,
	// but can be set to a specific domain for Sandbox or other similar
	// environments. Should be protocol and domain name without trailing slash
	BaseURL *url.URL

	RateLimitReset time.Time

	Advertisers        *EntityService
	AtomicCreatives    *EntityService
	Agencies           *EntityService
	AdServers          *EntityService
	Campaigns          *EntityService
	Concepts           *EntityService
	Creatives          *EntityService
	Deals              *EntityService
	Organizations      *EntityService
	Pixels             *EntityService
	PixelBundles       *EntityService
	PixelProviders     *EntityService
	PlacementSlots     *EntityService
	Publishers         *EntityService
	PublisherSites     *EntityService
	SitePlacements     *EntityService
	SiteLists          *EntityService
	Strategies         *EntityService
	SupplySources      *EntityService
	Users              *EntityService
	Vendors            *EntityService
	VendorContracts    *EntityService
	VendorDomains      *EntityService
	VendorPixels       *EntityService
	VendorPixelDomains *EntityService
	Verticals          *EntityService
	// contains filtered or unexported fields
}

A Client manages communication with the MediaMath APIs

func NewClient

func NewClient(httpClient *http.Client, apiKey string, baseURL *url.URL) *Client

NewClient returns a new MediaMath API client. If a nil httpClient is provided, an http.Client with sufficient timeout will be used. To use methods which require authentication (all methods at this point), provide an http.Client that will perform the authentication for you (such as that provided by the authenticators/oauth2 or authenticators/cookie libraries).

func (*Client) Do

func (c *Client) Do(req *http.Request, v interface{}) (*http.Response, error)

Do sends an API request and returns the API response. The API response is JSON decoded and stored in the value pointed to by v, or returned as an error if an API error has occurred. If v implements the io.Writer interface, the raw response body will be written to v, without attempting to first decode it. If rate limit is exceeded and reset time is in the future, Do returns *RateLimitError immediately without making a network API call.

func (*Client) NewRequest

func (c *Client) NewRequest(method, urlStr string, body Encoder) (*http.Request, error)

NewRequest creates an API request. A relative URL can be provided in urlStr, in which case it is resolved relative to the BaseURL of the Client. Relative URLs should always be specified with a preceding slash. If specified, the value pointed to by body is URL-encoded and included as the request body.

func (*Client) Session

func (c *Client) Session() (Session, error)

Session retrieves the session information of the client.

type Encoder

type Encoder interface {
	Encode() string
}

Encoder represents an object that can be encoded.

type EntityResponse

type EntityResponse struct {
	Meta Meta
	Data json.RawMessage
}

EntityResponse is the response returned by the Execution and Management API.

type EntityService

type EntityService struct {
	// contains filtered or unexported fields
}

EntityService is a generalized service object that helps work with entities. Designed to be instantiated for each entity type.

func (*EntityService) Get

func (s *EntityService) Get(id int, data interface{}) (Meta, error)

Get fetches an entity by ID and loads it into the data object passed in. The object should be provided so that EntityService does not need to do the job of figuring out what kind of entity it is. Like with encoding/json, it is the user's responsiblity to provide the correct type of object.

func (*EntityService) List

func (s *EntityService) List(params *UserParams, data interface{}) (Meta, error)

List fetches a list of entities according to the given user params and loads it into the data object passed in. data should be a slice of whatever entity the service represents.

func (*EntityService) Save

func (s *EntityService) Save(data interface{}) (Meta, error)

Save posts an entity to the API. data *must* be a pointer to an object: save will modify the object with what gets returned.

func (*EntityService) SaveWithResponse added in v1.0.2

func (s *EntityService) SaveWithResponse(data interface{}, response interface{}) (Meta, error)

SaveWithResponse posts an entity to the API. data *must* be a pointer to an object: save will modify the response struct with what gets returned.

type Error

type Error struct {
	Resource string `json:"resource"` // resource on which the error occurred
	Type     string `json:"type"`     // Type of error (e.g. field-error)
	Field    string `json:"field"`    // field on which the error occurred
	Code     string `json:"code"`     // validation error code
	Message  string `json:"message"`  // Message describing the error. Errors with Code == "custom" will always have this set.
}

Error reports more details on an individual error in an ErrorResponse. These are example validation error codes:

func (*Error) Error

func (e *Error) Error() string

Error tells you what error was caused by what field and resource

type ErrorResponse

type ErrorResponse struct {
	Response *http.Response `json:"-"`       // HTTP response that caused this error
	Message  string         `json:"message"` // error message
	Errors   []Error        `json:"errors"`  // more detail on individual errors
	Meta     Meta           `json:"meta"`
}

ErrorResponse reports one or more errors caused by an API request.

func (*ErrorResponse) Error

func (r *ErrorResponse) Error() string

type Meta

type Meta struct {
	CalledOn   t1time.T1Time `json:"called_on"`
	Count      int           `json:"count"`
	ETag       string        `json:"etag"`
	NextPage   string        `json:"next_page"`
	Offset     int           `json:"offset"`
	Status     string        `json:"status"`
	TotalCount int           `json:"total_count"`
}

Meta is a struct of the metadata returned by some of the APIs.

type RateLimitError

type RateLimitError struct {
	RetryAt  time.Time
	Response *http.Response // HTTP response that caused this error
	Message  string         `json:"message"` // error message
}

RateLimitError occurs when API returns 403 Forbidden response with an error header signifying over QPS

func (*RateLimitError) Error

func (r *RateLimitError) Error() string

type Session

type Session struct {
	UserName string `json:"name"`
	UserID   int    `json:"id"`
	// contains filtered or unexported fields
}

Session represents an Adama session object

type UserParams

type UserParams struct {
	Full       []string `json:"full,omitempty"`
	PageLimit  int      `json:"page_limit,omitempty"`
	PageOffset int      `json:"page_offset,omitempty"`
	Q          string   `json:"q,omitempty"`
	SortBy     string   `json:"sort_by,omitempty"`
}

UserParams is a struct of parameters to add to the query string of the URL of a request.

Directories

Path Synopsis
authenticators

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL