Skip to content

API Java client Documentation

willeybryan edited this page Sep 10, 2019 · 11 revisions

Cette documentation s'adresse aux développeurs intéressés par l'utilisation de la API Java client de notification CDS-SNC pour l'envoi d'e-mails ou de messages texte.

Le système de notification CDS-SNC est basé sur le travail effectué par GOV.UK de Notify.

Remarque importante

Pour vous connecter au système de notification CDS-SNC, vous devez utiliser un client GOV.UK. Cela signifie que certains messages d'erreur que vous obtenez sont spécifiques à GOV.UK Notify et vous lient directement à leur instance. Nous en sommes conscients et nous prévoyons de changer cela à l'avenir avec le développement de nos propres clients.

Nous vous recommandons d'utiliser cette bibliothèque client plutôt que l'API directement, car il n'y a pas de documentation pour utiliser l'API de cette façon

Configurer le client

Installer le client

'notifications-java-client` se déploie à Bintray.

Aller à la page GOV.UK Notify Java page client sur Bintray [lien externe]:

  1. Sélectionnez Set me up! et utilisez les instructions de téléchargement appropriées.
  2. Allez dans la section Paramètres de construction Maven de la page et copiez l'extrait de code de dépendance approprié.

Consulter le client journal des modifications pour le numéro de version et les dernières mises à jour.

Créer une nouvelle instance du client

Ajoutez ce code à votre application :

import uk.gov.service.notify.NotificationClient;
NotificationClient client = new NotificationClient(apiKey, apiEndpoint);

Remarque: Laisser un /à la fin de votre apiEndpoint causera une erreur template missing required fields

Pour obtenir une clé API,identifiez-vous et allez à la page API integration. Vous trouverez plus d'informations dans la sectionclé API de la documentation.

Envoyer un message

Vous pouvez utiliser le système pour envoyer des messages texte ou des e-mails.

envoyer un message SMS

Méthode

SendSmsResponse response = client.sendSms(
    templateId,
    phoneNumber,
    personalisation,
    reference,
    smsSenderId
);

Modificateurs

templateId (nécessaire)

s'identifier and go to the Templates page pour rechercher l'ID de modèle..

String templateId="f33517ff-2a88-4f6e-b855-c550268ce08a";

phoneNumber (nécessaire)

Le numéro de téléphone du destinataire du SMS. Ce numéro peut être un numéro canadien ou international

String phoneNumber="555-555-5555";

personalisation (nécessaire)

Si un modèle comporte des champs réservés à des informations personnalisées telles que le nom ou le numéro de référence, vous devez fournir leurs valeurs dans une carte. Par exemple :

Map<String, Object> personalisation = new HashMap<>();
personalisation.put("first_name", "Amala");
personalisation.put("application_date", "2019-01-01");
personalisation.put("list", listOfItems); // Will appear as a comma separated list in the message

Si un modèle n'a pas de champs de remplacement pour les informations personnalisées, vous devez passer dans une carte vide ou 'null'.

reference (nécessaire)

Un identifiant unique que vous créez. Cette référence identifie un seul avis unique ou un lot d'avis. Il ne doit pas contenir d'informations personnelles telles que le nom ou l'adresse postale. Si vous n'avez pas de référence, vous devez passer dans une chaîne vide ou null.

String reference='STRING';

smsSenderId (optionnelles)

Un identificateur exclusif de l'expéditeur de la notification par SMS. Pour trouver cette information, allez à l'écran Text Message sender settings :

  1. Connectez-vous à votre compte.
  2. aller à Paramètres.
  3. If you need to change to another service, select Changer de service in the top right corner of the screen and select the correct one.
  4. Go to the __ Paramètres du message texte__ section and select Modifier on the Envoyer des messages textes row.

Dans cet écran, vous pouvez ensuite effectuer les opérations suivantes:

  • copier sender ID que vous voulez utiliser et le coller dans la méthode
  • sélectionnez Change pour changer l'expéditeur par défaut que le service utilisera, et sélectionnez Save.
String smsSenderId='8e222534-7f05-4972-86e3-17c5d9f894e2'

Si vous n'avez pas un `smsSenderId', vous pouvez omettre cet modificateur.

Réponse

Si la demande au client est réussie, le client renvoie une SendSmsResponse.:

UUID notificationId;
Optional<String> reference;
UUID templateId;
int templateVersion;
String templateUri;
String body;
Optional<String> fromNumber;

