Opsgenie Go API v2

The Opsgenie SDK for Go provides a set of Go API for Opsgenie services, making it easier for go developers to build applications that integrate with Opsgenie. Developers can build Go applications on top of APIs that take the complexity out of coding directly against a web service interface. The library provides APIs that hide much of the lower-level plumbing, including authentication, request retries, and error handling.

Before starting, you must sign up for Opsgenie service, create an API Integration and get your API key. To use the Opsgenie Go SDK, you will need the API key from the API Integration you created. The API key is used to authenticate requests to the service and identify yourself as the sender of a request.

Go SDK Installation

Golang SDK requires Go version 1.4.1 or above. Golang can be downloaded here. One should make sure the GOPATH and GOROOT variables are set accordingly. Following that the API source can be downloaded via command: go get github.com/opsgenie/opsgenie-go-sdk-v2/.... The command will automatically download and install necessary package files and dependencies under the src directory of the GOPATH.

Opsgenie Go Sdk source code is available at GitHub Opsgenie Go Sdk repository.

SDK Structure

SDK uses different client objects for each domain to consume their APIs.(ex: alertClient, integrationClient etc.) Each domain separated into different packages. To configure a client for a specific API, the related package has to be used to initialize the client with "NewClient(*Config)" function. Under the hood, all the clients use the same base OpsgenieClient and pass a configuration object to change the behavior of the base client. When "NewClient" function is called, SDK configures corresponding client settings according to the "Config" object passed to the function.
Here are the properties of "Config" object

FieldsMandatoryDescription
ApiKeytrueIt is required for Authorization. For more information API Access Management
OpsGenieAPIURLfalseThe API request will be sent to that URL. Default value is api.opsgenie.com
ProxyUrlfalseIt should be defined that URL if there is a proxy server
HttpClientfalseThe retryablehttp.Client object.
BackofffalseThe Backoff definition of retryablehttp.Client
RetryPolicyfalseThe RetryPolicy definition of retryablehttp.Client
RetryCountfalseThe RetryCount definition of retryablehttp.Client
LogLevelfalseThe LogLevel definition of logrus.Level. The default value is InfoLevel
LoggerfalseThe logrus object which will be used for logging.

In general, all clients have different functions for each action that can be triggered by using API. Every function accepts a "Context" and "ApiRequest" and returns "ApiResult" and "Error". In the case that default Context wanted to be used then nil argument can be passed to the function.

SDK returns two types of errors. First one is the default error created by "errors.New()" function and the second one is "ApiError". ApiEror is returned when the request is successfully sent to API but API did not respond with 2XX status code. In that case, it might be needed to cast error to ApiError to see detailed information about why API did not respond with 2XX status code.

package main

import (
	"github.com/opsgenie/opsgenie-go-sdk-v2/client"
	"github.com/opsgenie/opsgenie-go-sdk-v2/alert"
	"fmt"
	"github.com/opsgenie/opsgenie-go-sdk-v2/policy"
)

func main() {

  //create a policy client
	policyClient, err := policy.NewClient(&client.Config{ApiKey: "your api key"})

  
	if err != nil {
		fmt.Println("error occured while creating policy client")
    return
	}

  //create a request object
	createAlertPolicyRequest := &policy.CreateAlertPolicyRequest{
		MainFields: policy.MainFields{
			Name:              "my alert policy",
			Enabled:           false,
			PolicyDescription: "a policy",
		},
		Message:  "a message",
		Continue: false,
		Alias:    "an alias",
		Priority: alert.P1,
	}

  //function call to process the request
	createAlertPolicyResult, err := policyClient.CreateAlertPolicy(nil, createAlertPolicyRequest)

	if err != nil {
		fmt.Printf("error: %s\n", err)
	} else {
		fmt.Sprintf("result: %v+: ", createAlertPolicyResult)
	}

}

SDK Core Capabilities

Configurable Retry Mechanism

In SDK structure, Opsgenie client wraps the retryablehttp client. This package provides a familiar HTTP client interface with automatic retries and exponential backoff.

Backoff, RetryPolicy and RetryCount properties of Config object can be used to configure the retry mechanism of the defined client.

Backoff specifies a policy for how long to wait between retries. It is called after a failing request to determine the amount of time that should pass before trying again. The default backoff performs exponential backoff based on the attempt number and the limited by the provided minimum and maximum duration. If the backoff policy wanted to be customized, a function like the following type must be provided.

📘

Backoff Type

