Skip to main content
Table of contents

Python client documentation

This documentation is for developers interested in using the GOV.UK Notify Python client to send emails, text messages or letters. Notify supports Python 3.6 and higher.

Set up the client

Install the client

Run the following code in the command line:

pip install notifications-python-client

Refer to the client changelog for the client version number and the latest updates.

Create a new instance of the client

Add this code to your application:

from notifications_python_client.notifications import NotificationsAPIClient

notifications_client = NotificationsAPIClient(api_key)

Arguments

api_key (required)

To get an API key, sign in to GOV.UK Notify and go to the API integration page. You can find more information in the API keys section of this documentation.

timeout (optional)

The default timeout is 30 seconds. For more information about timeouts see https://docs.python-requests.org/en/latest/user/advanced/#timeouts.

Send a message

You can use GOV.UK Notify to send text messages, emails and letters.

Send a text message

Method

response = notifications_client.send_sms_notification(
    phone_number='+447900900123', # required string
    template_id='f33517ff-2a88-4f6e-b855-c550268ce08a', # required UUID string
)

Arguments

phone_number (required)

The phone number of the recipient of the text message. This can be a UK or international number.

template_id (required)

To find the template ID:

  1. Sign in to GOV.UK Notify.
  2. Go to the Templates page and select the relevant template.
  3. Select Copy template ID to clipboard.
personalisation (optional)

If a template has placeholder fields for personalised information such as name or reference number, you must provide their values in a dictionary with key value pairs. For example:

personalisation={
    'first_name': 'Amala',
    'application_date': '2018-01-01',
}

You can leave out this argument if a template does not have any placeholder fields for personalised information.

reference (optional)

A unique identifier you can create if necessary. This reference identifies a single unique message or a batch of messages. It must not contain any personal information such as name or postal address. For example:

reference='STRING', # optional string - identifies notification(s)

You can leave out this argument if you do not have a reference.

sms_sender_id (optional)

A unique identifier of the sender of the text message.

To find the text message sender:

  1. Sign in to GOV.UK Notify.
  2. Go to the Settings page.
  3. In the Text Messages section, select Manage on the Text Message sender row.

You can then either:

  • copy the sender ID that you want to use and paste it into the method
  • select Change to change the default sender that the service will use, and select Save
sms_sender_id='8e222534-7f05-4972-86e3-17c5d9f894e2' # optional UUID string

You can leave out this argument if your service only has one text message sender, or if you want to use the default sender.

Response

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

{
  "id": "740e5834-3a29-46b4-9a6f-16142fde533a",
  "reference": "STRING",
  "content": {
    "body": "MESSAGE TEXT",
    "from_number": "SENDER"
  },
  "uri": "https://api.notifications.service.gov.uk/v2/notifications/740e5834-3a29-46b4-9a6f-16142fde533a",
  "template": {
    "id": 'f33517ff-2a88-4f6e-b855-c550268ce08a',
    "version": INTEGER,
    "uri": "https://api.notifications.service.gov.uk/v2/template/ceb50d92-100d-4b8b-b559-14fa3b091cd"
  }
}

If you are using the test API key, all your messages will come back with a delivered status.

All messages sent using the team and guest list or live keys will appear on your dashboard.

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 text message 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: API key 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 text message.

Send an email

Method

response = notifications_client.send_email_notification(
    email_address='sender@something.com', # required string
    template_id='f33517ff-2a88-4f6e-b855-c550268ce08a', # required UUID string
)

Arguments

email_address (required)

The email address of the recipient.

template_id (required)

To find the template ID:

  1. Sign in to GOV.UK Notify.
  2. Go to the Templates page and select the relevant template.
  3. Select Copy template ID to clipboard.
personalisation (optional)

If a template has placeholder fields for personalised information such as name or reference number, you need to provide their values in a dictionary with key value pairs. For example:

personalisation={
    'first_name': 'Amala',
    'application_date': '2018-01-01',
}

You can leave out this argument if a template does not have any placeholder fields for personalised information.

reference (optional)

A unique identifier you can create if necessary. This reference identifies a single unique email or a batch of emails. It must not contain any personal information such as name or postal address. For example:

reference='STRING', # optional string - identifies notification(s)

You can leave out this argument if you do not have a reference.

email_reply_to_id (optional)

This is an email address specified by you to receive replies from your users. You must add at least one reply-to email address before your service can go live.

