# app/v2/notifications/post_notifications.py
from flask import request, jsonify
from app.v2.notifications import v2_notification_blueprint
from app.schema_validation import validate
from app.v2.notifications.notification_schemas import post_sms_request_schema
from app.notifications.process_notifications import (
persist_notification,
send_notification_to_queue,
)
@v2_notification_blueprint.route('/sms', methods=['POST'])
def post_sms_notification():
"""
Send an SMS notification
POST /v2/notifications/sms
{
"phone_number": "+447700900123",
"template_id": "...",
"personalisation": {...},
"reference": "..."
}
"""
request_json = request.get_json()
# 1. Validate request
validate(request_json, post_sms_request_schema)
# 2. Load service from auth
service = services_dao.dao_fetch_service_by_id(g.service_id)
# 3. Load template
template = templates_dao.dao_get_template_by_id_and_service_id(
template_id=request_json['template_id'],
service_id=service.id,
)
# 4. Validate and format recipient
recipient_data = validate_and_format_recipient(
send_to=request_json['phone_number'],
key_type=g.api_user.key_type,
service=service,
notification_type=SMS_TYPE,
)
# 5. Check rate limits
check_service_over_daily_message_limit(
service,
g.api_user.key_type,
notification_type=SMS_TYPE,
)
# 6. Persist notification
notification = persist_notification(
template_id=template.id,
template_version=template.version,
recipient=recipient_data,
service=service,
personalisation=request_json.get('personalisation'),
notification_type=SMS_TYPE,
api_key_id=g.api_user.id,
key_type=g.api_user.key_type,
client_reference=request_json.get('reference'),
)
# 7. Queue for delivery
send_notification_to_queue(notification, research_mode=False)
# 8. Return response
return jsonify(
id=str(notification.id),
reference=notification.client_reference,
uri=url_for(
'v2_notifications.get_notification_by_id',
notification_id=notification.id,
_external=True
),
template={
"id": str(template.id),
"version": template.version,
"uri": template.get_link(),
},
content={
"body": str(notification.content),
},
), 201