type Backoff func(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration

package main

import (
	"fmt"
	"github.com/opsgenie/opsgenie-go-sdk-v2/client"
	"github.com/opsgenie/opsgenie-go-sdk-v2/heartbeat"
	"net/http"
	"sync/atomic"
	"time"
)

func main() {
	var retries int32
	config := &client.Config{
		ApiKey: "your api key",
		Backoff: func(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration {
			atomic.AddInt32(&retries, 1)
			return time.Millisecond * 1
		},
	}

	hc, _ := heartbeat.NewClient(config)
	hc.Ping(nil, "test")
}

RetryPolicy specifies the policy for handling retries and is called after each request. The default policy is set to retry on connection errors, server errors and 429 Too Many Requests status code. If the retry policy wanted to be customized, a function like the following type must be provided.

📘

Retry Policy Type

type CheckRetry func(ctx context.Context, resp *http.Response, err error) (bool, error)

package main

import (
	"context"
	"github.com/opsgenie/opsgenie-go-sdk-v2/client"
	"github.com/opsgenie/opsgenie-go-sdk-v2/heartbeat"
	"net/http"
	
)

func main() {
	config := &client.Config{
		ApiKey: "your api key",
		RetryPolicy: func(ctx context.Context, resp *http.Response, err error) (b bool, e error) {
			//Your retry conditions will be placed here
      
      //Example conditions
			if ctx.Err() != nil {
				return false, ctx.Err()
			}

			if err != nil {
				return true, err
			}

			return false, nil
		},
	}

	hc, _ := heartbeat.NewClient(config)
	hc.Ping(nil, "test")
}

RetryCount specified the maximum number of retries. The retry count can be customized by giving a valid retry count to Config object.

Configurable Log Support

By default, SDK uses logrus with TextFormatter and log level as info. A custom logrus logger can be provided for more advanced configuration. In the case that only the log level wanted to change to another level, there is no need to provide entirely new custom logger. It can be configured directly by setting "LogLevel" property of "Config" object.
Below is the example to configure custom logrus logger.

package main

import (
	"github.com/opsgenie/opsgenie-go-sdk-v2/client"
		"github.com/sirupsen/logrus"
	"time"
	"github.com/opsgenie/opsgenie-go-sdk-v2/heartbeat"
)

func main() {

	myLogger := logrus.New()
	myLogger.SetLevel(logrus.DebugLevel)
	myLogger.SetFormatter(&logrus.JSONFormatter{
		TimestampFormat:  time.RFC3339Nano,
		PrettyPrint:      true,
	},)
	config := &client.Config{
		ApiKey: "your api key",
		Logger: myLogger,
	}

	hc, _ := heartbeat.NewClient(config)
	hc.Ping(nil, "asd")

}

Metric Support

SDK publishes three types of metrics as SdkMetric, ApiMetric, and HttpMetric. Each of them has common fields: TransactionId, Duration, and ResourcePath.
TransactionId is generated just before the execution of the request in UUID format.
Duration is the total time that took the process a request(in milliseconds).
ResourcePath is the base path for a resource that exposed from API. ex(/v2/hearbeats/hb1)

SdkMetric includes ErrorType, ErrorMessage, SdkRequestDetails and SdkResultdetails. There are four types of errors attached to the metric. "request-validation-error" indicates that request provided does not meet requirements to be valid(eg: a mandatory field is not provided). "sdk-error" indicates that a problem occurred while building HTTP request from the request object. "api-error" indicates that API did not respond with 2XX status code. (In most of the cases you will not get 422 or 400 from the API since all the requests are validated before sending to API. But there may be cases that are not possible to know whether the request is valid before sending)
"http-response-parsing-error" indicates that HTTP response could not be parsed.

ApiMetric includes ResultMetadata and HttpResponse. ApiMetric is published only if an HTTP response is received. HttpResponse is the object provided by http library. ResultMetadata includes requestId(generated by API), responseTime(time took to process the request in API in milliseconds)

To subscribe a metric, MetricSubscriber object must be created. Subscriber Object has a function variable named "Process". Subscriber's "Process" function takes a parameter with "Metric" type and returns "interface{}". SDK will call this function by passing the corresponding metric object when a metric is published. A subscriber can subscribe more than one metrics. In that case, the same Process method provided for the subscriber will be called for each metric. Another subscriber can be created with different "Process" method if different action needs to be taken for each metric.

📘

Retry Count

Retry count includes the initial request made by SDK. For example, if maximum retry count is set to 2 and the request could not be processed after all tries, retryCount will be 3 in that case. But if the request is succeeded by initial request then retry count will be 0

An example for subscription to the metrics

package main

import (
	"fmt"
	"github.com/opsgenie/opsgenie-go-sdk-v2/client"
	"github.com/opsgenie/opsgenie-go-sdk-v2/heartbeat"
)

func main() {
  // create a subsriber object and provide a Process function
	sub := &client.MetricSubscriber{
		Process: myProcessMethod,
	}
	config := &client.Config{
		ApiKey: "your api key",
	}
  //start subscriptions for metrics that you want to listen
	sub.Register(client.API)					
	sub.Register(client.HTTP)
	sub.Register(client.SDK)
}

//SDK will call this function when the corresponding metric is published
func myProcessMethod (metric client.Metric) interface{} {
	fmt.Printf("received metric with type: %s %+v", metric.Type(), metric)
  return nil
}

Configurable Http Client

By default, SDK uses DefaultClient that creates a new http.Client with similar default values to
http.Client, but with a non-shared Transport, idle connections disabled, and keepalives disabled. To configure http.Client, HttpClient property of Config object can be used.

Proxy Configuration

To use Proxy Url, ProxyUrl property of Config object can be used. The URL will be controlled by SDK if that URL is a valid or not.

Using Context
Every function designed in a way that accepts a "Context" object. In the case that default Context wanted to be not used then nil argument can be passed to the function. In the other case, defined Context can be passed to the function as a parameter.

An example of using Context

package main

import (
	"context"
	"fmt"
	"github.com/opsgenie/opsgenie-go-sdk-v2/client"
	"github.com/opsgenie/opsgenie-go-sdk-v2/heartbeat"
	"time"
)

func main() {

	config := &client.Config{
		ApiKey: "your api key",
	}

	hc, _ := heartbeat.NewClient(config)

  //sample context
	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, 100*time.Second)
	defer cancel()

	res, err := hc.Ping(ctx, "ads")

}

Alert API Import Statements

import (
	"github.com/opsgenie/opsgenie-go-sdk-v2/alert"
	"github.com/opsgenie/opsgenie-go-sdk-v2/client"
)

Samples for Alert SDK

The Opsgenie Alert SDK for Go provides to call Alert API endpoints. A few samples are given below, For the other functions of Alert API, please visit Alert API Page.

Create Alert

alertClient, err := alert.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

createResult, err := alertClient.Create(nil, &alert.CreateAlertRequest{
  Message:     "message1",
  Alias:       "alias1",
  Description: "alert description1",
  Responders: [] alert.Responder{
    {Type: alert.EscalationResponder, Name: "TeamA_escalation"},
    {Type: alert.ScheduleResponder, Name: "TeamB_schedule"},
  },
  VisibleTo: [] alert.Responder{
    {Type: alert.UserResponder, Username: "[email protected]"},
    {Type: alert.TeamResponder, Name: "admin"},
  },
  Actions: []string{"action1", "action2"},
  Tags:    []string{"tag1", "tag2"},
  Details: map[string]string{
    "key1": "value1",
    "key2": "value2",
  },
  Entity:   "entity2",
  Source:   "source2",
  Priority: alert.P1,
  User:     "[email protected]",
  Note:     "alert note2",
})

Close Alert

alertClient, err := alert.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

closeResult, err := alertClient.Close(nil, &alert.CloseAlertRequest{
  IdentifierType:  alert.TINYID,
  IdentifierValue: "tiny1",
  User:            "[email protected]",
  Source:          "source1",
  Note:            "note1",
})

Get Alert

alertClient, err := alert.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

getResult, err := alertClient.Get(nil, &alert.GetAlertRequest{
  IdentifierType:  alert.TINYID,
  IdentifierValue: "tiny1",
})

Samples for Incident SDK

The Opsgenie Incident SDK for Go provides to call Incident API endpoints. A few samples are given below, For the other functions of Incident API, please visit Incident API Page.

Create Incident

incidentClient, err := incident.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

createResult, err := incidentClient.Create(nil, &incident.CreateRequest{
  Message:     "Service A is Down",
  Description: "incident description2",
  Responders: [] incident.Responder{
    {Type: incident.Team, Name: "TeamA"},
    {Type: incident.User, Id: "id123-11-0c0e3e57-6b2f-46ca-b6fa-914ff7ea798b"},
  },
  Tags:        []string{"tag12", "tag22"},
  Details: map[string]string{
    "key1":  "value1",
    "key2": "value2",
  },
  Priority:           incident.P1,
  Note:               "alert note2",
  ServiceId:          "",
  StatusPageEntity:   &incident.StatusPageEntity{
    Title:       "A Service is Down",
    Description: "Status page desc1.",
  },
  NotifyStakeholders: false,
})

Close Incident

incidentClient, err := incident.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

closeResult, err := incidentClient.Close(nil, &incident.CloseRequest{
  Id:          "tiny01",
  Identifier:  incident.Tiny,
  Note:        "service is available",
})

Get Incident

incidentClient, err := incident.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

getResult, err := incidentClient.Get(nil, &incident.GetRequest{
  Id:          "tiny01",
  Identifier:  incident.Tiny,
})

Samples for Integration SDK

The Opsgenie Integration SDK for Go provides to call Integration API endpoints. A few samples are given below, For the other functions of Integration API, please visit Integration API Page.

Create API Based Integration

integrationClient, err := integration.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

createResult, err := integrationClient.CreateApiBased(nil, &integration.APIBasedIntegrationRequest{
  Name:                        "Api Integration 1",
  Type:                        "API",
  AllowWriteAccess:            false,
  IgnoreRecipientsFromPayload: false,
  IgnoreTeamsFromPayload:      false,
  SuppressNotifications:       false,
  OwnerTeam: &og.OwnerTeam{
    Name: "TeamB",
  },
  Recipients: []integration.Recipient{
    {
      Type:     integration.User,
      Username: "[email protected]",
    },
  },
})

Update Integration

integrationClient, err := integration.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

updateResult, err := integrationClient.ForceUpdateAllFields(nil, &integration.UpdateIntegrationRequest{
  Id:                          "id1af8d-89a2-407a-89fa-1d9e3f112c6-aad11213",
  Name:                        "Api Integration 1",
  Type:                        "API",
  Enabled:                     false,
  IgnoreRecipientsFromPayload: false,
  IgnoreTeamsFromPayload:      false,
  SuppressNotifications:       false,
  Recipients: []integration.Recipient{
    {
      Type:     integration.User,
      Username: "[email protected]",
    },
  },
  OtherFields: nil,
})

Enable Integration

integrationClient, err := integration.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

enableResult, err := integrationClient.Enable(nil, &integration.EnableIntegrationRequest{
  Id:          "id1af8d-89a2-407a-89fa-1d9e3f112c6-aad11213",
})

Samples for Heartbeat SDK

The Opsgenie Heartbeat SDK for Go provides to call Heartbeat API endpoints. A few samples are given below, For the other functions of Heartbeat API, please visit Heartbeat API Page.

Add Heartbeat Request

heartbeatClient, err := heartbeat.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

addResult, err := heartbeatClient.Add(nil, &heartbeat.AddRequest{
  Name:          "New Heartbeat",
  Description:   "New Heartbeat for TeamA",
  Interval:      10,
  IntervalUnit:  heartbeat.Minutes,
  Enabled:       true,
  OwnerTeam:     og.OwnerTeam{
    Name: "TeamA",
  },
  AlertMessage:  "New Critical Error",
  AlertTag:      "critical",
  AlertPriority: "P1",
})

Get Heartbeat Request

heartbeatClient, err := heartbeat.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

hearbeatResult, err := heartbeatClient.Get(nil, "New Heartbeat")

Enable Heartbeat Request

heartbeatClient, err := heartbeat.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

hearbeatResult, err := heartbeatClient.Enable(nil, "heartbeatName")

Samples for Policy SDK

The Opsgenie Policy SDK for Go provides to call Policy API endpoints. A few samples are given below, For the other functions of Policy API, please visit Policy API Page.

Create Policy

policyClient, err := policy.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

policyResult, err := policyClient.CreateAlertPolicy(nil, &policy.CreateAlertPolicyRequest{
  MainFields:               policy.MainFields{
    PolicyType:        "alert",
    Name:              "Alert Policy",
    Enabled:           true,
    PolicyDescription: "alert policy description",
    Filter:            &og.Filter{
      ConditionMatchType: og.MatchAllConditions,
      Conditions:         []og.Condition{
        {
          Field:         "message",
          IsNot:         false,
          Operation:     og.Contains,
          ExpectedValue: "dynamodb",
        },
      },

    },
    TimeRestriction: &og.TimeRestriction{
      Type:            og.WeekdayAndTimeOfDay,
      RestrictionList: []og.Restriction{
        {
          StartDay:"monday",
          EndDay:"thursday",
          EndHour:5,
          EndMin:10,
          StartHour:20,
          StartMin:23,
        },
      },
    },
    TeamId:            "af8d-89a2-407a-89fa-1d232112c6d-asa11",
  },
  Message:                  "{{message}} db error",
  Continue:                 true,
  Alias:                    "{{alias.toLowerCase()}} dynamodb",
  AlertDescription:         "{{description}}",
  Tags:                     []string{"dynamodb"},
  Priority:                 "",
})

Enable Policy

policyClient, err := policy.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

policyResult, err := policyClient.EnablePolicy(nil, &policy.EnablePolicyRequest{
  Id:          "policy-af8d-89a2-407a-1d2312c6d-asa11",
  TeamId:      "af8d-89a2-407a-89fa-1d232112c6d-asa11",
})

Change Policy Order

policyClient, err := policy.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

policyResult, err := policyClient.ChangeOrder(nil, &policy.ChangeOrderRequest{
  Id:          "policy-af8d-89a2-407a-1d2312c6d-asa11",
  TeamId:      "af8d-89a2-407a-89fa-1d232112c6d-asa11",
  TargetIndex: 2,
})

Samples for Maintenance SDK

The Opsgenie Maintenance SDK for Go provides to call Maintenance API endpoints. A few samples are given below, For the other functions of Maintenance API, please visit Maintenance API Page.

Create Maintenance

maintenanceClient, err := maintenance.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

startDate := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)
endDate := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)