To add a reply-to email address:

  1. Sign in to GOV.UK Notify.
  2. Go to the Settings page.
  3. In the Email section, select Manage on the Reply-to email addresses row.
  4. Select Add reply-to address.
  5. Enter the email address you want to use, and select Add.

For example:

email_reply_to_id='8e222534-7f05-4972-86e3-17c5d9f894e2' # optional UUID string

You can leave out this argument if your service only has one reply-to email address, or you want to use the default email address.

Send a file by email

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

The file will be available for the recipient to download for 18 months.

The links are unique and unguessable. GOV.UK Notify cannot access or decrypt your file.

Add contact details to the file download page

  1. Sign in to GOV.UK Notify.
  2. Go to the Settings page.
  3. In the Email section, select Manage on the Send files by email row.
  4. Enter the contact details you want to use, and select Save.

Add a placeholder to the template

  1. Sign in to GOV.UK Notify.
  2. Go to the Templates page and select the relevant email template.
  3. Select Edit.
  4. Add a placeholder to the email template using double brackets. For example:

“Download your file at: ((link_to_file))”

Upload your file

You can upload PDF, CSV, .odt, .txt, .rtf, .xlsx and MS Word Document files. Your file must be smaller than 2MB. Contact the GOV.UK Notify team if you need to send other file types.

Pass the file object as a value into the personalisation argument. For example:

from notifications_python_client import prepare_upload

with open('file.pdf', 'rb') as f:
    ...
    personalisation={
      'first_name': 'Amala',
      'application_date': '2018-01-01',
      'link_to_file': prepare_upload(f),
    }
CSV Files

Uploads for CSV files should use the is_csv parameter on the prepare_upload() utility. For example:

from notifications_python_client import prepare_upload

with open('file.csv', 'rb') as f:
    ...
    personalisation={
      'first_name': 'Amala',
      'application_date': '2018-01-01',
      'link_to_file': prepare_upload(f, is_csv=True),
    }

Response

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

{
  "id": "740e5834-3a29-46b4-9a6f-16142fde533a",
  "reference": "STRING",
  "content": {
    "subject": "SUBJECT TEXT",
    "body": "MESSAGE TEXT",
    "from_email": "SENDER EMAIL"
  },
  "uri": "https://api.notifications.service.gov.uk/v2/notifications/740e5834-3a29-46b4-9a6f-16142fde533a",
  "template": {
    "id": "f33517ff-2a88-4f6e-b855-c550268ce08a",
    "version": INTEGER,
    "uri": "https://api.notifications.service.gov.uk/v2/template/f33517ff-2a88-4f6e-b855-c550268ce08a"
  }
}

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 email in trial mode
400 [{
"error": "BadRequestError",
"message": "Unsupported file type '(FILE TYPE)'. Supported types are: '(ALLOWED TYPES)'"
}]
Wrong file type. You can only upload .pdf, .csv, .txt, .doc, .docx, .xlsx, .rtf or .odt files
400 [{
"error": "BadRequestError",
"message": "File did not pass the virus scan"
}]
The file contains a virus
400 [{
"error": "BadRequestError",
"message": "Send files by email has not been set up - add contact details for your service at https://www.notifications.service.gov.uk/services/(SERVICE ID)/service-settings/send-files-by-email"
}]
See how to add contact details to the file download page
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: API key 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 email.
- ValueError('File is larger than 2MB') The file is too big. Files must be smaller than 2MB.

Send a letter

When you add a new service it will start in trial mode. You can only send letters when your service is live.

To send Notify a request to go live:

  1. Sign in to GOV.UK Notify.
  2. Go to the Settings page.
  3. In the Your service is in trial mode section, select request to go live.

Method

    response = notifications_client.send_letter_notification(
        template_id='f33517ff-2a88-4f6e-b855-c550268ce08a', # required UUID string
        personalisation={
          'address_line_1': 'The Occupier' # required string,
          'address_line_2': '123 High Street' # required string,
          'address_line_3': 'SW14 6BH' # required string,
        },
    )

Arguments

template_id (required)

To find the template ID:

  1. Sign in to GOV.UK Notify.
  2. Go to the Templates page and select the relevant template.
  3. Select Copy template ID to clipboard.
personalisation (required)

The personalisation argument always contains the following parameters for the letter recipient’s address:

  • address_line_1
  • address_line_2
  • address_line_3
  • address_line_4
  • address_line_5
  • address_line_6
  • address_line_7

The address must have at least 3 lines.

The last line needs to be a real UK postcode or the name of a country outside the UK.

