Mobile Application Development

Chapter 7
Networking, APIs and Cloud-Connected Services

Bachelors Program in IT
Mobile Application Development   •   Bachelor

Networking, APIs and Cloud-Connected Services

Introduction

Most modern mobile applications are not isolated programs. They obtain data from remote services, authenticate users through identity providers, upload media to cloud storage, synchronize changes across devices, and receive events through push notifications. Networking therefore changes the nature of application development: the application must operate across systems that may be slow, unavailable, inconsistent, insecure, or only partially compatible.

This chapter examines the principles and practices required to build reliable cloud-connected mobile applications. It focuses on REST, GraphQL, real-time communication, JSON processing, authentication, pagination, error handling, unreliable networks, cloud backends, serverless services, push notifications, and resilient API design.

Learning Objectives

By the end of this chapter, students should be able to:

  1. Explain the roles of clients, APIs, application servers, databases, identity providers, and cloud services.
  2. Compare REST, GraphQL, and real-time communication models.
  3. Design and consume JSON-based APIs safely.
  4. Apply authentication, authorization, pagination, validation, and error-handling strategies.
  5. Design mobile applications that tolerate latency, disconnection, retries, and partial failure.
  6. Explain the use of cloud databases, object storage, serverless functions, and push notifications.
  7. Evaluate an API for security, scalability, maintainability, and user experience.

1. The Mobile Networking Model

A typical mobile request passes through several layers:

  • Mobile client: the application running on a phone or tablet.
  • Transport layer: commonly HTTPS over TCP; newer systems may use HTTP/2 or HTTP/3.
  • API gateway or load balancer: routes requests, applies policies, and may terminate TLS.
  • Application service: validates input and implements business rules.
  • Data services: databases, caches, search engines, queues, and object storage.
  • Identity provider: authenticates users and issues credentials.
  • External services: payment, mapping, analytics, messaging, or artificial-intelligence services.

A request is not guaranteed to succeed merely because the code is correct. The device may lose connectivity, the user may switch networks, a server may be overloaded, or a response may arrive after the user has left the screen. Networking must consequently be treated as an asynchronous and failure-prone operation.

A useful performance approximation is:

Ttotal = Tdns + Tconnect + Ttls + Trequest + Tserver + Tresponse

Here, Ttotal is total elapsed time; Tdns is name-resolution time; Tconnect is connection-establishment time; Ttls is TLS negotiation time; Trequest and Tresponse are data-transfer times; and Tserver is server processing time. This is an approximate decomposition, not an exact universal model. Some phases can be avoided through connection reuse, caching, or protocol features. All terms represent time and must use the same unit, such as milliseconds.

2. HTTP and API Fundamentals

HTTP requests contain a method, URL, headers, and sometimes a body. Common methods include:

MethodTypical purposeIdempotency expectation
GETRetrieve a representationYes
POSTCreate a resource or perform an actionUsually no
PUTReplace a resourceYes
PATCHPartially modify a resourceDepends on implementation
DELETERemove a resourceYes

An operation is idempotent if repeating it has the same intended effect as performing it once. Idempotency does not mean that every response is identical. For example, repeating a successful DELETE may produce a “not found” response, but the intended state remains deleted.

HTTP status codes communicate broad outcomes. Successful responses generally use 200–299; redirects use 300–399; client errors use 400–499; and server or gateway errors use 500–599. A client should not treat every non-200 response as identical. A 401 response indicates missing or invalid authentication, a 403 indicates insufficient permission, a 404 indicates that a resource is unavailable at the requested location, a 409 indicates a conflict, a 429 indicates rate limiting, and a 503 commonly indicates temporary service unavailability.

Good APIs also communicate machine-readable error details. A useful error object may contain a stable code, a human-readable message, field-level validation information, and a correlation identifier. Human-facing text should be localized by the mobile application where possible rather than displayed directly from a server.

3. REST API Design

REST, or Representational State Transfer, organizes information as resources identified by URLs. A REST API commonly uses HTTP methods and status codes to operate on resource representations.

For example:

  • GET /v1/products/42 retrieves product 42.
  • POST /v1/orders creates an order.
  • PATCH /v1/profile changes selected profile fields.
  • DELETE /v1/sessions/current terminates a session.