maintenanceResult, err := maintenanceClient.Create(nil, &maintenance.CreateRequest{

  Description: "Maintenance Description",
  Time: maintenance.Time{
    Type:      "schedule",
    StartDate: &startDate,
    EndDate:   &endDate,
  },
  Rules: []maintenance.Rule{
    {
      State: "enabled",
      Entity: maintenance.Entity{
        Id:   "00746f59-a826-4a83-91ff-asd011-asdasd",
        Type: maintenance.Policy,
      },
    },
  }
  ]
})

Get Maintenance

maintenanceClient, err := maintenance.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

maintenanceResult, err := maintenanceClient.Get(nil, &maintenance.GetRequest{
  Id:          "3453301-89a2-22212-89fa-1d9e3f112c6d",
})

Delete Maintenance

maintenanceClient, err := maintenance.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

maintenanceResult, err := maintenanceClient.Delete(nil, &maintenance.DeleteRequest{
  Id:          "3453301-89a2-22212-89fa-1d9e3f112c6d",
})

Samples for Account SDK

The Opsgenie Account SDK for Go provides to call Account API endpoints. A sample is given below, For more information, please visit Account API Page.

Get Account Info

accountClient, err := account.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

accountResult, err := accountClient.Get(nil, &account.GetRequest{})

Samples for User SDK