Notify checks for international addresses and will automatically charge you the correct postage.

The postcode personalisation argument has been replaced. If your template still uses postcode, Notify will treat it as the last line of the address.

Any other placeholder fields included in the letter template also count as required parameters. You need to provide their values in a dictionary with key value pairs. For example:

personalisation={
  'address_line_1': 'The Occupier',
  'address_line_2': '123 High Street',
  'address_line_3': 'Richmond upon Thames',
  'address_line_4': 'Middlesex',
  'address_line_5': 'SW14 6BF',
  'name': 'John Smith',
  'application_id': '4134325'
}
reference (optional)

A unique identifier you can create if necessary. This reference identifies a single unique letter or a batch of letters. It must not contain any personal information such as name or postal address. For example:

reference='STRING' # optional string - identifies notification(s)

Response

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

{
  "id": "740e5834-3a29-46b4-9a6f-16142fde533a",
  "reference": 'STRING',
  "content": {
    "subject": "SUBJECT TEXT",
    "body": "LETTER TEXT",
  },
  "uri": "https://api.notifications.service.gov.uk/v2/notifications/740e5834-3a29-46b4-9a6f-16142fde533a",
  "template": {
    "id": "f33517ff-2a88-4f6e-b855-c550268ce08a",
    "version": INTEGER,
    "uri": "https://api.notifications.service.gov.uk/v2/template/f33517ff-2a88-4f6e-b855-c550268ce08a"
  }
  "scheduled_for": None
}

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": "Cannot send letters with a team api key"
}]
Use the correct type of API key
400 [{
"error": "BadRequestError",
"message": "Cannot send letters when service is in trial mode - see https://www.notifications.service.gov.uk/trial-mode"
}]
Your service cannot send this letter in trial mode.
400 [{
"error": "ValidationError",
"message": "personalisation address_line_1 is a required property"
}]
Ensure that your template has a field for the first line of the address, check personalisation for more information.
400 [{
"error": "ValidationError",
"message": "Must be a real UK postcode"
}]
Ensure that the value for the last line of the address is a real UK postcode.
400 [{
"error": "ValidationError",
"message": "Last line of address must be a real UK postcode or another country"
}]
Ensure that the value for the last line of the address is a real UK postcode or the name of a country outside the UK.
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: API key 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 letter.

Send a precompiled letter

Method

response = notifications_client.send_precompiled_letter_notification(
    reference,      # Reference to identify the notification
    pdf_file,       # PDF File object
    postage         # set postage on your precompiled letter
)

Arguments

reference (required)

A unique identifier you create. This reference identifies a single unique precompiled letter or a batch of precompiled letters. It must not contain any personal information such as name or postal address.

pdf_file (required)

The precompiled letter must be a PDF file which meets the GOV.UK Notify letter specification.

with open("path/to/pdf_file", "rb") as pdf_file:
    notification = notifications_client.send_precompiled_letter_notification(
        reference="your reference", pdf_file=pdf_file
    )
postage (optional)

You can choose first or second class postage for your precompiled letter. Set the value to first for first class, or second for second class. If you do not pass in this argument, the postage will default to second class.

Response

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

{
  "id": "740e5834-3a29-46b4-9a6f-16142fde533a",
  "reference": "your-letter-reference",
  "postage": "postage-you-have-set-or-None"
}

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": "Cannot send letters with a team api key"
}]
Use the correct type of API key
400 [{
"error": "BadRequestError",
"message": "Letter content is not a valid PDF"
}]
PDF file format is required
400 [{
"error": "BadRequestError",
"message": "Cannot send letters when service is in trial mode - see https://www.notifications.service.gov.uk/trial-mode"
}]
Your service cannot send this precompiled letter in trial mode
400 [{
"error": "ValidationError",
"message": "reference is a required property"
}]
Add a reference argument to the method call
400 [{
"error": "ValidationError",
"message": "postage invalid. It must be either first or second."
}]
Change the value of postage argument in the method call to either ‘first’ or 'second’
429 [{
"error": "RateLimitError",
"message": "Exceeded rate limit for key type live of 10 requests per 20 seconds"
}]
Use the correct API key. Refer to API keys for more information
429 [{
"error": "TooManyRequestsError",
"message": "Exceeded send limits (50) for today"
}]
Refer to service limits for the limit number

Get message status

Get the status of one message

You can only get the status of messages sent within the retention period. The default retention period is 7 days.

Method