Important REST design principles include:

  1. Stateless requests: each request contains the information needed for processing; server-side session state should not be required for basic request interpretation.
  2. Stable resource identifiers: URLs should identify resources rather than user-interface actions.
  3. Representations: JSON is a common representation, but the resource itself is conceptually separate from its representation.
  4. Explicit semantics: methods, status codes, headers, and documented schemas should communicate behavior.
  5. Versioning: breaking changes can be managed through a version such as /v1, a media type, or a compatible evolution strategy.

REST is straightforward, cache-friendly, and widely supported. However, mobile clients may receive too much or too little data, and a screen requiring several resources may require multiple requests.

4. GraphQL

GraphQL exposes a typed schema through which clients request the fields they need. A query might request a user and selected orders in one operation. The server validates the query against the schema and returns a response shaped approximately like the query.

GraphQL offers:

  • precise field selection;
  • a discoverable type system;
  • fewer endpoint-specific response shapes;
  • the ability to combine related data requests.

Its challenges include query complexity, caching difficulty, authorization at field or resolver level, and the risk of expensive nested queries. A GraphQL server should impose depth, cost, and rate limits. Sensitive fields must be authorized independently; hiding a field in the user interface is not a security control.

REST and GraphQL are not mutually exclusive. An organization may use REST for public resources and file transfers while using GraphQL for data-rich application screens.

5. Real-Time Services

Ordinary request-response communication requires the client to ask for updates. Real-time systems allow the server to deliver events when state changes.

  • Polling: the client periodically requests updates. It is simple but can waste bandwidth and create delay.
  • Long polling: the server holds a request until data is available or a timeout occurs.
  • Server-Sent Events: the server sends a one-way event stream over an HTTP connection.
  • WebSocket: the client and server maintain a bidirectional channel.
  • Managed real-time platforms: cloud services provide synchronization, presence, or event delivery without requiring the team to operate all infrastructure.

Real-time delivery is generally at-least-once rather than exactly-once. Events can be duplicated, delayed, or delivered out of order. Each event should therefore have an identifier, a type, a timestamp or sequence number, and enough information for deduplication or reconciliation. The client should be able to resynchronize from authoritative server state after reconnecting.

6. JSON and Data Modeling

JSON represents objects, arrays, strings, numbers, booleans, and null. A robust client should treat server data as untrusted input. It should validate required fields, handle unknown fields compatibly, distinguish missing from null where the contract requires it, and avoid assuming that all numeric values fit safely into a platform integer type.

A versioned response might contain:

{
  "data": {
    "id": "ord_91",
    "status": "paid",
    "total": { "amount": 2499, "currency": "USD" }
  },
  "meta": { "requestId": "7f2c" }
}

Money should generally be represented as an integer minor unit, such as cents, plus a currency code, rather than as a binary floating-point value. Dates should use an unambiguous standard such as an ISO 8601 representation and should include timezone information or clearly define that values are UTC.

Backward-compatible API evolution usually adds optional fields rather than changing the meaning or type of existing fields. Clients should ignore unknown fields, while servers should avoid removing fields until supported client versions have migrated.

7. Authentication and Authorization

Authentication answers “Who is the caller?” Authorization answers “What may the caller do?” These are separate decisions.

Common approaches include:

  • Session cookies: the server maintains session state and the client sends a secure cookie.
  • Access tokens: a client presents a short-lived bearer token, often in the Authorization header.
  • OAuth 2.0 and OpenID Connect: delegated authorization and identity protocols commonly used with external identity providers.
  • API keys: useful for identifying applications or low-risk server-to-server access, but generally unsuitable as the sole protection for sensitive user data.

Mobile applications should use HTTPS, avoid embedding long-lived secrets in the application package, store credentials in platform-provided secure storage, and request the minimum permissions necessary. Access tokens should be short-lived. Refresh tokens require particularly careful storage, revocation, rotation, and threat analysis.

Authorization must be enforced on the server for every protected operation. A client-side check improves usability but cannot prevent a malicious caller from directly invoking an API. Logs must not expose passwords, raw tokens, payment data, or unnecessary personal information.

8. Pagination, Filtering, and Sorting

Returning a complete collection is often unsafe for mobile devices and servers. Pagination limits response size and improves responsiveness.

Offset pagination uses parameters such as limit=20&offset=40. It is easy to understand but can skip or duplicate records when items are inserted or deleted during traversal.

Cursor pagination returns a token representing a position in a stable ordering. The client sends that cursor to obtain the next page. Cursor pagination is usually more reliable for changing datasets, but cursors should be treated as opaque values.