The Opsgenie User SDK for Go provides to call User API endpoints. A few samples are given below, For the other functions of User API, please visit User API Page.

Create User

userClient, err := user.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

userResult, err := userClient.Create(nil, &user.CreateRequest{
  Username: "[email protected]",
  FullName: "john doe",
  Role: &user.UserRoleRequest{
    RoleName: "Admin",
  },
  SkypeUsername: "doejohn",
  UserAddressRequest: &user.UserAddressRequest{
    Country: "US",
    State:   "Indiana",
    City:    "Terre Haute",
    Line:    "567 Stratford Park",
    ZipCode: "47802",
  },
  Tags: []string{"tag1", "tag3",},
  Details: map[string][]string{
    "detail1Key": {"detail1dValue1", "detail1Value2"},
    "detail2Key": {"detail2Value"},
  },
  TimeZone:          "UTC-5",
  Locale:            "en_US",
})

List User Escalations

userClient, err := user.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

userResult, err := userClient.ListUserEscalations(nil, &user.ListUserEscalationsRequest{
  Identifier:  "2971af8d-89a2-asd22-89fa-1d9e3f11-asd222",
})

Get Saved Search

userClient, err := user.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

userResult, err := userClient.GetSavedSearch(nil, &user.GetSavedSearchRequest{
  Identifier:     "verfiedUsers",
  IdentifierType: user.Name,
})

Samples for Custom User Role API SDK

The Opsgenie Custom User Role SDK for Go provides to call Custom User Role API endpoints. A few samples are given below, For the other functions of Custom User Role API, please visit Custom User Role API Page.

Create Custom User Role

customUserRoleClient, err := customuserrole.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

customUserRoleResult, err := customUserRoleClient.Create(nil, &customuserrole.CreateRequest{
  Name:             "UserRoleName",
  ExtendedRole:     "user",
  GrantedRights:    []string{"logs-page-access"},
  DisallowedRights: []string{"alert-update-priority", "alert-escalate"},
})

Get Custom User Role

customUserRoleClient, err := customuserrole.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

customUserRoleResult, err := customUserRoleClient.Get(nil, &customuserrole.GetRequest{
  Identifier:     "UserRoleName",
  IdentifierType: customuserrole.Name,
})

List Custom User Roles

customUserRoleClient, err := customuserrole.NewClient(&client.Config{
  ApiKey: <apiKey>,
})
customUserRoleResult, err := customUserRoleClient.List(nil, &customuserrole.ListRequest{
})