response = notifications_client.get_notification_by_id(notification_id)

Arguments

notification_id (required)

The ID of the notification. To find the notification ID, you can either:

Response

If the request to the client is successful, the client will return a dict:

{
  "id": "740e5834-3a29-46b4-9a6f-16142fde533a", # required string - notification ID
  "reference": "STRING", # optional string
  "email_address": "sender@something.com",  # required string for emails
  "phone_number": "+447900900123",  # required string for text messages
  "line_1": "ADDRESS LINE 1", # required string for letter
  "line_2": "ADDRESS LINE 2", # required string for letter
  "line_3": "ADDRESS LINE 3", # optional string for letter
  "line_4": "ADDRESS LINE 4", # optional string for letter
  "line_5": "ADDRESS LINE 5", # optional string for letter
  "line_6": "ADDRESS LINE 6", # optional string for letter
  "line_7": "ADDRESS LINE 7", # required string for letter
  "type": "sms / letter / email", # required string
  "status": "sending / delivered / permanent-failure / temporary-failure / technical-failure", # required string
  "template": {
    "Version": INTEGER
    "id": 'f33517ff-2a88-4f6e-b855-c550268ce08a' # required string - template ID
    "uri": "/v2/template/{id}/{version}", # required
  },
  "body": "STRING", # required string - body of notification
  "subject": "STRING" # required string for email - subject of email
  "created_at": "STRING", # required string - date and time notification created
  "created_by_name": "STRING", # optional string - name of the person who sent the notification if sent manually
  "sent_at": "STRING", # optional string - date and time notification sent to provider
  "completed_at:" "STRING" # optional string - date and time notification delivered or failed
}

For more information, see the:

Error codes

If the request is not successful, the client will return an HTTPError containing the relevant error code:

error.status_code error.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: API key not found"
}]
Use the correct API key. Refer to API keys for more information
404 [{
"error": "NoResultFound",
"message": "No result found"
}]
Check when your message was sent. If it was sent before the retention period, it has been deleted. You can no longer get the status of this message. The default retention period is 7 days.

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 older_than argument.

You can only get the status of messages sent within the retention period. The default retention period is 7 days.

Method

All messages

This will return all your messages with statuses. They will display in pages of up to 250 messages each.

response = notifications_client.get_all_notifications(template_type, status, reference, older_than, include_jobs)

You can filter the returned messages by including the following optional arguments in the method:

One page of up to 250 messages

This will return 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 older_than argument.

To get the most recent messages, add the following code to your application:

response = get_all_notifications_iterator(status="sending")

You must set the status argument to sending.

To get older messages:

  1. Get the ID of an older message.
  2. Add the following code to your application, with the older notification ID in the older_than argument.
response = get_all_notifications_iterator(status="sending",older_than="NOTIFICATION ID")

You must set the status argument to sending.

This method will return the next oldest messages from the specified notification ID.

Arguments

template_type (optional)

You can filter by:

  • email
  • sms
  • letter

You can leave out this argument to ignore this filter.

status (optional)

You can filter by each:

If you filter by failed it will return all 3 failure statuses: permanent-failure, temporary-failure and technical-failure.

You can leave out this argument to ignore this filter.

reference (optional)

A unique identifier you can create if necessary. This reference identifies a single unique message or a batch of messages. It must not contain any personal information such as name or postal address. For example:

reference='STRING' # optional string - identifies notification(s)

You can leave out this argument to ignore this filter.

older_than (optional)

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

older_than='740e5834-3a29-46b4-9a6f-16142fde533a' # optional string - notification ID

If you leave out this argument, the method returns the most recent 250 messages.

The client only returns messages sent within the retention period. The default retention period is 7 days. If the message specified in this argument was sent before the retention period, the client returns an empty response.

include_jobs (optional)

Includes notifications sent as part of a batch upload.

If you leave out this argument, the method only returns notifications sent using the API.

Response

If the request to the client is successful, the client returns a dict.

