Introducing a new way to review your PRs.

Read the announcement

capcom6 / android-sms-gateway

The SMS Gateway for Android™ app enables sending and receiving SMS messages through an API that can be accessed directly on the device or via a cloud server when direct device access is not possible.

View on GitHub

20 documents · Updated Nov 20, 2026

docs / local-http-api

Local HTTP API

The Local HTTP API is an embedded web service that lets clients use the Android phone as an SMS and MMS gateway over the local network. It exposes health checks, device data, outgoing message control, inbox access, settings, logs, webhook management, and token management through JSON HTTP endpoints. Clients must first enable the local server in the app and then connect to the device address and configured port.

Service lifecycle

The local server runs as an Android foreground service when the app's local-server setting is enabled. The application orchestrator starts it with the other gateway services and stops it during application shutdown. The service publishes its active state to the app UI and keeps the device and Wi-Fi awake while it serves requests. app/…/LocalServerService.kt• L14-55, app/…/WebService.kt• L58-75, app/…/OrchestratorService.kt• L29-79

The server uses the configured port and local credentials when it starts. The default port is 8080 and the default username is sms; the password is created and stored when no password exists. Port, username, password, and token lifetime changes need a restart to affect the running service. The app shows the local address when it can find one on the device network. app/…/LocalServerSettings.kt• L7-63, app/…/LocalServerSettingsFragment.kt• L14-76, app/…/local_server_preferences.xml• L4-50

sequenceDiagram
    participant App as App orchestrator
    participant Service as Foreground web service
    participant Client as Local client
    App->>Service: Start when local server is enabled
    Service->>Service: Bind port and initialize auth
    Service-->>App: Publish active state
    Client->>Service: Send HTTP request
    Service-->>Client: Return JSON or file response
    App->>Service: Stop during shutdown
    Service->>Service: Release locks and stop server

HTTP interface

The API uses JSON for request and response bodies and serves all routes from the device's local HTTP address. GET /health is public and reports service health; the root, data, authentication, and documentation routes require either configured HTTP Basic credentials or a valid bearer token. A built-in Swagger UI is available under /docs, so a client can inspect the published API description from the running device. app/…/WebService.kt• L77-153, app/…/DocsRoutes.kt• L18-65

The server returns a JSON object with a message field for common request, authorization, not-found, and server errors. Successful writes use 202 Accepted when work is queued, 201 Created when a resource is created, and 204 No Content when a resource is removed. app/…/WebService.kt• L118-128, app/…/swagger.json• L1607-1840

Request and response models

The API models each client task as a small JSON object and returns domain data rather than transport-specific state. The main model groups are:

Model groupRequest shapeResponse shape
AuthenticationRequested scopes and optional token lifetimeAccess token, refresh token, token type, ID, and expiry
Outgoing messagesOne text, data, or MMS body with recipients and optional send controls; the legacy message field remains acceptedMessage ID, device ID, creation and scheduled times, state, recipient states, state history, and optional content
Inbox refreshRequired start and end times with optional message types and webhook delivery modeEmpty accepted response; later reads return stored inbox records
WebhooksOptional ID and device ID with target URL and eventThe stored webhook definition
SettingsA map of named setting groupsThe full grouped settings map
LogsOptional start and end times in query parametersLog priority, module, message, context, ID, and creation time

Dates use JSON date values. List endpoints use limit and offset for paging. Message and inbox lists also return X-Total-Count, which lets clients distinguish the current page from the full result set. app/…/TokenRequest.kt• L5-10, app/…/TokenResponse.kt• L6-17, app/…/PostMessageRequest.kt• L7-99, app/…/InboxRefreshRequest.kt• L7-14, app/…/InboxRoutes.kt• L217-233, app/…/GetLogsResponse.kt• L7-14

Route groups

The route groups map client tasks to the gateway capabilities below. /message and /messages are aliases for the outgoing message routes. /webhook and /webhooks are aliases for webhook routes. app/…/WebService.kt• L151-210

RoutePurposeMain actions
/healthCheck service health without credentialsGET
/Confirm an authenticated service responseGET
/deviceRead this device identity, key information, and active SIM cardsGET
/message, /messagesQueue, list, inspect, and cancel outgoing messagesGET, POST, GET /{id}, DELETE /{id}
/message/inbox, /messages/inboxExport phone inbox messages into the gateway inboxPOST /export
/inboxList received SMS and MMS records and refresh the phone inboxGET, POST /refresh
/inbox/{id}/attachments/{partId}Download one MMS attachmentGET
/webhook, /webhooksList, register, replace, and delete local webhooksGET, POST, DELETE /{id}
/settingsRead or update gateway settingsGET, PATCH
/logsRead log entries for a time rangeGET
/auth/tokenCreate, refresh, or revoke local bearer tokensPOST, POST /refresh, DELETE /{jti}
/docsServe the interactive API documentationGET

References: app/…/WebService.kt• L139-210 app/…/swagger.json• L2000-3440

Device access