Si vous utilisez la touchetest clé API, tous vos messages reviennent avec un statut `delivered'.

Tous les messages envoyés à l'aide des touchesteam and whitelist oulive apparaissent sur votre tableau de bord.

Codes d'erreur

Si la demande n'aboutit pas, le client renvoie un NotificationClientException contenant le code d'erreur correspondant:

httpResult Message réparer
400 [{
"error": "BadRequestError",
"message": "Can't send to this recipient using a team-only API key"
]}
Use the correct type of API key
400 [{
"error": "BadRequestError",
"message": "Can't send to this recipient when service is in trial mode"
}]
Your service cannot send this notification in trial mode
403 [{
"error": "AuthError",
"message": "Error: Your system clock must be accurate to within 30 seconds"
}]
Check your system clock
403 [{
"error": "AuthError",
"message": "Invalid token: signature, api token not found"
}]
Use the correct API key. Refer to API keys for more information
429 [{
"error": "RateLimitError",
"message": "Exceeded rate limit for key type TEAM/TEST/LIVE of 3000 requests per 60 seconds"
}]
Refer to API rate limits for more information
429 [{
"error": "TooManyRequestsError",
"message": "Exceeded send limits (LIMIT NUMBER) for today"
}]
Refer to service limits for the limit number
500 [{
"error": "Exception",
"message": "Internal server error"
}]
Notify was unable to process the request, resend your notification

Envoyer un email

Méthode

SendEmailResponse response = client.sendEmail(
    templateId,
    emailAddress,
    personalisation,
    reference,
    emailReplyToId
);

Modificateurs

templateId (required)

Sign in and go to the Templates page to find the template ID.

String templateId="f33517ff-2a88-4f6e-b855-c550268ce08a";

emailAddress (required)

The email address of the recipient.

String emailAddress='sender@something.com';

personalisation (required)

If a template has placeholder fields for personalised information such as name or application date, you must provide their values in a map. For example:

Map<String, Object> personalisation = new HashMap<>();
personalisation.put("first_name", "Amala");
personalisation.put("application_date", "2018-01-01");
personalisation.put("list", listOfItems); // Will appear as a bulleted list in the message

If a template does not have any placeholder fields for personalised information, you must pass in an empty map or null.

reference (required)

A unique identifier you create. This reference identifies a single unique notification or a batch of notifications. It must not contain any personal information such as name or postal address. If you do not have a reference, you must pass in an empty string or null.

String reference='STRING';

emailReplyToId (optional)

This is an email reply-to address specified by you to receive replies from your users. Your service cannot go live until you set up at least one of these email addresses. To set up:

  1. Sign into your account.
  2. Go to Settings.
  3. If you need to change to another service, select Switch service in the top right corner of the screen and select the correct one.
  4. Go to the Email section and select Manage on the Email reply-to addresses row.
  5. Select Change to specify the email address to receive replies, and select Save.
String emailReplyToId='8e222534-7f05-4972-86e3-17c5d9f894e2'

If you do not have an emailReplyToId, you can leave out this argument.

Response

If the request to the client is successful, the client returns a SendEmailResponse:

UUID notificationId;
Optional<String> reference;
UUID templateId;
int templateVersion;
String templateUri;
String body;
String subject;
Optional<String> fromEmail;

Error codes

If the request is not successful, the client returns a NotificationClientException containing the relevant error code:

httpResult Message How to fix
400 [{
"error": "BadRequestError",
"message": "Can't send to this recipient using a team-only API key"
]}
Use the correct type of 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"
}]
Your service cannot send this notification in trial mode
403 [{
"error": "AuthError",
"message": "Error: Your system clock must be accurate to within 30 seconds"
}]
Check your system clock
403 [{
"error": "AuthError",
"message": "Invalid token: signature, api token not found"
}]
Use the correct API key. Refer to API keys for more information
429 [{
"error": "RateLimitError",
"message": "Exceeded rate limit for key type TEAM/TEST/LIVE of 3000 requests per 60 seconds"
}]
Refer to API rate limits for more information
429 [{
"error": "TooManyRequestsError",
"message": "Exceeded send limits (LIMIT NUMBER) for today"
}]
Refer to service limits for the limit number
500 [{
"error": "Exception",
"message": "Internal server error"
}]
Notify was unable to process the request, resend your notification

Send a file by email

Send files without the need for email attachments.

This is an invitation-only feature. Contact the GOV.UK Notify team to enable this function for your service.

To send a file by email, add a placeholder field to the template then upload a file. The placeholder field will contain a secure link to download the file.

Add a placeholder field to the template

  1. Sign in.
  2. Go to the Templates page and select the relevant email template.
  3. Add a placeholder field to the email template using double brackets. For example:

"Download your file at: ((link_to_document))"

Upload your file

The file you upload must be a PDF file smaller than 2MB.

  1. Convert the PDF to a byte[].
  2. Pass the byte[] to the personalisation argument.
  3. Call the sendEmail method.

For example:

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("document_to_upload.pdf").getFile());
byte [] fileContents = FileUtils.readFileToByteArray(file);

HashMap<String, Object> personalisation = new HashMap();
personalisation.put("link_to_document", client.prepareUpload(fileContents));
client.sendEmail(templateId,
                 emailAddress,
                 personalisation,
                 reference,
                 emailReplyToId);

Error codes

If the request is not successful, the client returns an HTTPError containing the relevant error code.

error.status_code error.message How to fix
400 [{
"error": "BadRequestError",
"message": "Can't send to this recipient using a team-only API key"
]}
Use the correct type of 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"
}]
Your service cannot send this notification in trial mode
400 [{
"error": "BadRequestError",
"message": "Unsupported document type '{}'. Supported types are: {}"
}]
The document you upload must be a PDF file
400 [{
"error": "BadRequestError",
"message": "Document didn't pass the virus scan"
}]
The document you upload must be virus free
400 [{
"error": "BadRequestError",
"message": "Service is not allowed to send documents"
}]
Contact the GOV.UK Notify team
403 [{
"error": "AuthError",
"message": "Error: Your system clock must be accurate to within 30 seconds"
}]
Check your system clock
403 [{
"error": "AuthError",
"message": "Invalid token: signature, api token not found"
}]
Use the correct type of API key
429 [{
"error": "RateLimitError",
"message": "Exceeded rate limit for key type TEAM/TEST/LIVE of 3000 requests per 60 seconds"
}]
Refer to API rate limits for more information
429 [{
"error": "TooManyRequestsError",
"message": "Exceeded send limits (LIMIT NUMBER) for today"
}]
Refer to service limits for the limit number
500 [{
"error": "Exception",
"message": "Internal server error"
}]
Notify was unable to process the request, resend your notification.
N\A Document is larger than 2MB Document is larger than 2MB

Status - text and email

Status Information
Created GOV.UK Notify has placed the message in a queue, ready to be sent to the provider. It should only remain in this state for a few seconds.
Sending GOV.UK Notify has sent the message to the provider. The provider will try to deliver the message to the recipient. GOV.UK Notify is waiting for delivery information.
Delivered The message was successfully delivered.
Failed This covers all failure statuses:
- permanent-failure - "The provider could not deliver the message because the email address or phone number was wrong. You should remove these email addresses or phone numbers from your database. You’ll still be charged for text messages to numbers that do not exist."
- temporary-failure - "The provider could not deliver the message after trying for 72 hours. This can happen when the recipient's inbox is full or their phone is off. You can try to send the message again. You’ll still be charged for text messages to phones that are not accepting messages."
- technical-failure - "Your message was not sent because there was a problem between Notify and the provider.
You’ll have to try sending your messages again. You will not be charged for text messages that are affected by a technical failure."

Status - text only

Status Information
Pending GOV.UK Notify is waiting for more delivery information.
GOV.UK Notify received a callback from the provider but the recipient's device has not yet responded. Another callback from the provider determines the final status of the notification.
Sent / Sent internationally The message was sent to an international number. The mobile networks in some countries do not provide any more delivery information. The GOV.UK Notify client API returns this status as sent. The GOV.UK Notify client app returns this status as Sent internationally.

Get the status of one message

Method

Notification notification = client.getNotificationById(notificationId);

Arguments

notificationId (required)

The ID of the notification. You can find the notification ID in the response to the original notification method call.

You can also find it in your Dashboard.

  1. Sign in and select Dashboard.
  2. Select either emails sent or text messages sent
  3. Select the relevant notification.
  4. Copy the notification ID from the end of the page URL, for example https://notification.cdssandbox.xyz/services/af90d4cb-ae88-4a7c-a197-5c30c7db423b/notification/ID.

Response

If the request to the client is successful, the client returns a Notification:

UUID id;
Optional<String> reference;
Optional<String> emailAddress;
Optional<String> phoneNumber;
Optional<String> line1;
Optional<String> line2;
Optional<String> line3;
Optional<String> line4;
Optional<String> line5;
Optional<String> line6;
Optional<String> postcode;
Optional<String> postage;
String notificationType;
String status;
UUID templateId;
int templateVersion;
String templateUri;
String body;
Optional<String subject;
DateTime createdAt;
Optional<DateTime> sentAt;
Optional<DateTime> completedAt;
Optional<DateTime> estimatedDelivery;
Optional<String> createdByName;

Error codes

If the request is not successful, the client returns a NotificationClientException containing the relevant error code:

httpResult Message How to fix
400 [{
"error": "ValidationError",
"message": "id is not a valid UUID"
}]
Check the notification ID
403 [{
"error": "AuthError",
"message": "Error: Your system clock must be accurate to within 30 seconds"
}]
Check your system clock
403 [{
"error": "AuthError",
"message": "Invalid token: signature, api token not found"
}]
Use the correct API key. Refer to API keys for more information
404 [{
"error": "NoResultFound",
"message": "No result found"
}]
Check the notification ID

Get the status of multiple messages

This API call returns one page of up to 250 messages and statuses. You can get either the most recent messages, or get older messages by specifying a particular notification ID in the olderThanId argument.

You can only get the status of messages that are 7 days old or newer.

Method

NotificationList notification = client.getNotifications(
    status,
    notificationType,
    reference,
    olderThanId
);

To get the most recent messages, you must pass in an empty olderThanId argument or null.

To get older messages, pass the ID of an older notification into the olderThanId argument. This returns the next oldest messages from the specified notification ID.

Arguments

You can pass in empty arguments or null to ignore these filters.

status (optional)

status description text email letter Precompiled letter
created GOV.UK Notify has placed the message in a queue, ready to be sent to the provider. It should only remain in this state for a few seconds. Yes Yes
sending GOV.UK Notify has sent the message to the provider. The provider will try to deliver the message to the recipient. GOV.UK Notify is waiting for delivery information. Yes Yes
delivered The message was successfully delivered Yes Yes
sent / sent internationally The message was sent to an international number. The mobile networks in some countries do not provide any more delivery information. Yes
pending GOV.UK Notify is waiting for more delivery information.
GOV.UK Notify received a callback from the provider but the recipient's device has not yet responded. Another callback from the provider determines the final status of the notification.
Yes
failed This returns all failure statuses:
- permanent-failure
- temporary-failure
- technical-failure
Yes Yes
permanent-failure The provider could not deliver the message because the email address or phone number was wrong. You should remove these email addresses or phone numbers from your database. You’ll still be charged for text messages to numbers that do not exist. Yes Yes
temporary-failure The provider could not deliver the message after trying for 72 hours. This can happen when the recipient's inbox is full or their phone is off. You can try to send the message again. You’ll still be charged for text messages to phones that are not accepting messages. Yes Yes
technical-failure Email / Text: Your message was not sent because there was a problem between Notify and the provider.
You’ll have to try sending your messages again. You will not be charged for text messages that are affected by a technical failure.

Letter: Notify had an unexpected error while sending to our printing provider.

You can leave out this argument to ignore this filter.
Yes Yes
accepted GOV.UK Notify has sent the letter to the provider to be printed. Yes
received The provider has printed and dispatched the letter. Yes
pending-virus-check GOV.UK Notify is scanning the precompiled letter file for viruses. Yes
virus-scan-failed GOV.UK Notify found a potential virus in the precompiled letter file. Yes
validation-failed Content in the precompiled letter file is outside the printable area. Yes

notificationType (optional)

You can filter by:

  • email
  • sms

reference (optional)

A unique identifier you create if necessary. This reference identifies a single unique notification or a batch of notifications. It must not contain any personal information such as name or postal address.

String reference='STRING';

olderThanId (optional)

Input the ID of a notification into this argument. If you use this argument, the client returns the next 250 received notifications older than the given ID.

String olderThanId='8e222534-7f05-4972-86e3-17c5d9f894e2'

If you pass in an empty argument or null, the client returns the most recent 250 notifications.

Response

If the request to the client is successful, the client returns a NotificationList:

List<Notification> notifications;
String currentPageLink;
Optional<String> nextPageLink;

Error codes

If the request is not successful, the client returns a NotificationClientException containing the relevant error code:

httpResult Message
400 [{
"error": "ValidationError",
"message": "bad status is not one of [created, sending, sent, delivered, pending, failed, technical-failure, temporary-failure, permanent-failure, accepted, received]"
}]
Contact the GOV.UK Notify team
400 [{
"error": "ValidationError",
"message": "Applet is not one of [sms, email, letter]"
}]
Contact the GOV.UK Notify team
403 [{
"error": "AuthError",
"message": "Error: Your system clock must be accurate to within 30 seconds"
}]
Check your system clock
403 [{
"error": "AuthError",
"message": "Invalid token: signature, api token not found"
}]
Use the correct API key. Refer to API keys for more information

Get a template

Get a template by ID

Method

This returns the latest version of the template.

Template template = client.getTemplateById(templateId);

Arguments

templateId (required)

Sign in and go to the Templates page to find the template ID.

String templateId='f33517ff-2a88-4f6e-b855-c550268ce08a';

Response

If the request to the client is successful, the client returns a Template:

UUID id;
String name;
String templateType;
DateTime createdAt;
Optional<DateTime> updatedAt;
String createdBy;
int version;
String body;
Optional<String> subject;
Optional<Map<String, Object>> personalisation;

Error codes

If the request is not successful, the client returns a NotificationClientException containing the relevant error code:

httpResult Message How to fix
403 [{
"error": "AuthError",
"message": "Error: Your system clock must be accurate to within 30 seconds"
}]
Check your system clock
403 [{
"error": "AuthError",
"message": "Invalid token: signature, api token not found"
}]
Use the correct API key. Refer to API keys for more information
404 [{
"error": "NoResultFound",
"message": "No Result Found"
}]
Check your template ID

Get a template by ID and version

Method

Template template = client.getTemplateVersion(templateId, version);

Arguments

templateId (required)

Sign in and go to the Templates page to find the template ID.

String templateId='f33517ff-2a88-4f6e-b855-c550268ce08a';

version (required)

The version number of the template.

Response

If the request to the client is successful, the client returns a Template:

UUID id;
String name;
String templateType;
DateTime createdAt;
Optional<DateTime> updatedAt;
String createdBy;
int version;
String body;
Optional<String> subject;
Optional<Map<String, Object>> personalisation;

Error codes

If the request is not successful, the client returns a NotificationClientException containing the relevant error code:

httpResult message How to fix
400 [{
"error": "ValidationError",
"message": "id is not a valid UUID"
}]
Check the notification ID
403 [{
"error": "AuthError",
"message": "Error: Your system clock must be accurate to within 30 seconds"
}]
Check your system clock
403 [{
"error": "AuthError",
"message": "Invalid token: signature, api token not found"
}]
Use the correct API key. Refer to API keys for more information
404 [{
"error": "NoResultFound",
"message": "No Result Found"
}]
Check your template ID and version

Get all templates

Method

This returns the latest version of all templates.

TemplateList templates = client.getAllTemplates(templateType);

Arguments

templateType (optional)

If you don’t use templateType, the client returns all templates. Otherwise you can filter by:

  • email
  • sms

Response

If the request to the client is successful, the client returns a TemplateList:

List<Template> templates;

If no templates exist for a template type or there are no templates for a service, the templates list is empty.

Generate a preview template

Method

This generates a preview version of a template.

TemplatePreview templatePreview = client.getTemplatePreview(
    templateId,
    personalisation
);

The parameters in the personalisation argument must match the placeholder fields in the actual template. The API notification client ignores any extra fields in the method.

Arguments

templateId (required)

Sign in and go to the Templates page to find the template ID.

String templateId='f33517ff-2a88-4f6e-b855-c550268ce08a';

personalisation (required)

If a template has placeholder fields for personalised information such as name or application date, you must provide their values in a map. For example:

Map<String, Object> personalisation = new HashMap<>();
personalisation.put("first_name", "Amala");
personalisation.put("application_date", "2018-01-01");

If a template does not have any placeholder fields for personalised information, you must pass in an empty map or null.

Response

If the request to the client is successful, the client returns a TemplatePreview:

UUID id;
String templateType;
int version;
String body;
Optional<String> subject;
Optional<String> html;

Error codes

If the request is not successful, the client returns a NotificationClientException containing the relevant error code:

httpResult message How to fix
400 [{
"error": "BadRequestError",
"message": "Missing personalisation: [PERSONALISATION FIELD]"
}]
Check that the personalisation arguments in the method match the placeholder fields in the template
400 [{
"error": "NoResultFound",
"message": "No result found"
}]
Check the template ID
403 [{
"error": "AuthError",
"message": "Error: Your system clock must be accurate to within 30 seconds"
}]
Check your system clock
403 [{
"error": "AuthError",
"message": "Invalid token: signature, api token not found"
}]
Use the correct API key. Refer to API keys for more information