All messages
{"notifications":
  [
    {
      "id": "740e5834-3a29-46b4-9a6f-16142fde533a", # required string - notification ID
      "reference": "STRING", # optional string - client reference
      "email_address": "sender@something.com",  # required string for emails
      "phone_number": "+447900900123",  # required string for text messages
      "line_1": "ADDRESS LINE 1", # required string for letter
      "line_2": "ADDRESS LINE 2", # required string for letter
      "line_3": "ADDRESS LINE 3", # optional string for letter
      "line_4": "ADDRESS LINE 4", # optional string for letter
      "line_5": "ADDRESS LINE 5", # optional string for letter
      "line_6": "ADDRESS LINE 6", # optional string for letter
      "postcode": "A REAL UK POSTCODE", # required string for letter
      "type": "sms / letter / email", # required string
      "status": "sending / delivered / permanent-failure / temporary-failure / technical-failure", # required string
      "template": {
        "version": INTEGER
        "id": 'f33517ff-2a88-4f6e-b855-c550268ce08a' # required string - template ID
        "uri": "/v2/template/{id}/{version}", # required
      },
      "body": "STRING", # required string - body of notification
      "subject": "STRING" # required string for email - subject of email
      "created_at": "STRING", # required string - date and time notification created
      "created_by_name": "STRING", # optional string - name of the person who sent the notification if sent manually
      "sent_at": " STRING", # optional string - date and time notification sent to provider
      "completed_at": "STRING" # optional string - date and time notification delivered or failed
    },
    
  ],
  "links": {
    "current": "/notifications?template_type=sms&status=delivered",
    "next": "/notifications?other_than=last_id_in_list&template_type=sms&status=delivered"
  }
}
One page of up to 250 messages
<generator object NotificationsAPIClient.get_all_notifications_iterator at 0x1026c7410>

For more information, see the:

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": "ValidationError",
"message": "status ‘elephant’ is not one of [cancelled, created, sending, sent, delivered, pending, failed, technical-failure, temporary-failure, permanent-failure, pending-virus-check, validation-failed, virus-scan-failed, returned-letter, accepted, received]"
}]
Change the status argument
400 [{
"error": "ValidationError",
"message": "‘Apple’ is not one of [sms, email, letter]"
}]
Change the template_type argument

Email status descriptions

Status Description
#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 for up to 72 hours. GOV.UK Notify is waiting for delivery information.
#delivered The message was successfully delivered.
#permanent-failure The provider could not deliver the message because the email address was wrong. You should remove these email addresses from your database.
#temporary-failure The provider could not deliver the message. This can happen when the recipient’s inbox is full or their anti-spam filter rejects your email. Check your content does not look like spam before you try to send the message again.
#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.

Text message status descriptions

Status Description
#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 for up to 72 hours. GOV.UK Notify is waiting for delivery 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 text message.
#sent 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 website displays this status as 'Sent to an international number’.
#delivered The message was successfully delivered.
#permanent-failure The provider could not deliver the message. This can happen if the phone number was wrong or if the network operator rejects the message. If you’re sure that these phone numbers are correct, you should contact GOV.UK Notify support. If not, you should remove them from your database. You’ll still be charged for text messages that cannot be delivered.
#temporary-failure The provider could not deliver the message. This can happen when the recipient’s phone is off, has no signal, or their text message inbox is full. 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.

Letter status descriptions

Status Description
#accepted GOV.UK Notify has sent the letter to the provider to be printed.
#received The provider has printed and dispatched the letter.
#cancelled Sending cancelled. The letter will not be printed or dispatched.
#technical-failure GOV.UK Notify had an unexpected error while sending the letter to our printing provider.
#permanent-failure The provider cannot print the letter. Your letter will not be dispatched.

Precompiled letter status descriptions

Status Description
#accepted GOV.UK Notify has sent the letter to the provider to be printed.
#received The provider has printed and dispatched the letter.
#cancelled Sending cancelled. The letter will not be printed or dispatched.
#pending-virus-check GOV.UK Notify has not completed a virus scan of the precompiled letter file.
#virus-scan-failed GOV.UK Notify found a potential virus in the precompiled letter file.
#validation-failed Content in the precompiled letter file is outside the printable area. See the GOV.UK Notify letter specification for more information.
#technical-failure GOV.UK Notify had an unexpected error while sending the letter to our printing provider.
#permanent-failure The provider cannot print the letter. Your letter will not be dispatched.

Get a PDF for a letter

Method

This returns the PDF contents of a letter.

pdf_file = notifications_client.get_pdf_for_letter(
  'f33517ff-2a88-4f6e-b855-c550268ce08a' # required string - notification ID
)

Arguments

notification_id (required)

The ID of the notification. To find the notification ID, you can either:

Response

If the request to the client is successful, the client will return a io.BytesIO object containing the raw PDF data.

Error codes

If the request is not successful, the client will return an HTTPError containing the relevant error code:

