HTTP, REST, and Data FormatsIntroductionMobile applications rarely operate in isolation. An iOS app may display account information, submit an order, upload a profile image, or receive a notification from a remote service. Application programming interfaces (APIs) provide the communication boundary between the app and those services. To use APIs effectively, an iOS developer must understand how requests are addressed, how information is represented, how errors are communicated, and how different API designs affect application architecture. This chapter introduces the foundations of web APIs, focusing on HTTP, REST, JSON, URL parameters, headers, status codes, and multipart data. It also briefly compares REST with GraphQL and real-time API approaches. The emphasis is practical: developers should be able to interpret API documentation, construct correct requests, process responses, and recognize common design and security problems. Learning ObjectivesBy the end of this chapter, you should be able to: - explain the request–response model of HTTP;
- distinguish HTTP methods and select an appropriate method for a task;
- interpret URLs, paths, query parameters, headers, and request bodies;
- classify common HTTP status codes;
- describe the principles and limitations of REST;
- encode and decode JSON safely in an iOS application;
- explain multipart form data and file uploads;
- compare REST, GraphQL, and real-time API patterns;
- apply API design and security best practices.
1. The Web API Communication ModelAn API is a defined interface through which one software system requests capabilities or data from another. In a typical mobile application, the iOS client is the consumer and a remote server is the provider. The client sends an HTTP request; the server processes it and returns an HTTP response. A request commonly contains: - a method, such as
GET or POST; - a URL identifying the target resource;
- headers containing metadata;
- an optional body containing data.
A response commonly contains: - a status code;
- response headers;
- an optional body containing data or an error description.
HTTP is generally stateless: each request should contain the information needed to process it, rather than relying on the server remembering the conversational state of previous requests. Authentication tokens can provide continuity of identity, but they do not change the basic stateless nature of HTTP requests. A simplified exchange is: iOS app → HTTP request → API server → HTTP response → iOS app
The transport may use HTTP or, in production, HTTPS. HTTPS is HTTP protected by TLS encryption and server authentication. It helps prevent eavesdropping and tampering while data travels across a network. 2. URLs and Resource IdentificationA Uniform Resource Locator (URL) identifies where a resource can be accessed. Consider: https://api.example.com/v1/books/42?include=author&language=en
Its components are: | Component | Example | Purpose |
|---|
| Scheme | https | Specifies the communication protocol | | Host | api.example.com | Identifies the server | | Path | /v1/books/42 | Identifies an API route and resource | | Query string | include=author&language=en | Supplies optional parameters | | Fragment | #details | Used mainly by clients; normally not sent to servers |
A path parameter usually identifies a particular resource. In /books/42, 42 is the identifier of one book. A query parameter normally modifies retrieval, filtering, sorting, pagination, or field selection. For example: /books?author=lee&page=2&limit=20
The server may interpret this as a request for the second page of books associated with an author. Query parameters should be percent-encoded when necessary. Spaces, ampersands, and reserved characters cannot always be inserted literally because they have special meaning in URLs. Good resource-oriented naming generally uses nouns rather than actions: /users/17/orders is usually preferable to /getUserOrders?id=17;POST /orders expresses creation through the method rather than putting create in the path.
However, real APIs sometimes include action-oriented endpoints when an operation does not map naturally to a simple resource, such as /password-reset or /payments/{id}/capture. 3. HTTP Methods and Their SemanticsHTTP methods communicate the intended operation. The server defines the exact behavior, but standard semantics provide a shared vocabulary. | Method | Common use | Request body | Typical safety/idempotence |
|---|
GET | Retrieve a representation | Usually no | Safe and idempotent | POST | Create a subordinate resource or perform processing | Often yes | Usually neither | PUT | Replace a resource at a known URI | Often yes | Idempotent | PATCH | Partially modify a resource | Usually yes | Depends on implementation | DELETE | Remove a resource | Optional | Idempotent in intended effect | HEAD | Retrieve headers without response content | No | Safe and idempotent | OPTIONS | Discover supported communication options | No | Safe |
A method is safe when it is intended not to change server state. GET may cause logging or analytics, but its defined purpose is retrieval. A method is idempotent when repeating the same request has the same intended final effect as making it once. Deleting an already deleted resource may return different status codes, but the intended end state remains deletion. Idempotence is important when a client retries after a network timeout. Retrying a PUT is generally less likely to create duplicates than retrying a POST. Applications should nevertheless follow the API’s documented behavior. Some APIs support an idempotency key for safely retrying operations such as payments. Example requestsRetrieve a book: GET /v1/books/42 HTTP/1.1
Host: api.example.com
Accept: application/json
Authorization: Bearer token-value Create a book: POST /v1/books HTTP/1.1
Host: api.example.com
Content-Type: application/json
Accept: application/json
{"title":"Networks","authorId":7}The Accept header describes response formats the client can process. The Content-Type header describes the format of the request body. 4. Headers, Parameters, and BodiesHeaders are key–value metadata fields. Frequently used headers include: Authorization: credentials or an access token;Accept: response media types the client accepts;Content-Type: media type of the request body;User-Agent: identifies the client software;If-None-Match: supports conditional requests using an entity tag;Cache-Control: supplies caching instructions;Location: identifies a newly created resource or redirect target.
Headers are not a safe place for arbitrary sensitive information. HTTPS protects headers in transit, but tokens may still be exposed through logs, diagnostic tools, proxies, or incorrectly configured servers. Access tokens should be stored using appropriate iOS secure storage, such as the Keychain, rather than ordinary preferences. Parameters occur in several locations: - Path parameters:
/users/17; identify a resource. - Query parameters:
/users?role=student; filter or modify retrieval. - Header parameters:
Authorization: Bearer ...; carry metadata or credentials. - Body parameters: JSON or form data; carry structured input.
The same logical value can be represented in different locations, but API documentation determines what is valid. A client should not move a required body field into a query string merely because doing so appears convenient. 5. HTTP Status CodesThe status code is a three-digit indication of how the server handled a request. | Class | Meaning | Examples |
|---|
| 1xx | Informational | 100 Continue | | 2xx | Successful processing | 200 OK, 201 Created, 204 No Content | | 3xx | Redirection or cache-related response | 304 Not Modified | | 4xx | Client-side request or authorization problem | 400, 401, 403, 404, 409, 422, 429 | | 5xx | Server-side failure | 500, 502, 503, 504 |
Important distinctions include: 200 OK: the request succeeded and usually contains a representation;201 Created: a resource was created, often with a Location header;204 No Content: succeeded without a response body;400 Bad Request: malformed or invalid request syntax;401 Unauthorized: authentication is missing or invalid; despite its name, this usually means unauthenticated;403 Forbidden: the server understood the identity or request but refuses the operation;404 Not Found: the resource or route was not found;409 Conflict: the request conflicts with current resource state;422 Unprocessable Content: syntactically valid input fails semantic validation;429 Too Many Requests: rate limit exceeded;500 Internal Server Error: unexpected server failure;503 Service Unavailable: temporary unavailability or overload.
An iOS client should not treat every non-200 response as the same error. A 401 may require refreshing authentication, a 429 may require backoff, and a 422 should normally be displayed as a validation problem. Network failures, such as no connectivity or a timeout, are distinct from HTTP responses because the server may never have been reached. 6. REST PrinciplesREST, or Representational State Transfer, is an architectural style rather than a single protocol. A RESTful system commonly has the following characteristics: - Client–server separation: user-interface concerns and data/service concerns are separated.
- Stateless interaction: each request contains the necessary context.
- Cacheability: responses indicate whether they may be reused.
- Uniform interface: resources, representations, standard methods, and meaningful status codes provide consistent interaction.
- Layered system: intermediaries such as gateways and caches may exist without the client knowing every layer.
- Optional code-on-demand: a server may transmit executable code, although this is uncommon in typical mobile JSON APIs.
A resource is an identifiable concept, such as a user, order, or article. A representation is a transferable form of that resource, such as JSON. The resource itself is not identical to its JSON representation. For example: GET /articles/8 retrieves an article;POST /articles creates an article;PATCH /articles/8 modifies selected fields;DELETE /articles/8 requests deletion.
Many systems are described as “REST APIs” even though they use only some REST ideas. This is not automatically a defect. The practical question is whether the interface is consistent, documented, secure, and suitable for its consumers. REST also has limitations. Multiple related resources may require several requests, leading to latency or over-fetching. A response designed for one screen may not fit another. Versioning, pagination, partial updates, and error consistency require deliberate design. 7. JSON Data RepresentationJSON (JavaScript Object Notation) is a text-based data format widely used in APIs. Its value types are object, array, string, number, Boolean, and null. An object contains name–value pairs, while an array contains an ordered sequence. Example: {
"id": 42,
"title": "Networks",
"published": true,
"authors": ["A. Lee", "M. Singh"],
"metadata": null
}JSON object names are strings in double quotation marks. JSON does not formally distinguish integer and floating-point number types in the same way many programming languages do. Applications must therefore consider precision, especially for currency, identifiers, and large values. Monetary values are often represented as integer minor units, such as cents, or as carefully handled decimal strings rather than binary floating-point values. JSON and Swift modelsIn Swift, Codable provides a standard approach to encoding and decoding JSON: struct Book: Codable {
let id: Int
let title: String
let published: Bool
}
let decoder = JSONDecoder()
let book = try decoder.decode(Book.self, from: data)The model must match the response structure. If the server uses names such as published_at, a CodingKeys enumeration or decoder key strategy may be needed. Optional properties should be used only when the server may genuinely omit or return null values. Making every property optional can hide contract errors and make invalid data appear valid. A robust client distinguishes at least these outcomes: - transport failure;
- HTTP failure with a status code;
- invalid or unexpected response data;
- successful decoding.
The client should also avoid trusting unvalidated server data. Decoding establishes structural compatibility; application-level validation may still be required. 8. Multipart Data and File UploadsJSON is suitable for structured text data but is not normally the most efficient format for binary files. multipart/form-data allows a request to contain multiple parts, such as text fields and an image. Each part has its own headers and content, separated by a boundary. Conceptually: Content-Type: multipart/form-data; boundary=Boundary-123
--Boundary-123
Content-Disposition: form-data; name="caption"
Profile photo
--Boundary-123
Content-Disposition: form-data; name="photo"; filename="profile.jpg"
Content-Type: image/jpeg
(binary image bytes)
--Boundary-123-- The boundary must separate parts and must not occur accidentally in the content. In practice, networking libraries can construct multipart requests, but developers must still set the correct content type, file name, MIME type, and size constraints. For large files, an application should consider streaming, background transfers, progress reporting, cancellation, retry behavior, and server-side limits. A file upload should not be assumed to be atomic from the user’s perspective: the network can fail after the server has received the file but before the client receives confirmation. APIs may therefore use upload identifiers or resumable protocols. 9. REST Compared with GraphQL and Real-Time APIsGraphQLGraphQL usually exposes a schema and a query endpoint. The client specifies the fields it wants, which can reduce over-fetching and combine related data in one request. It also introduces schema management, query complexity controls, caching considerations, and a different error model: an HTTP response can be successful while the body contains a GraphQL errors array. REST is often simpler to cache and understand using standard HTTP semantics. GraphQL can be useful when clients have diverse data requirements, such as multiple mobile and web interfaces. The choice should reflect team capability, domain complexity, observability, and operational cost rather than fashion. Real-time alternativesOrdinary HTTP request–response communication is client initiated. Real-time systems support timely server-to-client updates through approaches such as: - WebSockets: a long-lived, bidirectional connection;
- Server-Sent Events: a server-to-client event stream over HTTP;
- long polling: the server holds a request until data is available or a timeout occurs;
- push notification services: platform-mediated notification delivery, often used to wake or inform mobile apps.
Real-time communication introduces connection lifecycle management, reconnection, duplicate events, ordering, authentication renewal, offline behavior, and battery considerations. A mobile application should not maintain an unnecessary persistent connection when periodic retrieval or push notifications are sufficient. 10. Applied Case: Campus Library Mobile AppThe following is an illustrative case. BackgroundA university library wants an iOS app through which students can search books, view availability, reserve a copy, and upload a photograph of a damaged book. ProblemThe first prototype sends large unstructured requests, uses GET to submit reservations, returns 200 OK for all outcomes, and places access tokens in query strings. Users cannot reliably distinguish unavailable books from network failures. AnalysisThe operations have different semantics. Searching and viewing availability are retrieval operations. Creating a reservation changes server state and should not use GET. A damaged-book photograph is binary data and should use multipart data or a dedicated upload service. Consistent status codes and an error schema are needed for meaningful client behavior. Approach and solutionA resource-oriented design is introduced: GET /v1/books?query=swift&page=1 searches books;GET /v1/books/42/availability retrieves availability;POST /v1/reservations creates a reservation;DELETE /v1/reservations/91 cancels a reservation;POST /v1/books/42/reports accepts a multipart damage report.
Requests use HTTPS. The access token is supplied through the Authorization header. Successful reservation creation returns 201 Created; invalid input returns 422; an already reserved copy returns 409; rate limiting returns 429. Responses use a documented JSON error structure, for example: {
"error": {
"code": "COPY_UNAVAILABLE",
"message": "The selected copy is already reserved"
}
}The iOS app maps transport errors, authentication errors, validation errors, conflicts, and successful responses to different user-interface states. It also prevents duplicate submission by disabling the reservation action while a request is pending and by using an idempotency key where supported. OutcomeUsers receive clearer feedback, accidental duplicate reservations are reduced, and the API can evolve without relying on undocumented client assumptions. The design also supports monitoring because status codes and error codes communicate operational outcomes consistently. Learning pointsThe case demonstrates that API quality is not merely a matter of making requests succeed. Method semantics, resource design, security, error classification, and user experience are connected. A technically valid request can still represent poor API design if it is unsafe, ambiguous, or difficult to recover from. 11. Best Practices, Governance, and LimitationsDesign and implementation practices- Use HTTPS for all production API traffic.
- Document methods, URLs, parameters, authentication, response schemas, and errors.
- Validate input on the server even when the client validates it first.
- Use consistent naming and error formats.
- Apply pagination to potentially large collections.
- Define maximum request sizes and timeouts.
- Use caching and conditional requests where appropriate.
- Treat
204 responses as bodyless and do not attempt to decode them as JSON. - Design retries carefully; use exponential backoff for transient failures and idempotency controls for repeatable operations.
- Log correlation identifiers rather than sensitive payloads.
- Test malformed input, expired credentials, offline operation, slow networks, and partial failures.
Security and privacyAuthentication establishes identity; authorization determines permitted actions. These are different controls. An authenticated user should not automatically be allowed to access every resource. APIs should enforce least privilege, validate object ownership, limit requests, and avoid exposing unnecessary personal data. Tokens, passwords, health information, and location data require careful handling. Developers should minimize collection, define retention policies, provide transparent privacy notices, and follow applicable law and institutional policy. Debug logs and crash reports must be reviewed because they can accidentally contain credentials or personal information. Versioning and change managementAn API contract is shared software architecture. Removing a field, changing a type, altering authentication, or modifying error behavior can break clients. Common strategies include URL versioning such as /v1, media-type versioning, additive evolution, deprecation periods, and contract testing. Versioning alone does not solve poor change governance; teams need communication, documentation, monitoring, and migration plans. Contemporary directionModern APIs increasingly use generated client models, OpenAPI descriptions, automated contract tests, observability platforms, and typed schemas. AI-assisted coding can help generate request models or test cases, but generated code must be reviewed for authentication errors, unsafe data handling, incorrect assumptions about optional fields, and privacy violations. AI does not replace reading the API contract or testing against the actual service. Chapter SummaryHTTP provides the request–response foundation for many mobile APIs. A request combines a method, URL, headers, and—when needed—a body. URLs identify resources through schemes, hosts, paths, and query parameters. HTTP methods communicate intended operations, while safety and idempotence help developers reason about side effects and retries. Headers describe metadata such as authentication and media types. Status codes distinguish successful processing, client problems, redirection, and server failures. REST organizes communication around resources, representations, statelessness, cacheability, and a uniform interface, although practical APIs may implement these principles to different degrees. JSON is a common structured format and integrates naturally with Swift’s Codable system. Multipart form data supports combined text and binary uploads. GraphQL offers client-selected fields through a schema, while WebSockets, server-sent events, long polling, and push notifications support real-time or near-real-time requirements. Effective API development combines technical correctness with security, privacy, error handling, documentation, testing, and responsible change management. Key TermsHTTP: A protocol for transferring messages and resources over the web. API: A defined interface through which software systems communicate. URL: An address identifying a resource or service endpoint. Resource: An identifiable domain object or concept exposed by an API. Representation: A transferable form of a resource, such as JSON. HTTP method: A standardized indication of the intended request operation. Header: Metadata attached to an HTTP request or response. Query parameter: A parameter in the URL used to filter or modify a request. Path parameter: A variable segment of a URL path identifying a resource. Request body: Data sent by a client as part of a request. Status code: A three-digit code describing the result of an HTTP request. REST: An architectural style based on resources, representations, and uniform interaction. Statelessness: The principle that each request contains the context needed for processing. JSON: A text-based format containing objects, arrays, and primitive values. MIME type: A label identifying the format of transmitted content. Multipart form data: A format for sending multiple content parts, including files. Idempotence: The property that repeating an operation has the same intended final effect. GraphQL: A schema-based API approach in which clients specify requested fields. WebSocket: A protocol supporting persistent bidirectional communication. Idempotency key: A client-provided value allowing a server to recognize repeated submissions. Review QuestionsShort Answer Questions- What are the principal components of an HTTP request?
- Distinguish a path parameter from a query parameter.
- What is the difference between
401 Unauthorized and 403 Forbidden? - Why is JSON commonly used in mobile APIs?
- What problem does multipart form data solve?
Long Answer Questions- Explain the semantics of
GET, POST, PUT, PATCH, and DELETE, including safety and idempotence. - Describe the main constraints of REST and discuss two practical limitations of REST APIs.
- Explain how an iOS application should distinguish transport errors, HTTP errors, and decoding errors.
- Compare REST and GraphQL in relation to data selection, caching, complexity, and client requirements.
- Discuss security, privacy, and versioning responsibilities when designing a public mobile API.
Analytical / Application Questions- Design endpoints and expected status codes for searching products, creating an order, cancelling an order, and uploading a receipt image. Justify each method and data format.
- An app receives
429, 401, 409, and 503 responses during a purchase workflow. Explain how the client should respond to each and identify which responses might be safely retried. - A social application requires live message updates but must conserve battery when running in the background. Evaluate WebSockets, push notifications, and periodic polling, and recommend an architecture with reasons.
Multiple Choice Questions with AnswersQuestion 1Which HTTP method is normally used to retrieve a resource without intending to change server state? A. GET B. POST C. PATCH D. DELETE Correct Answer: A. GET Question 2In the URL /books?author=lee&page=2, what is page=2? A. A path parameter B. A query parameter C. A response header D. A media type Correct Answer: B. A query parameter Question 3Which status code most appropriately indicates that a new resource was successfully created? A. 200 B. 201 C. 204 D. 304 Correct Answer: B. 201 Question 4Which header describes the format of data being sent in an HTTP request body? A. Accept B. Location C. Content-Type D. Cache-Control Correct Answer: C. Content-Type Question 5Which characteristic means that repeating an operation has the same intended final effect as performing it once? A. Cacheability B. Idempotence C. Authentication D. Serialization Correct Answer: B. Idempotence Question 6Which format is most appropriate for a request containing both an image file and a text caption? A. Plain text only B. JSON only C. multipart/form-data D. HTTP status code Correct Answer: C. multipart/form-data Question 7A server understands a valid request, but the user is not permitted to perform the operation. Which status code is most appropriate? A. 401 B. 403 C. 404 D. 500 Correct Answer: B. 403 Question 8Which Swift facility is commonly used to encode and decode JSON models? A. Codable B. UIView C. URLCache D. NotificationCenter Correct Answer: A. Codable Question 9Which API approach allows a client to specify the fields it wants in a query against a schema? A. REST B. GraphQL C. SMTP D. FTP Correct Answer: B. GraphQL Question 10Which technology provides persistent bidirectional communication between a client and server? A. WebSocket B. DNS C. HEAD request D. JSON Schema Correct Answer: A. WebSocket
|