Samples for Contact SDK

The Opsgenie Contact SDK for Go provides to call Contact API endpoints. A few samples are given below, For the other functions of Contact API, please visit Contact API Page.

Create Contact

contactClient, err := contact.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

contactResult, err := contactClient.Create(nil, &contact.CreateRequest{
  UserIdentifier:  "[email protected]",
  To:              "[email protected]",
  MethodOfContact: "email",
})

Delete Contact

contactClient, err := contact.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

contactResult, err := contactClient.Delete(nil, &contact.DeleteRequest{
  UserIdentifier:    "[email protected]",
  ContactIdentifier: "4fb6ad93-ffed-4c04-b62a-f3bfd993fb3d",
})

Enable Contact

contactClient, err := contact.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

contactResult, err := contactClient.Enable(nil, &contact.EnableRequest{
  UserIdentifier:    "[email protected]",
  ContactIdentifier: "4fb6ad93-ffed-4c04-b62a-f3bfd993fb3d",
})

Samples for Notification Rule SDK

The Opsgenie Notification Rule SDK for Go provides to call Notification Rule API endpoints. A few samples are given below, For the other functions of Notification Rule API, please visit Notification Rule API Page.

Create Notification Rule

notificationClient, err := notification.NewClient(&client.Config{
  ApiKey: <apiKey>,
})
ruleResult, err := notificationClient.CreateRule(nil, &notification.CreateRuleRequest{
  Name:       "Test Notification Rule",
  ActionType: "schedule-start",
  Enabled:    true,
  Criteria: &og.Filter{
    ConditionMatchType: og.MatchAll,
  },
  Order: 1,
  NotificationTime: []notification.NotificationTimeType{
    notification.OneHourAgo,
  },
  Schedules: []notification.Schedule{
    {
      Name:           "test_schedule",
      TypeOfSchedule: "schedule",
    },
  },
  Repeat: &notification.Repeat{
    LoopAfter: 2,
  },
  TimeRestriction: &og.TimeRestriction{
    Type: "time-of-day",
    Restriction: og.Restriction{
      StartHour: 3,
      StartMin:  15,
      EndHour:   5,
      EndMin:    30,
    },
  },
})

Get Notification Rule

notificationClient, err := notification.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

ruleResult, err := notificationClient.GetRule(nil, &notification.GetRuleRequest{
  UserIdentifier: "[email protected]",
  RuleId:         "6250e423-fd5e-451c-8573-a20c61fb9872",
})

Copy Notification Rules to Other Users

notificationClient, err := notification.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

ruleResult, err := notificationClient.CopyRule(nil, &notification.CopyNotificationRulesRequest{
  UserIdentifier: "[email protected]",
  ToUsers: []string{"username1", "username2" , "username3"},
  RuleTypes: []notification.RuleTypes{notification.NewAlertRule, notification.ScheduleStartRule},
})

Samples for Notification Rule Step SDK

The Opsgenie Notification Rule Step SDK for Go provides to call Notification Rule Step API endpoints. A few samples are given below, For the other functions of Notification Rule Step API, please visit Notification Rule Step API Page.

Create Notification Rule Step

notificationClient, err := notification.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

ruleResult, err := notificationClient.CreateRuleStep(nil, &notification.CreateRuleStepRequest{
  UserIdentifier: "[email protected]",
  RuleId:         "e3face00-e378-4eb1-8141-cd21103d1814",
  Contact:        og.Contact{
    To:              "email",
    MethodOfContact: "[email protected]",
  },
  SendAfter:      &og.SendAfter{
    TimeAmount: 5,
  },
  Enabled:        false,
})

Get Notification Rule Step

notificationClient, err := notification.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

ruleResult, err := notificationClient.GetRuleStep(nil, &notification.GetRuleStepRequest{
  UserIdentifier: "[email protected]",
  RuleId:         "e3face00-e378-4eb1-8141-cd21103d1814",
  RuleStepId:     "dbf70781-d6d8-4924-b90d-6a0c77833748",
})

Enable Notification Rule Step

notificationClient, err := notification.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

ruleResult, err := notificationClient.EnableRuleStep(nil, &notification.EnableRuleStepRequest{
  UserIdentifier: "[email protected]",
  RuleId:         "e3face00-e378-4eb1-8141-cd21103d1814",
  RuleStepId:     "dbf70781-d6d8-4924-b90d-6a0c77833748",
})

Samples for Team SDK

The Opsgenie Team SDK for Go provides to call Team API endpoints. A few samples are given below, For the other functions of Team API, please visit Team API Page.

Create Team

teamClient, err := team.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

teamResult, err := teamClient.Create(nil, &team.CreateTeamRequest{
  Name:        "TeamName",
  Description: "Team Description",
  Members: []team.Member{
    {
      User: team.User{
        Username: "[email protected]",
      },
      Role: "admin",
    },
    {
      User: team.User{
        ID: "00564944-b42f-4b95-a882-ee9a5assb9bb",
      },
    },
    {
      User: team.User{
        Username: "[email protected]",
        ID:       "1f2ass91-bca3-4ae2-bdea-b02e94d10953",
      },
      Role: "user",
    },
  },
})

Get Team

teamClient, err := team.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

teamResult, err := teamClient.Get(nil, &team.GetTeamRequest{
  IdentifierType:  team.Name,
  IdentifierValue: "TeamName",
})

List Team Logs

teamClient, err := team.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

teamResult, err := teamClient.ListTeamLogs(nil, &team.ListTeamLogsRequest{
  IdentifierType:  team.Name,
  IdentifierValue: "TeamName",
  Limit:           10,
  Order:           "desc",
  Offset:          0,
})

Samples for Team Member SDK