error.status_code error.message How to fix
400 [{
"error": "ValidationError",
"message": "id is not a valid UUID"
}]
Check the notification ID
400 [{
"error": "PDFNotReadyError",
"message": "PDF not available yet, try again later"
}]
Wait for the letter to finish processing. This usually takes a few seconds
400 [{
"error": "BadRequestError",
"message": "File did not pass the virus scan"
}]
You cannot retrieve the contents of a letter that contains a virus
400 [{
"error": "BadRequestError",
"message": "PDF not available for letters in technical-failure"
}]
You cannot retrieve the contents of a letter in technical-failure
400 [{
"error": "ValidationError",
"message": "Notification is not a letter"
}]
Check that you are looking up the correct notification
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: API key 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 a template

Get a template by ID

Method

This returns the latest version of the template.

response = notifications_client.get_template(
  'f33517ff-2a88-4f6e-b855-c550268ce08a' # required string - template ID
)

Arguments

template_id (required)

The ID of the template. Sign in to GOV.UK Notify and go to the Templates page to find it.

Response

If the request to the client is successful, the client returns a dict.

{
    "id": 'f33517ff-2a88-4f6e-b855-c550268ce08a', # required string - template ID
    "name": "STRING", # required string - template name
    "type": "sms / email / letter" , # required string
    "created_at": "STRING", # required string - date and time template created
    "updated_at": "STRING", # required string - date and time template last updated
    "version": INTEGER,
    "created_by": "someone@example.com", # required string
    "body": "STRING", # required string - body of notification
    "subject": "STRING" # required string for email - subject of email
    "letter_contact_block": "STRING" # optional string - None if not a letter template or contact block not set
}

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
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: API key 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

response = notifications_client.get_template_version(
    'f33517ff-2a88-4f6e-b855-c550268ce08a' # required string - template ID
    'version': INTEGER,
)

Arguments

template_id (required)

The ID of the template. Sign in to GOV.UK Notify and go to the Templates page to find it.

version (required)

The version number of the template.

Response

If the request to the client is successful, the client returns a dict.

{
    "id": 'f33517ff-2a88-4f6e-b855-c550268ce08a', # required string - template ID
    "name": "STRING", # required string - template name
    "type": "sms / email / letter" , # required string
    "created_at": "STRING", # required string - date and time template created
    "updated_at": "STRING", # required string - date and time template last updated
    "version": INTEGER,
    "created_by": "someone@example.com", # required string
    "body": "STRING", # required string - body of notification
    "subject": "STRING" # required string for email - subject of email
    "letter_contact_block": "STRING" # optional string - None if not a letter template or contact block not set
}

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
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: API key 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.

response = notifications_client.get_all_templates(
    template_type="sms / letter / email" # optional string
)

Arguments

template_type (optional)

If you leave out this argument, the method returns all templates. Otherwise you can filter by:

  • email
  • sms
  • letter

Response

If the request to the client is successful, the client returns a dict.

{
    "templates": [
        {
            "id": 'f33517ff-2a88-4f6e-b855-c550268ce08a', # required string - template ID
            "name": "STRING", # required string - template name
            "type": "sms / email / letter" , # required string
            "created_at": "STRING", # required string - date and time template created
            "updated_at": "STRING", # required string - date and time template last updated
            "version": NUMBER, # required string - template version
            "created_by": "someone@example.com", # required string
            "body": "STRING", # required string - body of notification
            "subject": "STRING" # required string for email - subject of email
            "letter_contact_block": "STRING" # optional string - None if not a letter template or contact block not set
        },
        {
            ...another template
        }
    ]
}

If no templates exist for a template type or there no templates for a service, the client returns a dict with an empty templates list element:

{
    "templates": []
}

Generate a preview template

Method

This generates a preview version of a template.

response = notifications_client.post_template_preview(
    template_id='f33517ff-2a88-4f6e-b855-c550268ce08a', # required UUID string
    personalisation={
        'KEY': 'VALUE',
        'KEY': 'VALUE',
        ...
        }, # required dict - specifies template parameters
)

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

Arguments

template_id (required)

The ID of the template. Sign in to GOV.UK Notify and go to the Templates page to find it.

personalisation (required)

If a template has placeholder fields for personalised information such as name or reference number, you need to provide their values in a dictionary with key value pairs. For example:

personalisation={
    'first_name': 'Amala',
    'application_date': '2018-01-01',
}

Response

If the request to the client is successful, you receive a dict response.