A good collection API documents maximum page size, default ordering, filters, and whether a next-page token is present. The client must handle an empty page, an expired cursor, and changes between requests. Infinite scrolling should preserve the last successfully loaded cursor and prevent concurrent duplicate loads.

9. Unreliable Networks and Resilient Clients

A resilient client separates transient failures from permanent failures. Timeouts, temporary DNS failures, connection resets, and many 5xx responses may be transient. Invalid input, insufficient permission, and malformed requests generally require correction rather than repetition.

A retry policy should include:

  1. a bounded number of attempts;
  2. a timeout for each attempt;
  3. exponential backoff;
  4. random jitter to avoid synchronized retries;
  5. cancellation when the screen or operation is no longer relevant;
  6. idempotency protection for operations that create or charge resources.

A basic exponential schedule is:

tn = min(tmax, t0 × 2n)

tn is the delay before retry n, t0 is the initial delay, tmax is the maximum delay, and n begins at 0 for the first retry. The formula assumes a transient failure and a finite retry limit. In practice, random jitter is added, for example by selecting a delay uniformly between zero and tn, to reduce synchronized load. The units of all delay variables must match.

Retries are dangerous when a request may have succeeded but its response was lost. An idempotency key allows the server to recognize repeated attempts as one logical operation. This is especially important for payments, order creation, and message submission.

Mobile applications commonly use these states:

  • loading;
  • loaded;
  • empty;
  • refreshing;
  • offline with cached data;
  • retryable error;
  • permanent error;
  • unauthorized;
  • partially loaded.

The user interface should explain what can be done next rather than merely displaying a technical exception. Local caching can provide fast startup and offline reading. Write operations require a carefully designed synchronization policy, conflict handling, and clear user feedback.

10. Cloud-Connected Architecture

Cloud backends commonly combine managed and custom services:

ServiceTypical responsibility
Managed databaseStructured or document data, indexing, transactions
Object storageImages, videos, documents, backups
CacheLow-latency temporary data
Queue or event busDecoupling and asynchronous processing
Serverless functionEvent-driven or request-driven business logic
Identity serviceUser registration, login, federation, token issuance
Notification servicePush delivery and device-token management
Observability serviceLogs, metrics, traces, and alerts

Serverless functions can scale automatically and reduce infrastructure management. They are useful for image processing, webhooks, scheduled jobs, and lightweight API operations. Their limitations include cold-start latency, execution limits, vendor-specific behavior, distributed debugging, and the need for idempotent event processing.

A cloud architecture should define ownership of data, backups, recovery objectives, access policies, regional placement, and costs. “Managed” does not mean “automatically secure.” Misconfigured storage permissions, excessive database privileges, exposed logs, and unbounded function invocation remain application responsibilities.

11. Push Notifications

Push notification systems generally involve three parties: the application, a provider-specific device service, and a cloud messaging provider. The application obtains a device token, sends that token securely to the backend, and the backend requests delivery through the messaging provider.

A notification is not a guaranteed command channel. Delivery may be delayed, suppressed, duplicated, or unavailable. Notifications should therefore contain a small reference to authoritative server data rather than sensitive information or the complete state of an object. When the user opens the application, it should fetch current state and process the event safely.

Applications must request permission appropriately, respect platform policies, provide meaningful notification controls, and avoid excessive or manipulative alerts. Notification tokens can change and must be refreshed. The backend should remove invalid tokens and record delivery outcomes without retaining unnecessary personal data.

12. Case Study: A Campus Event Application

Background

Consider the illustrative case of CampusConnect, a mobile application through which students discover events, reserve places, receive schedule changes, and check in using a QR code.

Problem

The initial application downloaded all events at launch, used a permanent API key embedded in the app, and assumed that every booking request received exactly one response. During registration periods, the API became slow, duplicate bookings appeared, and users received stale event schedules.

Analysis

The system had several design weaknesses. It lacked authenticated user identity, returned an unbounded collection, had no request timeout or retry policy, and treated a push notification as authoritative data. Booking was not protected by an idempotency key. The database also lacked a constraint preventing the same student from booking the same event twice.

Approach and Solution

The redesigned system used OAuth 2.0/OpenID Connect for login and short-lived access tokens. GET /v1/events used cursor pagination and filters for date, campus, and category. Event responses included an update timestamp and an opaque version identifier.

