API request processing and validation
The API turns an HTTP request into a checked service operation and a stable JSON result. Middleware identifies the caller, a handler shapes and checks the input, and a service applies the business action. This page describes that path and the extra checks used for requests sent by a phone.
Request lifecycle
The request lifecycle separates transport concerns from business work. Route registration selects the handler and middleware, while the handler owns the request-specific checks and response choice.
This diagram shows the main path from an incoming request to its result.
flowchart LR
A[HTTP request] --> B[Auth middleware]
B --> C[Authenticated context]
C --> D[Handler]
D --> E[Bind request type]
E --> F[Sanitize input]
F --> G[Validate input]
G -->|invalid| H[Error response]
G -->|valid| I[Service call]
I --> J[Success or domain error]
J --> K[JSON response]
Route and authentication boundary
Routes are registered on the shared Fiber application. General API routes use the authenticated user context. Phone-facing routes add phone API key lookup before the same authentication gate, so the handler can apply both user identity and phone scope. api/…/container.go• L1745-1793.
Authentication middleware does not complete the request by itself. It places an AuthContext in the request context when a bearer token or API key is valid. The authenticated middleware rejects requests that have no usable context before the handler runs. api/…/api_key_auth_middleware.go• L13-37, api/…/phone_api_key_auth_middleware.go• L13-35, api/…/authenticated_middlesare.go• L20-35.
References: api/…/container.go• L1745-1793 api/…/api_key_auth_middleware.go• L13-37 api/…/phone_api_key_auth_middleware.go• L13-35 api/…/authenticated_middlesare.go• L20-35
Handler boundary
A handler is the boundary between HTTP and the service layer. It reads path, query, body, or form data into a request type, starts request tracing, and returns before the service call when the input cannot be used.
Handlers pass a context that carries the authenticated user and request trace. They convert a checked request into service parameters instead of passing raw HTTP data into business code. api/…/phone_handler.go• L69-92, api/…/message_handler.go• L83-111, api/…/contact_handler.go• L73-103.
References: api/…/phone_handler.go• L69-92 api/…/message_handler.go• L83-111 api/…/contact_handler.go• L73-103
Request types and input shaping
Request types define the input contract for each operation. They also provide a small shaping step that trims values, normalizes phone numbers, removes empty values, and applies safe defaults before validation.
Request normalization
Sanitization makes equivalent user input reach validation in one form. Phone values can be converted to international E.164 form, query values become typed service parameters, and contact values are trimmed and de-duplicated. Validation then checks the shaped value rather than the raw wire value. api/…/request.go• L16-53, api/…/request.go• L97-138.
The request type can also preserve client intent when an update supports partial fields. For example, phone updates inspect the original JSON body so an omitted field is different from a field sent with an empty or zero value. api/…/phone_update_request.go• L56-115.
References: api/…/request.go• L16-53 api/…/request.go• L97-138 api/…/phone_update_request.go• L45-115
Request format variants
Some endpoints accept more than one transport shape while keeping one service contract. Contact creation accepts either a JSON array or an object with a contacts array. Contact upload follows the same item rules after the CSV file is parsed. api/…/contact_store.go• L21-54, api/…/contact_handler_validator.go• L116-167.
The handler still treats a body that cannot be decoded, a missing upload, or an unusable query value as a malformed request. That check happens before semantic validation. api/…/contact_handler.go• L121-135, api/…/contact_handler.go• L171-186.
References: api/…/contact_store.go• L21-54 api/…/contact_handler_validator.go• L116-167 api/…/contact_handler.go• L121-135 api/…/contact_handler.go• L171-186
Validation boundary
Validation protects the service layer from malformed data and invalid business input. Validators return field-based errors, and handlers stop the flow when that set is not empty.
Structural and business validation
Structural rules check required fields, types, lengths, ranges, UUIDs, allowed values, and URL forms. Business checks then use services or other validators when a value must belong to the authenticated user or must pass an external rule. Examples include checking that a sending phone exists for the user and that a selected send schedule belongs to that user. api/…/message_handler_validator.go• L132-184, api/…/phone_handler_validator.go• L62-118.
Validation can also check data that is expensive or unsafe to pass onward. Attachment checks enforce allowed content types and decoded size limits. Contact upload checks the file type, file size, required columns, row count, and each contact item. api/…/message_handler_validator.go• L96-129, api/…/contact_handler_validator.go• L116-206.
References: api/…/message_handler_validator.go• L132-184 api/…/phone_handler_validator.go• L62-118 api/…/message_handler_validator.go• L96-129 api/…/contact_handler_validator.go• L116-206
Phone number validation
Phone numbers are a shared input contract because they identify phones, message owners, and contacts. The API uses international phone parsing for application phone numbers and contact numbers, then reports field errors when the value cannot be parsed or is not valid. api/…/validator.go• L32-93, api/…/contact_handler_validator.go• L170-205.
The same contract is applied to phone-facing message input. A phone number must identify the right destination or source, and the source phone must already be registered for the authenticated user before a send is accepted. api/…/message_handler_validator.go• L132-184.
References: api/…/validator.go• L32-93 api/…/contact_handler_validator.go• L170-205 api/…/message_handler_validator.go• L132-184
Service handoff
After validation, the handler converts the request into service parameters and calls one service operation. The service owns the business action and downstream effects, so the handler does not decide how data is stored, queued, or dispatched.
Business operation handoff
The handoff includes the authenticated user, normalized values, request source, and any operation-specific context. A message send therefore reaches the message service with a normalized owner and contact, while a phone update reaches the phone service with update intent preserved. api/…/message_send_request.go• L47-61, api/…/phone_update_request.go• L56-115.
The service result becomes the handler's response data. For message operations, the service can also create or dispatch events after persistence. The handler reports the accepted result without exposing those internal steps as a second API protocol. api/…/message_service.go• L73-106.
References: api/…/message_send_request.go• L47-61 api/…/phone_update_request.go• L56-115 api/…/message_service.go• L73-106
Entitlement checks
Some valid requests still cannot proceed because the account has reached a plan or usage limit. Handlers perform that check after input validation and before the service operation, then return a payment-required result when the action is not allowed. api/…/message_handler.go• L95-111, api/…/contact_handler.go• L131-153.
This ordering keeps invalid input separate from an account limit. It also prevents the service from starting work that the account cannot complete.
References: api/…/message_handler.go• L95-111 api/…/message_handler.go• L140-171 api/…/contact_handler.go• L131-153
Phone-facing requests
Phone-facing requests let the mobile phone report state and receive work through the API. They use phone API key authentication, but the handler still checks that the phone number in the request is within the key's allowed phone scope.
Phone input contract
Phone-facing endpoints validate both the message payload and the phone-specific fields. The main checks are:
| Input group | Purpose of the check |
|---|---|
| Phone number | Confirms an international phone value can identify the device or destination. |
| SIM value | Limits the request to a supported SIM slot. |
| Message event | Limits event names to known sent, failed, or delivered states. |
| Received message | Checks sender, destination, content, and attachment limits. |
| Missed call | Checks source, destination, and SIM data before recording the event. |
| Phone registration | Checks notification token, send limits, expiration, and optional schedule ownership. |
These checks protect downstream message state. They stop a phone from recording an unknown event, sending through an unregistered source, or submitting data that the service cannot safely process. api/…/message_handler_validator.go• L54-129, api/…/message_handler_validator.go• L349-394, api/…/phone_handler_validator.go• L62-164.
References: api/…/message_handler_validator.go• L54-129 api/…/message_handler_validator.go• L349-394 api/…/phone_handler_validator.go• L62-164
Phone authorization scope
Authentication proves which account owns a request. Phone authorization proves that a phone API key may act for the phone number named in that request. Message events, received messages, and missed calls apply this second check after payload validation and before the service call. api/…/handler.go• L41-46, api/…/handler.go• L156-162, api/…/message_handler.go• L303-324, api/…/message_handler.go• L362-373.
This two-part check matters because a valid phone key can be limited to selected phone numbers. A request with a valid key but an out-of-scope number receives an authorization error rather than reaching message processing.
References: api/…/handler.go• L41-46 api/…/handler.go• L156-162 api/…/message_handler.go• L303-324 api/…/message_handler.go• L362-373
Response and error handling
Handlers map each outcome to a consistent JSON envelope. The envelope carries a status and message, and successful or validation responses can carry data. This gives clients one way to read results across different API resources.
Outcome mapping
The main outcomes are mapped as follows:
| Outcome | HTTP status | Meaning |
|---|---|---|
| Malformed request | 400 | The body or transport value cannot be read. |
| Missing authentication or phone scope | 401 | The caller cannot act on the request. |
| Account limit | 402 | The action is valid but not allowed by the account plan. |
| Missing resource | 404 | The requested resource is not available to the caller. |
| Validation failure | 422 | The request is readable but fails field or business rules. |
| Unexpected service failure | 500 | The API could not complete the operation. |
The shared handler response methods keep these outcomes aligned. The response type definitions document the same status, message, and data shape for clients and API descriptions. api/…/handler.go• L18-114, api/…/response.go• L8-58.
References: api/…/handler.go• L18-114 api/…/response.go• L8-58
Service error translation
Handlers translate known repository outcomes into client-safe results, such as 404 for a missing phone or message. Other service errors are logged with request context and returned as a generic 500 response. This keeps internal failure detail out of the API while preserving trace data for diagnosis. api/…/phone_handler.go• L155-170, api/…/message_handler.go• L397-418.
Validation errors retain field names and one or more messages in the data object. Clients can therefore correct input without treating a business or transport failure as a server failure. api/…/handler.go• L56-61, api/…/response.go• L27-32.
References: api/…/phone_handler.go• L155-170 api/…/message_handler.go• L397-418 api/…/handler.go• L56-61 api/…/response.go• L27-32
For the wider placement of these handlers and services, see API service architecture.
Change checklist
When these files or sections are changed, remember to consider these:
- Keep route middleware order aligned with the authentication context required by the handler.
- Keep request sanitization and validator rules aligned so phone and contact values are normalized before all entry paths are checked.
- Keep phone-facing payload rules aligned with phone API key scope checks.
- Keep known repository error codes mapped to the same client status instead of exposing them as generic server errors.
- Keep response envelope fields aligned with the request types and the published API response types.
- When an update adds an optional field, preserve the difference between an omitted field and an explicit zero or empty value.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A route omits the authenticated middleware | The handler cannot safely read the user context. | Register protected routes with the authentication middleware. |
| A phone request uses a valid key for another phone number | The request could change or report another phone's state. | Apply phone scope checks before the service call. |
| A phone number passes shape checks but is not registered for the user | A message may be sent from a phone that cannot perform the operation. | Load the source phone during message validation. |
| An attachment exceeds type, count, or size rules | The phone or carrier may reject the message. | Validate attachment metadata and decoded content before service work. |
| A contact upload has missing columns or too many rows | The import cannot map safely to contact records. | Validate the CSV structure, size, and batch count. |
| A service returns a known not-found error and the handler ignores its code | The client receives a misleading 500 response. | Map repository not-found codes to 404. |
Key files
| File | Why to read it |
|---|---|
| api/…/container.go | Shows route registration and the middleware paths for general and phone-facing APIs. |
| api/…/handler.go | Defines shared context access, authorization scope checks, and response mapping. |
| api/…/message_handler.go | Shows the main send, receive, event, and phone-facing request flow. |
| api/…/phone_handler.go | Shows phone registration, update, and phone input processing. |
| api/…/contact_handler.go | Shows JSON and CSV input paths, entitlement checks, and resource errors. |
| api/…/request.go | Defines shared normalization for addresses and common request values. |
| api/…/validator.go | Defines shared phone, URL, event, and attachment validation rules. |
| api/…/message_handler_validator.go | Shows message and phone-facing payload checks. |
| api/…/contact_handler_validator.go | Shows contact item and CSV upload validation. |
| api/…/response.go | Defines the public response envelope types. |