The /device route gives an authenticated client the identity of the local gateway and the SIM cards that it can use. It returns a one-item list with the configured device ID, device name, install and activity times, active SIM data, and the current encryption public key and version. The route ensures that a device key exists before it builds this response. See Device identity and key management for the key lifecycle and identity model. app/…/DeviceRoutes.kt• L28-50, app/…/Device.kt• L21-30

The key fields are optional as a pair. If key creation fails, the device record can still be returned without them, so a client that needs encrypted message exchange must treat their absence as a device-readiness problem. app/…/DeviceService.kt• L47-67

References: app/…/DeviceRoutes.kt• L17-51 app/…/Device.kt• L5-30 app/…/DeviceService.kt• L47-67

Authentication and authorization

The API separates client login from permission checks. Basic authentication uses the local server username and password. A client can exchange those credentials for a short-lived access token and a refresh token. The access token carries scopes that control each route, while refresh-token use is limited to creating a new token pair. See Local API authentication for the token flow and scope rules. app/…/WebService.kt• L83-108, app/…/AuthRoutes.kt• L23-120, app/…/JwtService.kt• L44-155

The available permission areas are messages, inbox, devices, webhooks, settings, logs, and token management. Basic-authenticated requests bypass individual scope checks except where a route requires an exact refresh-token scope. Bearer-token requests receive 401 Unauthorized when they have no valid identity and 403 Forbidden when their scopes do not allow the action. app/…/AuthScopes.kt• L3-35, app/…/ScopeAuthorization.kt• L12-45

References: app/…/AuthScopes.kt• L3-35 app/…/ScopeAuthorization.kt• L12-45 app/…/AuthRoutes.kt• L27-119

Message access

The message routes provide the client-facing view of outgoing SMS and MMS work. A client submits exactly one text, data, or MMS message with one or more phone numbers. The legacy message field remains available for older clients, while newer clients use the matching message object. An MMS can contain text, a subject, and base64-encoded attachments. The gateway accepts optional scheduling, expiry, SIM selection, delivery-report, encryption, priority, and device fields, then places the message in the local send queue. A successful submission returns the message state with 202 Accepted; a repeated message ID returns a conflict. See Message processing and Outbound message delivery for the work that follows queueing. app/…/MessagesRoutes.kt• L137-225, app/…/PostMessageRequest.kt• L7-99, app/…/MmsMessage.kt• L3-21

Message reads return state rather than only the original request. The response identifies the message and device, reports overall and per-recipient state, preserves state history, and includes creation and scheduled times. When content is requested, the response can include text, data, or MMS content with its subject, text, and attachments. List responses support state, date, device, page, sort, and content filters. Content is omitted from list results unless includeContent=true; the total matching count is returned in X-Total-Count. app/…/MessagesRoutes.kt• L53-135, app/…/MessagesRoutes.kt• L226-246, app/…/Message.kt• L6-26, app/…/MmsMessage.kt• L3-21

Cancellation applies to a message by ID and is intended for pending work. The gateway returns the state after cancellation, or an error when the message does not exist or cannot be cancelled in its current state. app/…/MessagesRoutes.kt• L248-276

Inbox access

The inbox routes expose records that the phone has received and that the gateway has stored. A list request can filter by message type and time range and can page through results. Each record includes its ID, type, sender, recipient when known, SIM number when known, a content preview, and creation time. The response uses X-Total-Count for the full match count. See Inbound SMS and MMS capture for how phone messages reach this store. app/…/InboxRoutes.kt• L39-152, app/…/IncomingMessage.kt• L7-30

MMS records can include attachment metadata when includeAttachments=true. The client downloads attachment bytes through the attachment route by using the inbox message ID and part ID. The response has an attachment content type and download name. app/…/InboxRoutes.kt• L53-61, app/…/InboxRoutes.kt• L154-178

An inbox refresh asks the phone receiver to export a selected time range. The request can select SMS or MMS and can choose disabled, individual, or batch webhook delivery. The refresh is asynchronous and returns 202 Accepted after the export is accepted. The message export route under the message aliases provides the same phone-inbox export action with different default webhook behavior for compatibility. See Webhook delivery for the later callback work. app/…/InboxRoutes.kt• L180-214, app/…/MessagesRoutes.kt• L279-299, app/…/WebhookDelivery.kt• L5-14

References: app/…/InboxRoutes.kt• L39-214 app/…/MessagesRoutes.kt• L279-299 app/…/InboxRefreshRequest.kt• L7-43

Settings and logs

The settings routes expose the app settings that support API export and import. GET /settings returns grouped settings for encryption, gateway, incoming messages, outgoing messages, ping, logs, and webhooks. PATCH /settings accepts a map of changed groups, applies valid values, and returns the full current settings map. A change notification tells the user to restart the app when a setting needs a new service lifecycle. See Configuration management for the wider settings model. app/…/SettingsRoutes.kt• L23-55, app/…/SettingsService.kt• L25-63

The logs route returns stored log entries and can limit the result to an ISO date-time range. Each entry carries its priority, module, message, optional structured context, ID, and creation time. Invalid date input is reported as a bad request. See Operational logs for the log system that supplies these records. app/…/LogsRoutes.kt• L24-40, app/…/GetLogsResponse.kt• L7-24, app/…/LogEntry.kt• L8-23