The Opsgenie Team Member SDK for Go provides to call Team Member API endpoints. A few samples are given below, For more information, please visit Team Member API Page.

Add Team Member

teamClient, err := team.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

teamResult, err := teamClient.AddMember(nil, &team.AddTeamMemberRequest{
  TeamIdentifierType:  team.Name,
  TeamIdentifierValue: "TeamName",
  User: team.User{
    Username: "[email protected]",
  },
  Role: "admin",
})

Remove Team Member

teamClient, err := team.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

teamResult, err := teamClient.RemoveMember(nil, &team.RemoveTeamMemberRequest{
  TeamIdentifierType:    team.Name,
  TeamIdentifierValue:   "TeamName",
  MemberIdentifierType:  team.Username,
  MemberIdentifierValue: "[email protected]",
})

❗️

Handle Username Encoding Problem

If you use MemberIdentifierType as "username" and your username includes "+" character, you need to encode "+" as "%2B".

Samples for Team Role SDK

The Opsgenie Team Role SDK for Go provides to call Team Role API endpoints. A few samples are given below, For the other functions of Team Role API, please visit Team Role API Page.

Create Team Role

teamClient, err := team.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

teamResult, err := teamClient.CreateRole(nil, &team.CreateTeamRoleRequest{
  TeamIdentifierType:  team.Name,
  TeamIdentifierValue: "TeamName",
  Name:                "NewRole",
  Rights: []team.Right{
    {
      Right:   "manage-members",
      Granted: true,
    },
    {
      Right:   "edit-team-roles",
      Granted: true,
    },
  },
})

Get Team Role

teamClient, err := team.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

teamResult, err := teamClient.GetRole(nil, &team.GetTeamRoleRequest{
  TeamName:    "TeamName",
  RoleID:      "dbe375e3-b7d4-4e18-balas-8c47fd4de27a",
})

Delete Team Role

teamClient, err := team.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

teamResult, err := teamClient.DeleteRole(nil, &team.DeleteTeamRoleRequest{
  TeamName:    "NewTeam",
  RoleID:      "dbe375e3-b7d4-4e18-asda-8c47fd4de27a",
})

Samples for Team Routing Rule SDK

The Opsgenie Team Routing Rule SDK for Go provides to call Team Routing Rule API endpoints. A few samples are given below, For the other functions of Team Routing Rule API, please visit Team Routing Rule API Page.

Create Team Routing Rule

teamClient, err := team.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

var order=0

teamResult, err := teamClient.CreateRoutingRule(nil, &team.CreateRoutingRuleRequest{
  TeamIdentifierType:  team.Name,
  TeamIdentifierValue: "TeamName",
  Name:                "Route1",
  Order:               &order,
  Timezone:            "America/Los_Angeles",
  Criteria:            &og.Filter{
    ConditionMatchType: og.MatchAll,
  },
  TimeRestriction:     &og.TimeRestriction{
    Type:            og.TimeOfDay,
    Restriction:     og.Restriction{
      StartDay:  "monday",
      StartHour: 8,
      StartMin:  0,
      EndDay:    "tuesday",
      EndHour:   18,
      EndMin:    30,
    },
  },
  Notify:              &team.Notify{
    Type: team.ScheduleNotifyType,
    Name: "TeamName_schedule",
  },
})

Get Team Routing Rule

teamClient, err := team.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

teamResult, err := teamClient.GetRoutingRule(nil, &team.GetRoutingRuleRequest{
  TeamIdentifierType:  team.Name,
  TeamIdentifierValue: "TeamName",
  RoutingRuleId:       "c8214a84-09e1-4961-9ee6-f977fasd637d",
})

Change Team Routing Rule Order

teamClient, err := team.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

var order=0

teamResult, err := teamClient.ChangeRoutingRuleOrder(nil, &team.ChangeRoutingRuleOrderRequest{
  TeamIdentifierType:  team.Name,
  TeamIdentifierValue: "TeamName",
  RoutingRuleId:       "c8214a84-09e1-4961-9ee6-f977fasd637d",
  Order:               &order,
})

Samples for Schedule SDK

The Opsgenie Schedule SDK for Go provides to call Schedule API endpoints. A few samples are given below, For the other functions of Schedule API, please visit Schedule API Page.

Create Schedule

scheduleClient, err := schedule.NewClient(&client.Config{
  ApiKey: <ApiKey>
})

startDate := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)
endDate := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)

scheduleResult, err := scheduleClient.Create(nil, &schedule.CreateRequest{
  Name:        "TeamName_schedule",
  Description: "Schedule of TeamName",
  Timezone:    "Europe/Kirov",
  Enabled:     true,
  OwnerTeam: &og.OwnerTeam{
    Name: "TeamName",
  },
  Rotations: []og.Rotation{
    {
      Name:      "Rot1",
      StartDate: &startDate,
      EndDate:   &endDate,
      Type:      og.Daily,
      Length:    3,
      Participants: []og.Participant{
        {
          Type:     og.User,
          Username: "[email protected]",
        },
      },
      TimeRestriction: &og.TimeRestriction{
        Type: og.TimeOfDay,
        Restriction: og.Restriction{
          StartDay:  "monday",
          EndDay:    "thursday",
          EndHour:   5,
          EndMin:    10,
          StartHour: 20,
          StartMin:  23,
        },
      },
    },
  },
})

Get Schedule

scheduleClient, err := schedule.NewClient(&client.Config{
  ApiKey: <ApiKey>
})

scheduleResult, err := scheduleClient.Get(nil, &schedule.GetRequest{
  IdentifierType:  schedule.Name,
  IdentifierValue: "TeamName_schedule",
})

Get Schedule Timeline

scheduleClient, err := schedule.NewClient(&client.Config{
  ApiKey: <ApiKey>
})

date := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)