Booking used POST /v1/events/{id}/bookings with a client-generated idempotency key. The server stored the key with the result and enforced a uniqueness constraint on student and event. Temporary failures could be retried safely; validation and capacity errors were shown without retrying.

The application cached recently viewed events, displayed stale data with a refresh indicator, and synchronized after reconnection. Push messages contained an event identifier and change type. Opening the notification caused the client to retrieve the current event, so an outdated notification could not overwrite newer state.

Outcome

The new design reduced unnecessary downloads, prevented duplicate bookings, and improved behavior during weak connectivity. It also made failure visible and recoverable: users could retry a temporary problem while receiving a clear explanation for a full event or invalid request.

Learning Points

The case demonstrates that reliability depends on cooperation between client and server. Pagination, authentication, database constraints, idempotency, caching, and notification design solve different problems and must be used together.

13. Security, Ethics, and Governance

Networked applications process personal and sometimes sensitive data. Developers should apply data minimization, purpose limitation, retention limits, and least-privilege access. Privacy notices should explain collection and use in understandable language. Regulations may impose obligations concerning consent, access, deletion, breach reporting, children’s data, and cross-border transfers.

Threat modeling should consider credential theft, insecure direct object references, injection, replay, man-in-the-middle attacks, excessive data exposure, denial of service, and insecure third-party dependencies. Input validation, output encoding, TLS, secure authorization checks, dependency updates, rate limiting, audit trails, and penetration testing reduce risk but do not eliminate it.

Artificial intelligence may be used in cloud-connected applications for recommendations, support, or anomaly detection. If AI is introduced, developers must address data provenance, privacy, model error, explainability, bias, prompt or data injection, and human oversight. AI-generated output should not silently make high-impact decisions without appropriate controls.

14. Testing and Observability

Networking tests should include successful responses, malformed JSON, slow responses, timeouts, expired credentials, rate limiting, server errors, duplicate events, reordered events, empty pages, and offline transitions. Contract tests verify that client and server agree on schemas. Integration tests exercise real authentication and data flows in a controlled environment.

Observability commonly combines:

  • Logs: detailed records of significant events, excluding secrets.
  • Metrics: counts, rates, latency distributions, error rates, and saturation.
  • Traces: a request’s path across services using correlation identifiers.

A useful service-level view distinguishes availability from correctness. An API may return HTTP 200 while providing stale or semantically incorrect data. Monitoring should therefore include business indicators such as successful bookings, failed payments, synchronization conflicts, and notification engagement, interpreted with privacy safeguards.

Best Practices Checklist

  • Use HTTPS and secure platform credential storage.
  • Define schemas and versioning rules before implementation.
  • Validate all remote data and ignore unknown fields safely.
  • Separate authentication from authorization.
  • Paginate large collections and document ordering.
  • Set connection, request, and overall operation timeouts.
  • Retry only transient failures and use bounded backoff with jitter.
  • Use idempotency keys for retryable state-changing operations.
  • Cache deliberately and define freshness and invalidation behavior.
  • Treat push notifications and real-time events as hints requiring reconciliation.
  • Enforce permissions and uniqueness constraints on the server.
  • Test offline, slow, duplicated, delayed, and malformed responses.
  • Monitor reliability, cost, privacy, and security continuously.

Chapter Summary

Mobile networking is an exercise in distributed-systems design. REST provides resource-oriented operations; GraphQL provides typed, client-shaped queries; and real-time technologies deliver events that require deduplication and reconciliation. JSON contracts must be validated and evolved compatibly. Authentication identifies callers, while authorization determines permitted actions and must be enforced server-side.

Pagination controls data volume, and cursor pagination is often suitable for changing collections. Reliable clients distinguish transient from permanent failures, use timeouts, bounded retries, exponential backoff, jitter, cancellation, and idempotency. Cloud backends combine databases, storage, queues, functions, identity, notification, and observability services, but managed infrastructure still requires secure configuration and governance. Push notifications are signals rather than authoritative state. Resilient applications combine sound API contracts, secure architecture, defensive clients, testing, monitoring, and thoughtful user experience.

Key Terms

API: An interface through which software systems exchange operations and data.

REST: A resource-oriented architectural style using representations and HTTP semantics.

GraphQL: A typed query language and execution system allowing clients to request selected fields.

WebSocket: A protocol supporting persistent bidirectional communication.

JSON: A text-based data-interchange format containing objects, arrays, and primitive values.