{
    "id": "740e5834-3a29-46b4-9a6f-16142fde533a", # required string - notification ID
    "type": "sms / email / letter" , # required string
    "version": INTEGER,
    "body": "STRING", # required string - body of notification
    "subject": "STRING" # required string for email - subject of email
}

Error codes

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

error.status_code error.message Notes
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: API key not found"
}]
Use the correct API key. Refer to API keys for more information

Get received text messages

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

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

Get all received text messages

This method returns a <generator object> with all received text messages.

Method

response = get_received_texts_iterator()

Response

If the request to the client is successful, the client will return a <generator object> that will return all received text messages.

<generator object NotificationsAPIClient.get_received_texts_iterator at 0x1026c7410>

Get one page of received text messages

This will return one page of up to 250 text messages.

Method

response = client.get_received_texts(older_than)

You can specify which text messages to receive by inputting the ID of a received text message into the older_than argument.

Arguments

older_than (optional)

Input the ID of a received text message into this argument. If you use this argument, the method returns the next 250 received text messages older than the given ID.

older_than='740e5834-3a29-46b4-9a6f-16142fde533a' # optional string - notification ID

If you leave out this argument, the method returns the most recent 250 text messages.

Response

If the request to the client is successful, the client returns a dict.

{
  "received_text_messages":
  [
    {
      "id": "STRING", # required string - ID of received text message
      "user_number": "STRING", # required string
      "notify_number": "STRING", # required string - receiving number
      "created_at": "STRING", # required string - date and time template created
      "service_id": "STRING", # required string - service ID
      "content": "STRING" # required string - text content
    },
    
  ],
  "links": {
    "current": "/received-text-messages",
    "next": "/received-text-messages?other_than=last_id_in_list"
  }
}

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
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: API key not found"
}]
Use the correct API key. Refer to API keys for more information

Testando

Todos os testes ocorrem no ambiente de produção. Não há ambiente de teste para Gov.br Notifica.

Teste de fumaça

Se você precisar de teste de fumaça no Notifica regularmente, você deve usar os seguintes números de telefone e endereços de e-mail para teste de fumaça.

 
Número de telefone
07700900000
07700900111
07700900222
Endereço de e-mail
simulate-delivered@notifications.service.gov.uk
simulate-delivered-2@notifications.service.gov.uk
simulate-delivered-3@notifications.service.gov.uk

Os números de telefone e endereços de e-mail do teste de fumaça validarão a solicitação e simularão uma resposta bem-sucedida, mas não enviarão uma mensagem real, produzirão um recibo de entrega ou manterão a notificação no banco de dados.

Você pode usar esses números e endereços de teste de fumaça com qualquer tipo de chave de API.

Você pode testar todas as funções do cliente Notificação API, exceto:

  • Obtenha o status de uma mensagem
  • Obtenha o status de todas as mensagens

Você não pode usar os números de telefone ou endereço de e-mail do teste de fumaça com essas funções porque eles retornam um falso notification_ID. Se você precisar testar essas funções, use uma chave API de teste e qualquer outro número de telefone ou e-mail.

Outros testes

Você deve usar uma chave de API de teste para fazer um teste sem fumaça, como teste de desempenho ou integração. Você pode usar qualquer número de telefone ou endereço de e-mail de teste que não seja de fumaça. Você não precisa de uma conta de teste específica do Gov.br Notifica.

Chaves da API

Existem três tipos diferentes de chaves de API:

  • teste
  • lista de equipe e de convidados
  • ao vivo

Quando você configura um novo serviço, ele começa em modo de teste. Um serviço em modo de teste pode criar chaves de lista de teste e equipe e de convidados. Você deve ter um serviço ativo para criar uma chave ativa.

Para criar uma chave de API:

  1. Faça login no Gov.br Notifica.
  2. Vá para a página de Integração da API.
  3. Selecione chaves de API.
  4. Selecione Criar uma chave da API.

Teste

Use uma chave de teste para testar o desempenho de seu serviço e sua integração com Gov.br Notifica.

Mensagens enviadas usando uma chave de teste:

  • gerar respostas realistas
  • resulta em um status entregue
  • não são realmente entregues a um destinatário
  • não aparecem no seu painel
  • não conte para as suas mensagens de texto e e-mail

Para testar as respostas de falha com uma chave de teste, use os seguintes números e endereços:

Número de telefone / endereço de e-mail Resposta
07700900003 temporary-failure
07700900002 permanent-failure
temp-fail@simulator.notify temporary-failure
perm-fail@simulator.notify permanent-failure
qualquer outro número ou endereço válido delivered

