Giter Club home page Giter Club logo

alphagov.notifications-go-client's Introduction

GOV.UK Notify Go client

Note to anyone cloning this repo

Please be aware that is currently an unsupported client for GOV.UK Notify. If you do want to use this client please contact the Notify team using slack or by submitting feedback. We need to make sure this repo upholds our standards and is updated with new features, has integration tests and is included in our development pipeline.

Installing

The Notify Go Client can be installed with go get.

go get github.com/alphagov/notifications-go-client

Getting started

Create an instance of the Client using:

package main

import "github.com/alphagov/notifications-go-client"

func main() {
	// Configure the client.
	config := notify.Configuration{
		APIKey: "{your api key}",
		ServiceID: "{your service id}",
	}

	// Initialise the client.
	client, err := notify.New(config)
	if err != nil {
		panic(err)
	}
}

Generate an API key by logging in to GOV.UK Notify and going to the API integration page.

Send messages

Text message

The method signature is:

SendSms(phoneNumber, templateID string, personalisation templateData, reference string) (*NotificationEntry, error)

An example request would look like:

data := map[string]string{
	"name": "Betty Smith",
	"dob": "12 July 1968",
}

response, err := client.SendSms("+447777111222", "df10a23e-2c6d-4ea5-87fb-82e520cbf93a", data, "")
Response

If the request is successful, response will be a *notify.NotificationEntry:

type NotificationEntry struct {
	Content   map[string]string
	ID        string
	Reference string
	Template  type Template struct {
		Version int64
		ID      int64
		URI     string
	}
	URI       string
}

Otherwise the notify.APIError will be returned:

`error["status_code"]` `error["message"]`
429
[{
	"error": "RateLimitError",
	"message": "Exceeded rate limit for key type TEAM of 10 requests per 10 seconds"
}]
429
[{
	"error": "TooManyRequestsError",
	"message": "Exceeded send limits (50) for today"
}]
400
[{
	"error": "BadRequestError",
	"message": "Can"t send to this recipient using a team-only API key"
]}
400
[{
	"error": "BadRequestError",
	"message": "Can"t send to this recipient when service is in trial mode
	              - see https://www.notifications.service.gov.uk/trial-mode"
}]

Email

The method signature is:

SendEmail(emailAddress, templateID string, personalisation templateData, reference string) (*NotificationEntry, error)

An example request would look like:

data := map[string]string{
	"name": "Betty Smith",
	"dob": "12 July 1968",
}

response, err := SendEmail("[email protected]", "df10a23e-2c0d-4ea5-87fb-82e520cbf93c", data, "")
Response

If the request is successful, response will be an *notify.NotificationEntry:

type NotificationEntry struct {
	Content   map[string]string
	ID        string
	Reference string
	Template  type Template struct {
		Version int64
		ID      int64
		URI     string
	}
	URI       string
}

Otherwise the client will raise a Alphagov\Notifications\Exception\NotifyException:

`error["status_code"]` `error["message"]`
429
[{
	"error": "RateLimitError",
	"message": "Exceeded rate limit for key type TEAM of 10 requests per 10 seconds"
}]
429
[{
	"error": "TooManyRequestsError",
	"message": "Exceeded send limits (50) for today"
}]
400
[{
	"error": "BadRequestError",
	"message": "Can"t send to this recipient using a team-only API key"
]}
400
[{
	"error": "BadRequestError",
	"message": "Can"t send to this recipient when service is in trial mode
	              - see https://www.notifications.service.gov.uk/trial-mode"
}]

Arguments

templateId

Find by clicking API info for the template you want to send.

personalisation

If a template has placeholders you need to provide their values. For example:

personalisation := map[string]string{
	"name": "Betty Smith",
	"dob": "12 July 1968",
}

reference

An optional identifier you generate if you don’t want to use Notify’s id. It can be used to identify a single notification or a batch of notifications.

Get the status of one message

The method signature is:

GetNotification(id string) (*Notification, error)

An example request would look like:

notification, err := client.GetNotification("c32e9c89-a423-42d2-85b7-a21cd4486a2a")
Response

If the request is successful, notification will be an *notify.Notification:

type Notification struct {
	ID        string
	Body      string
	Subject   string
	Reference string
	Email     string
	Phone     string
	Line1     string
	Line2     string
	Line3     string
	Line4     string
	Line5     string
	Line6     string
	Postcode  string
	Type      string
	Status    string
	Template  type Template struct {
		ID      int64
		URI     string
		Version int64
	}
	CreatedAt time.Time
	SentAt    time.Time
}

Otherwise the client will raise a notify.APIError:

`error["status_code"]` `error["message"]`
404
[{
	"error": "NoResultFound",
	"message": "No result found"
}]
400
[{
	"error": "ValidationError",
	"message": "id is not a valid UUID"
}]

Get the status of all messages

The method signature is:

ListNotifications(filters notify.Filters) (*NotificationList, error)

An example request would look like:

filters := notify.Filters{
	OlderThan: "c32e9c89-a423-42d2-85b7-a21cd4486a2a",
	Reference: "weekly-reminders",
	Status: "delivered",
	TemplateType: "sms",
}

list, err := client.ListNotifications(filters)
Response

If the request is successful, list will be an *notify.NotificationList:

type NotificationList struct {
	Client *Client

	Notifications []Notification
	Links         Pagination
}

Otherwise the client will raise a notify.APIError:

`error["status_code"]` `error["message"]`
400
[{
	'error': 'ValidationError',
	'message': 'bad status is not one of [created, sending, delivered, pending, failed, technical-failure, temporary-failure, permanent-failure]'
}]
400
[{
	"error": "ValidationError",
	"message": "Apple is not one of [sms, email, letter]"
}]

Notification list pagination

The method signatures are:

Next() error
Previous() error

An example request would look like:

var err error
a := list.Notifications[0].ID // Recorded for demonstration only.

err = list.Next()
if err != nil {
	fmt.Printf("Could be that there are no more pages that way. %#v", err)
}

fmt.Println(list.Notifications[0].ID == a) // false

err = list.Previous()
if err != nil {
	fmt.Printf("Could be that there are no more pages that way. %#v", err)
}

fmt.Println(list.Notifications[0].ID == a) // true

Arguments

older_than

If omitted all messages are returned. Otherwise you can filter to retrieve all notifications older than the given notification id.

template_type

If omitted all messages are returned. Otherwise you can filter by:

  • email
  • sms
  • letter

status

If omitted all messages are returned. Otherwise you can filter by:

  • sending - the message is queued to be sent by the provider.
  • delivered - the message was successfully delivered.
  • failed - this will return all failure statuses permanent-failure, temporary-failure and technical-failure.
  • permanent-failure - the provider was unable to deliver message, email or phone number does not exist; remove this recipient from your list.
  • temporary-failure - the provider was unable to deliver message, email box was full or the phone was turned off; you can try to send the message again.
  • technical-failure - Notify had a technical failure; you can try to send the message again.

reference

This is the reference you gave at the time of sending the notification. This can be omitted to ignore the filter.

Development

Tests

There are unit and integration tests that can be run to test functionality of the client.

To run the tests:

ginkgo

Or in the traditional way:

go test

License

The Notify Go Client is released under the MIT license, a copy of which can be found in LICENSE.

alphagov.notifications-go-client's People

Contributors

mfcrocker avatar paroxp avatar quis avatar servingupaces avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.