scheduleResult, err := scheduleClient.GetTimeline(nil, &schedule.GetTimelineRequest{
  IdentifierType:  schedule.Name,
  IdentifierValue: "TeamName_schedule",
  Expands:         []schedule.ExpandType{schedule.Base,schedule.Forwarding},
  Interval:        2,
  IntervalUnit:    schedule.Days,
  Date:            &date,
})

Samples for Schedule Rotation SDK

The Opsgenie Schedule Rotation SDK for Go provides to call Schedule Rotation API endpoints. A few samples are given below, For the other functions of Schedule Rotation API, please visit Schedule Rotation API Page.

Create Schedule Rotation

scheduleClient, err := schedule.NewClient(&client.Config{
  ApiKey: <ApiKey>
})

startDate := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)
endDate := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)

scheduleResult, err := scheduleClient.CreateRotation(nil, &schedule.CreateRotationRequest{
	Rotation: &og.Rotation{
    Name:      "Rot1",
    StartDate: &startDate,
    EndDate:   &endDate,
    Type:      og.Daily,
    Length:    3,
    Participants: []og.Participant{
      {
        Type:     og.User,
        Username: "[email protected]",
      },
    },
    TimeRestriction: &og.TimeRestriction{
      Type: og.TimeOfDay,
      Restriction: og.Restriction{
        StartDay:  "monday",
        EndDay:    "thursday",
        EndHour:   5,
        EndMin:    10,
        StartHour: 20,
        StartMin:  23,
      },
    },
  },
  ScheduleIdentifierType:  schedule.Name,
  ScheduleIdentifierValue: "TeamName_schedule",
})

Delete Schedule Rotation

scheduleClient, err := schedule.NewClient(&client.Config{
  ApiKey: <ApiKey>
})

scheduleResult, err := scheduleClient.DeleteRotation(nil, &schedule.DeleteRotationRequest{
  ScheduleIdentifierType:  schedule.Name,
  ScheduleIdentifierValue: "TeamName_schedule",
  RotationId:              "13a3sad1-5f0c-4370-a033-87a7sdsbe5d0e",
})

List Schedule Rotations

scheduleClient, err := schedule.NewClient(&client.Config{
  ApiKey: <ApiKey>
})

scheduleResult, err := scheduleClient.ListRotations(nil, &schedule.ListRotationsRequest{
  ScheduleIdentifierType:  schedule.Name,
  ScheduleIdentifierValue: "TeamName_schedule",
})

Samples for Schedule Override SDK

The Opsgenie Schedule Override SDK for Go provides to call Schedule Override API endpoints. A few samples are given below, For the other functions of Schedule Override API, please visit Schedule Override API Page.

Create Schedule Override

scheduleClient, err := schedule.NewClient(&client.Config{
  ApiKey: <ApiKey>
})
scheduleResult, err := scheduleClient.CreateScheduleOverride(nil, &schedule.CreateScheduleOverrideRequest{
  Alias: "Override Alias",
  User: schedule.Responder{
    Type:     schedule.UserResponderType,
    Username: "[email protected]",
  },
  StartDate: time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC),
  EndDate:   time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC),
  Rotations: []schedule.RotationIdentifier{
    {
      Name: "RotationName",
    },
    {
      Id: "29c15643-7351-4337-ad6f-0fd8af8aass2",
    },
  },
  ScheduleIdentifierType: schedule.Name,
  ScheduleIdentifier:     "",
})

Get Schedule Override

scheduleClient, err := schedule.NewClient(&client.Config{
  ApiKey: <ApiKey>
})

scheduleResult, err := scheduleClient.GetScheduleOverride(nil, &schedule.GetScheduleOverrideRequest{
  ScheduleIdentifierType: schedule.Name,
  ScheduleIdentifier:     "TeamName_schedule",
  Alias:                  "Override Alias",
})

List Schedule Overrides

scheduleClient, err := schedule.NewClient(&client.Config{
  ApiKey: <ApiKey>
})

scheduleResult, err := scheduleClient.ListScheduleOverride(nil, &schedule.ListScheduleOverrideRequest{
  ScheduleIdentifierType: schedule.Name,
  ScheduleIdentifier:     "TeamName_schedule",
})

Samples for Escalation SDK

The Opsgenie Escalation SDK for Go provides to call Escalation API endpoints. A few samples are given below, For the other functions of Escalation API, please visit Escalation API Page.

Create Escalation

escalationClient, err := escalation.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

escalationResult, err := escalationClient.Create(nil, &escalation.CreateRequest{
  Name:        "team_escalation",
  Description: "escalation of Team 1",
  Rules:       []escalation.RuleRequest{
    {
      Condition:  "default",
      NotifyType: "if-not-acked",
      Recipient:  og.Participant{
        Type:     og.Team,
        Name:     "teamA",
      },
      Delay:      escalation.EscalationDelayRequest{
        TimeAmount: 1,
      },
    },
  },
  OwnerTeam:   &og.OwnerTeam{
    Name: "TeamA",
  },
  Repeat:  &escalation.RepeatRequest{
    WaitInterval:         15,
    Count:                13,
    ResetRecipientStates: true,
    CloseAlertAfterAll:   true,
  },
})

Get Escalation

escalationClient, err := escalation.NewClient(&client.Config{
  ApiKey: <apiKey>,
})
getResult, err := escalationClient.Get(nil, &escalation.GetRequest{
  IdentifierType: escalation.Name,
  Identifier:     "team_escalation",
})

List Escalation

escalationClient, err := escalation.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

escalationResult, err := escalationClient.List(nil)

Samples for Who is On Call SDK

The Opsgenie Who is On Call SDK for Go provides to call Who is On Call API endpoints. A few samples are given below, For the other functions of Who is On Call API, please visit Who is On Call API Page.