Você não precisa revogar as chaves de teste.

Equipe e lista de convidados

Uma chave de equipe e lista de convidados permite que você envie mensagens reais aos membros de sua equipe e endereços / números em sua lista de convidados enquanto seu serviço ainda está em modo de teste.

Você receberá um erro se usar essas teclas para enviar mensagens a alguém que não esteja em sua equipe ou na sua lista de convidados.

As mensagens enviadas com uma chave de equipe e lista de convidados aparecem em seu painel e contam em sua mensagem de texto e e-mail.

Você não precisa revogar as chaves da equipe e da lista de convidados.

Ao Vivo (Produção)

Você só pode criar chaves ativas (produção) quando o serviço estiver ativo (produção). Você pode usar as chaves ativas para enviar mensagens para qualquer pessoa.

As mensagens enviadas com uma chave ativa aparecem no seu painel e contam contra as suas mensagens de texto e e-mail.

Você deve revogar e recriar essas chaves regularmente. Para revogar uma chave:

  1. Faça login no Gov.br Notifica.
  2. Vá para a página de Integração da API.
  3. Selecione chaves de API.
  4. Selecione Revogar para a chave de API que você deseja revogar.

Você pode ter mais de uma chave ativa por vez.

Você nunca deve enviar mensagens de teste para números ou endereços inválidos usando uma chave ativa.

Limites

Limites de taxa

Você está limitado a enviar 1.000 mensagens por minuto.

Esse limite é calculado em uma base contínua, por tipo de chave de API. Se você exceder o limite, obterá o erro 429 RateLimitError.

Limites diários

Há um limite para o número de mensagens que você pode enviar por dia:

Status do serviço Tipo de chave API Limite diário
Ao vivo Equipe ou ao vivo 150,000
Trial Equipe 50
Ao vivo ou trial Teste Ilimitada

Esses limites são redefinidos à meia-noite.

Limites da rede telefônica

Se você enviar mensagens de texto repetidamente para o mesmo número, as redes telefônicas as bloquearão.

Existe um limite por hora de:

  • 20 mensagens com o mesmo conteúdo
  • 100 mensagens com qualquer conteúdo

Suas mensagens não podem ser entregues se você exceder esses limites.

Chamadas de retorno

Chamadas de retorno são quando o Gov.br Notifica envia solicitações POST para o seu serviço. Você pode obter retornos de chamada quando:

  • uma mensagem de texto ou e-mail que você enviou foi entregue ou falhou <!– seu serviço recebe uma mensagem de texto –>

Configurar chamadas de retorno

Você deve fornecer:

  • um URL onde o Gov.br Notifica postará o retorno para a chamada
  • um token de portador que o Gov.br Notifica colocará no cabeçalho de autorização das solicitações

Para fazer isso:

  1. Faça login no Gov.br Notifica.
  2. Vá para a página de Integração da API.
  3. Selecione Callbacks.

Recibos de entrega

Quando você envia um e-mail ou mensagem de texto, o Gov.br Notifica envia um recibo para o seu URL de retorno com o status da mensagem. Este é um método automatizado para obter o status das mensagens.

Esta funcionalidade funciona com chaves de API de teste, mas não funciona com números de telefone ou endereços de e-mail de teste de fumaça.

A mensagem de retorno de chamada é formatada em JSON. A chave, a descrição e o formato dos argumentos da mensagem de retorno de chamada serão:

Chave Descrição Formato
id ID de notificação para os recibos de status UUID
reference A referência enviada pelo serviço 12345678
to O endereço de e-mail ou número de telefone do destinatário hello@gov.uk ou 07700912345
status O status da notificação delivered, permanent-failure, temporary-failure ou technical-failure
created_at A hora em que o serviço enviou a solicitação 2017-05-14T12:15:30.000000Z
completed_at A última vez que o status foi atualizado 2017-05-14T12:15:30.000000Z ou nulo
sent_at A hora em que a notificação foi enviada 2017-05-14T12:15:30.000000Z ou nulo
notification_type O tipo de notificação email ou sms

Arquitetura da API

Envie uma mensagem

Importante ressaltar que a parte da resposta entre o recipient e o provider ainda não estão disponíveis no Notifica Gov.Br

Obter status da mensagem

Suporte

Relate quaisquer problemas através da página de suporte de notificação do Gov.br Notifica.