Authentication: Verification of a caller’s identity.

Authorization: Determination of what an authenticated caller may do.

Access token: A credential presented to access protected resources.

Idempotency: Property whereby repeating an operation has the same intended effect as performing it once.

Pagination: Division of a collection into manageable pages.

Cursor: An opaque position token used to retrieve a subsequent page.

Retry: A repeated attempt after an operation fails.

Exponential backoff: A retry schedule whose delay increases exponentially up to a limit.

Jitter: Random variation added to timing to prevent synchronized activity.

Cache: Temporarily stored data used to reduce latency or network traffic.

Serverless function: A managed, event-driven execution unit operated without direct server administration.

Push notification: A provider-mediated message delivered to an application or device.

Webhook: An HTTP callback sent when an event occurs.

Observability: The ability to understand system behavior through logs, metrics, and traces.

Eventual consistency: A model in which replicas may temporarily differ but converge when updates propagate.

Review Questions

Short Answer Questions

  1. What is the difference between authentication and authorization?
  2. Why is cursor pagination often preferable for frequently changing datasets?
  3. What information should a robust API error response contain?
  4. Why should push notifications not normally be treated as authoritative application state?
  5. What is the purpose of an idempotency key?

Long Answer Questions

  1. Compare REST and GraphQL in terms of data selection, caching, authorization, and operational complexity.
  2. Explain how a mobile client should respond to timeouts, 401 responses, 429 responses, and 503 responses.
  3. Describe a secure authentication architecture for a mobile application using an external identity provider.
  4. Explain how cloud databases, object storage, queues, and serverless functions can cooperate in a mobile backend.
  5. Discuss the security, privacy, and governance responsibilities of a team deploying a cloud-connected application.

Analytical / Application Questions

  1. Design an API and synchronization strategy for a mobile shopping cart that must work during temporary offline periods and prevent duplicate orders.
  2. A real-time chat client receives messages out of order and sometimes receives duplicates. Propose an event format and client-side reconciliation strategy.
  3. Evaluate the CampusConnect redesign. Identify two additional risks and propose technical controls for each.

Multiple Choice Questions with Answers

Question 1

Which HTTP method is normally used to retrieve a resource?

A. GET

B. POST

C. PATCH

D. DELETE

Correct Answer: A. GET

Question 2

What does authorization determine?

A. Whether a network connection exists

B. What an authenticated caller may do

C. Whether JSON is valid

D. How quickly a server responds

Correct Answer: B. What an authenticated caller may do

Question 3

Which pagination approach uses an opaque position token?

A. Offset pagination

B. Cursor pagination

C. Random pagination

D. Header pagination

Correct Answer: B. Cursor pagination

Question 4

Why is jitter added to retry delays?

A. To encrypt the response

B. To increase payload size

C. To prevent synchronized retries

D. To remove authentication requirements

Correct Answer: C. To prevent synchronized retries

Question 5

Which operation most clearly benefits from an idempotency key?

A. Reading a public image

B. Creating a potentially chargeable order

C. Loading a static application screen

D. Resolving a DNS name

Correct Answer: B. Creating a potentially chargeable order

Question 6

What is a major GraphQL feature?

A. Clients request selected fields from a typed schema

B. It eliminates the need for authorization

C. It guarantees exactly-once event delivery

D. It requires one URL for every database row

Correct Answer: A. Clients request selected fields from a typed schema

Question 7

What should a client generally do after receiving a push notification about changed data?

A. Assume the notification contains complete authoritative state

B. Delete its local database

C. Fetch or reconcile current authoritative state

D. Disable future notifications

Correct Answer: C. Fetch or reconcile current authoritative state

Question 8

Which response commonly indicates rate limiting?

A. 201

B. 301

C. 404

D. 429

Correct Answer: D. 429

Question 9

Which practice is most appropriate for access tokens in a mobile application?

A. Embed a permanent secret in the application package

B. Store credentials in secure platform storage and limit token lifetime

C. Display tokens in diagnostic logs

D. Send tokens over unencrypted HTTP

Correct Answer: B. Store credentials in secure platform storage and limit token lifetime

Question 10

If t0 = 1 second and the retry number is n = 2, what is tn using tn = t0 × 2n with no maximum cap?

A. 1 second

B. 2 seconds

C. 4 seconds

D. 8 seconds

Correct Answer: C. 4 seconds

Mobile Application Development
Chapter 7 of 15