Get On Calls

scheduleClient, err := schedule.NewClient(&client.Config{
  ApiKey: <ApiKey>
})

date := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)

scheduleResult, err := scheduleClient.GetOnCalls(nil, &schedule.GetOnCallsRequest{
  Flat:                   false,
  Date:                   &date,
  ScheduleIdentifierType: schedule.Name,
  ScheduleIdentifier:     "TeamName_schedule",
})

Get Next On Calls

scheduleClient, err := schedule.NewClient(&client.Config{
  ApiKey: <ApiKey>
})

date := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)

scheduleResult, err := scheduleClient.GetNextOnCall(nil, &schedule.GetNextOnCallsRequest{
  Flat:                   false,
  Date:                   &date,
  ScheduleIdentifierType: schedule.Name,
  ScheduleIdentifier:     "TeamName_schedule",
})

Export On-Call User

scheduleClient, err := schedule.NewClient(&client.Config{
  ApiKey: <ApiKey>
})

downloadedFile, err := scheduleClient.ExportOnCallUser(nil, &schedule.ExportOnCallUserRequest{
  UserIdentifier:   "[email protected]",
  ExportedFilePath: "/Users/testuser/Documents/",
})

Samples for Service SDK

The Opsgenie Service SDK for Go provides to call Service API endpoints. A few samples are given below, For the other functions of Service API, please visit Service API Page.

Create Service

serviceClient, err := service.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

serviceResult, err := serviceClient.Create(nil, &service.CreateRequest{
  Name:        "Service API Test Service",
  TeamId:      "eb24dsd-faa2-4ba2-a551q-1assf565c889",
  Description: "Service API Test Service Description",
  Visibility:  service.TeamMembers,
})

Get Service

serviceClient, err := service.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

serviceResult, err := serviceClient.Get(nil, &service.GetRequest{
  Id:          "aasd221-faa2-4ba2-a551q-1assf565c889",
})

List Service

serviceClient, err := service.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

serviceResult, err := serviceClient.List(nil, &service.ListRequest{
  Limit:       10,
  Offset:      0,
})

Samples for Service Incident Rules SDK

The Opsgenie Service Incident Rules SDK for Go provides to call Service Incident Rules API endpoints. A sample is given below, For the other functions of Service Incident Rules API, please visit Service Incident Rules API Page.

Create Service Incident Rules

serviceIncidentRulesClient, err := service.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

serviceIncidentRulesClient.CreateIncidentRule(nil, &service.CreateIncidentRuleRequest{
		ServiceId: "1-234245335",
		Conditions: []og.Condition{
			{
				Field:         "message",
				IsNot:         false,
				Operation:     og.Contains,
				ExpectedValue: "dynamodb",
			},
		},
		ConditionMatchType: og.MatchAnyCondition,
		IncidentProperties: service.IncidentProperties{
			Message: "message",
			Tags:    []string{"tag1", "tag3",},
			Details: map[string]string{
				"key1": "value1",
				"key2": "value2",
			},
			Description: "description",
			Priority:    alert.P1,
			StakeholderProperties: service.StakeholderProperties{
				Enable:      false,
				Message:     "stakeholder message",
				Description: "desc",
			},
		},
	})

Samples for Service Incident Templates SDK

The Opsgenie Service Incident Rules SDK for Go provides to call Service Incident Templates API endpoints. A sample is given below, For the other functions of Service Incident Templates API, please visit Service Incident Templates API Page.

Create Service Incident Templates

serviceClient, err := service.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

serviceClient.CreateIncidentTemplate(nil, &service.CreateIncidentTemplateRequest{
		ServiceId:        "1234-1234",
		IncidentTemplate: service.IncidentTemplateRequest{
			Name:               "service temp",
			IncidentProperties: service.IncidentProperties{
				Message: "message",
				Tags:    []string{"tag1", "tag3",},
				Details: map[string]string{
					"key1": "value1",
					"key2": "value2",
				},
				Description: "description",
				Priority:    alert.P1,
				StakeholderProperties: service.StakeholderProperties{
					Enable:      false,
					Message:     "stakeholder message",
					Description: "desc",
				},
			},
		},
	})

Samples for Service Audience Template SDK

The Opsgenie Service Audience Template SDK for Go provides to call Service Audience Template API endpoints. A sample is given below, For the other functions of Service Audience Template API, please visit Service Audience Template API Page.

Update Service Audience Template

serviceClient, err := service.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

serviceClient.UpdateAudienceTemplate(nil, &service.UpdateAudienceTemplateRequest{
		BaseRequest: client.BaseRequest{},
		ServiceId:   "1234-1234",
		Responder: service.ResponderOfAudience{
			Teams:       []string{"1234523", "73664672"},
			Individuals: []string{"12345345",},
		},
		Stakeholder: service.StakeholderOfAudience{
			Individuals:        []string{"12345",},
			ConditionMatchType: og.MatchAnyCondition,
			Conditions: []service.ConditionOfStakeholder{
				{
					MatchField: service.Country,
					Value:      "usa",
				},
			},
		},
	})

Samples for Logs SDK

The Opsgenie Logs SDK for Go provides to call Logs API endpoints. A few samples are given below, For more information, please visit Logs API Page.

List Log Files

logsClient, err := logs.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

logsResult, err := logsClient.ListLogFiles(nil, &logs.ListLogFilesRequest{
  Marker:      "2018-10-24-07-30-00",
  Limit:       10,
})

Generate Log File Download Link

logsClient, err := logs.NewClient(&client.Config{
  ApiKey: <apiKey>,
})

logsResult, err := logsClient.GenerateLogFileDownloadLink(nil, &logs.GenerateLogFileDownloadLinkRequest{
  FileName:    "2019-02-26-08-30-00.json",
})