References: app/…/SettingsRoutes.kt• L14-55 app/…/SettingsService.kt• L14-63 app/…/LogsRoutes.kt• L14-40

Webhook management

The webhook routes manage callbacks that the gateway sends when local events occur. A webhook has an optional ID, an optional device ID, a target URL, an event name, and a source. Listing returns local webhooks. Posting creates or replaces a webhook with the same ID, and deleting removes it by ID. See Webhook delivery for event creation and delivery. app/…/WebhooksRoutes.kt• L18-50, app/…/WebHookDTO.kt• L5-11

Supported event families cover received, sent, delivered, failed, cancelled, and data SMS; received and downloaded MMS; system ping; and app start. Received and downloaded message events also have batch forms where the event model supports batching. The webhook worker later delivers these events, so a successful registration does not mean that a callback has already been sent. Local webhook callbacks must use HTTPS, except that HTTP is allowed for loopback targets and for insecure development builds. app/…/WebHookEvent.kt• L5-54, app/…/WebHooksService.kt• L79-120, app/…/WebHooksService.kt• L126-181

References: app/…/WebhooksRoutes.kt• L18-50 app/…/WebHookDTO.kt• L5-11 app/…/WebHookEvent.kt• L5-54

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the route aliases aligned when changing message or webhook paths. Clients may use either singular or plural forms.
  • Keep route scope checks aligned with AuthScopes. A new route without a matching scope can expose the wrong access level.
  • Keep the /device response fields aligned with the device identity contract. The public key and key version must remain an optional pair.
  • Keep local server settings validation aligned with the service restart rule. A changed port or credential does not update an already running server.
  • Keep request models and the Swagger contract aligned for message variants, legacy fields such as message, expiry aliases such as ttl and validUntil, and deprecated fields such as triggerWebhooks.
  • Keep message response mappings aligned with the public model when adding fields such as createdAt, so list and single-message reads expose the same time data.
  • Keep X-Total-Count behavior aligned with list pagination so clients can advance through message and inbox results.
  • Keep webhook event names and WebhookDelivery values aligned with the event queue and callback payloads.

Important failure modes

TriggerConsequenceGuard
Local server is disabled or the foreground service cannot start in the backgroundThe local address does not accept requests even though other gateway work may continueCheck the server active state and the app's foreground notification before connecting
Port, username, password, or JWT settings change while the service is runningThe running listener continues to use its old valuesRestart the app after local server setting changes
A bearer token lacks the scope required by a routeThe server returns 403 Forbidden and does not perform the actionRequest only the scopes the client needs and renew tokens through the refresh flow
A token is expired, revoked, or reused as a refresh tokenThe server returns 401 UnauthorizedStore the newest token pair and discard a refresh token after rotation
A message request has more than one content type, empty content, duplicate recipients, or an invalid MMS bodyThe server rejects the request as invalidSend one non-empty text, data, or MMS message; use unique phone numbers; an MMS needs text or at least one attachment
A message request sets both ttl and validUntil, or schedules a message in the pastThe server rejects the request as invalidSet one expiry form and use a future scheduleAt value
An inbox or message date range has a start after its endThe server returns 400 Bad RequestValidate ISO date ranges before sending requests
An MMS attachment was removed or its file is not presentThe attachment route returns 404 Not FoundTreat attachment metadata as a reference and handle missing files
Device key creation fails during a device readThe response can omit the public key and key version, so encrypted device exchange cannot startTreat a missing key pair as a readiness failure and review device logs
A webhook target is registered successfully but delivery later failsThe event remains subject to the webhook queue and retry behaviorUse the logs and webhook delivery settings to monitor delivery

Key files

FileWhy to read it
app/…/WebService.ktDefines the embedded server, shared middleware, lifecycle hooks, and top-level route map
app/…/LocalServerService.ktConnects the app orchestrator and UI state to the web service lifecycle
app/…/AuthScopes.ktDefines the permission areas available to local API clients
app/…/JwtService.ktExplains token creation, expiry, refresh rotation, and revocation at a high level
app/…/DeviceRoutes.ktDefines the authenticated device and SIM data returned to local clients
app/…/Device.ktDefines the device identity response, including the optional public-key pair
app/…/MessagesRoutes.ktShows the outgoing message, MMS, and phone-inbox export contract
app/…/PostMessageRequest.ktDefines accepted outgoing message variants and request validation rules
app/…/Message.ktDefines the local API message response, including creation time, state history, recipients, and optional content
app/…/MmsMessage.ktDefines the local API shape for outgoing MMS text, subjects, and attachments
app/…/InboxRoutes.ktShows received-message, MMS attachment, and inbox refresh access
app/…/WebhooksRoutes.ktShows local webhook registration and deletion
app/…/SettingsRoutes.ktShows grouped settings read and update behavior
app/…/swagger.jsonProvides the client-facing OpenAPI route and schema contract