Beginners Guide to Client Server Communication

RESTful communication in iOS Applications

Shubhang Dixit
Jul 30, 2019 · 9 min read

What is Client-Server communication?

In client-server communication we have first of all two obvious partners: The client and the server.

To understand the communication between these two partners, we need to know some simple topics:

  • Requests: Requests are sent from the client in order to ask the server for some data like files, or tell the server about things that happen, like that a user wants to login with his credentials
  • Response: A response is sent from the server to the client and is the reaction of the server to a request of the client. This could for example be an authentication result.
  • Service: A Service is a specific task that the server provides for the client to use, like downloading image

When we need client-server communication?

Client-Server communication is always used, whenever someone requests something from the internet. Some examples would be applications like Facebook, Twitter, Instagram, Maps or even simple games like Temple Run and so on.

REST

Let’s first understand what is REST and RESTful Communication. Modern web services are often based on the REST architecture, which relies on the HTTP protocol and returns data in the JSON format.

What is RESTful Communication?

RESTful communication means implementation of a web service using HTTP and REST principles.

REST Principles are:

  1. Application state and functionality are divided into resources and than the application would respond based on the resource that the operation is being performed
  2. Resources are addressable using standard URIs that can be used as hypermedia links such as http://example.com/resources/ and than for each resource the type of the resource is added in the URI such as http://example.com/resources/resource.
  3. Resources provide information using MIME( Multipurpose Internet Mail Extensions)types supported by HTTP (e.g JSON, XML, Atom, etc.)
  4. Use only standard HTTP methods, they are GET, PUT, POST and DELETE.
  5. Protocol is stateless, cacheable and layered

Stateless which means that the server would not need to remember any kind of information regarding the state of the client whereas the client would need to include all the information in its request.

REST allows caching which means that the responses would need to be defined as cacheable which would eliminate some client-server interactions, further improving scalability and performance.

Layered meaning that the client does not know if the server that is responding is the actually the end server that is serving the resource which is a great principle to enable load balancing and provide shared caches.

Note : Most REST API implementations rely on agent driven content negotiations. Agent driven content negotiation rely on usage of HTTP request headers or resource URI patterns.

Content negotiation using HTTP headers

At server side, an incoming request may have an entity attached to it. To determine it’s type, server uses the HTTP request header Content-Type. Some common examples of content types are “text/plain”, “application/xml”, “text/html”, “application/json”, “image/gif”, and “image/jpeg”

REST architecture

REST is a client-server architecture. The client and the server both have a different set of concerns. The server stores and/or manipulates information and makes it available to the user in an efficient manner. The client takes that information and displays it to the user and/or uses it to perform subsequent requests for information. This separation of concerns allows both the client and the server to evolve independently as it only requires that the interface stays the same.

REST is stateless. That means the communication between the client and the server always contains all the information needed to perform the request. There is no session state in the server, it is kept entirely on the client’s side. If access to a resource requires authentication, then the client needs to authenticate itself with every request.

REST is cacheable. The client, the server and any intermediary components can all cache resources in order to improve performance.

REST provides a uniform interface between components. This simplifies the architecture, as all components follow the same rules to speak to one another. It also makes it easier to understand the interactions between the different components of the system.

REST is a layered system. Individual components cannot see beyond the immediate layer with which they are interacting. This means that a client connecting to an intermediate component, like a proxy, has no knowledge of what lies beyond. This allows components to be independent and thus easily replaceable or extendable.

Resources and Resource identifiers

A resource is an abstract concept. In a REST system, any information that can be named may be a resource. This includes documents, images, a collection of resources and any other information. Any information that can be the target of an hypertext link can be a resource.

A resource is a conceptual mapping to a set of entities.

A resource is a conceptual mapping to a set of entities. The set of entities evolves over time; a resource doesn’t. For example, a resource can map to “users who have logged in this past month” and another to “all users”. At some point in time they may map to the same set of entities, because all users logged in this past month. But they are still different resources. Similarly, if nobody logged in recently, then the first resource may map to the empty set. This resource exists regardless of the information it maps to.

Resources are identified by uniform resource identifiers, also known as URIs.

REST APIs use URLs and the HTTP protocol to identify resources and transfer data

A URL has different parts, but in the context of REST APIs we are usually interested in just three:

  • The host, which is usually a name (or sometimes the IP address) that identifies the other endpoint we are going to reach through the network
  • A path, which identifies the resource we are looking for
  • An optional query, to express extra parameters we might need for our request

These URLs, though, are just a part of what you need to understand to talk to a REST API.

REST is a type of architecture for web services. But as iOS developers, we don’t care how the entire REST architecture works on the server side.

REST API calls using HTTP requests

REST works over the Hypertext Transfer Protocol (HTTP), which is a protocol originally created to allow the transmission of web pages over the internet.

In HTTP a session is usually a sequence of network requests and responses, although when making calls from iOS apps, we usually use a single session for every call we make.

An HTTP request usually contains:

  • a URL for the resource we want
  • an HTTP method to state the action we want to perform
  • optional parameters in the form of HTTP headers
  • some optional data we want to send to the server

In a REST API call we use only a subset of the HTTP methods for the actions we need to perform:

  • GET, to retrieve a resource
  • POST, to create a resource
  • DELETE, to delete a resource

CRUD operations

In RESTful architecture, CRUD operations correspond to basic HTTP methods. Create is being implemented using POST method, Read using GET method, Update using PUT method and DELETE using DELETE method.

NOTE:

  • the query string is for parameters related to the resource we are accessing
  • the HTTP headers are for parameters related to the request itself, for example, authentication headers

Finally, in the optional data section of a request we put the data we want to send to the API when we are creating or modifying a resource..

Self-descriptive messages

Messages must be self-descriptive. That means that the data format of a representation must always come with its media type (and similarly requesting a resource involves choosing the media type of the representation returned). If you are sending HTML, then you must say it is HTML by sending the media type with the representation. In HTTP this is done using the content-type header.

REST APIs respond with structured data

When we make an HTTP request, we get a response from the server. This response usually carries:

  • a status code, which is a number that tells us if our call was ok or if there was some sort of error
  • some HTTP headers specifying some extra information about the response
  • data, if we requested some. Data can be Requested using Content-
    Type in HTTP request header .At server side, an incoming request may have an entity attached to it. To determine it’s type, server uses the HTTP request header . Some common examples of content types are “text/plain”, “application/xml”, “text/html”, “application/json”, “image/gif”, and “image/jpeg”.

URLSession, URLRequest and URLSessionTask

After you understand how a REST API and the HTTP protocol work, it’s time to make network requests from our app.

There are three classes you need to know to make an HTTP request:

  • URLSession: as the name implies, this corresponds to an HTTP session. Since an HTTP session groups a set of requests and responses, URLSession is used to make different requests that share the same configuration. In practice though, you don’t need to reuse a URLSession and you can create a new one for every request.
  • URLRequest: this class encapsulates the metadata of a single request, including the URL, the HTTP method ( GET, POST, etc.), HTTP headers and so on. But for simple requests, you don’t need to use this class at all.
  • URLSessionTask: this class performs the actual transfer of data. It has different subclasses for different types of tasks. The most common one you will use is URLSessionDataTask, which retrieves the content of a URL as a Data object. You actually don’t instantiate a task yourself, the URLSession class does it for you. But you have to remember to all their resume() method, or it won’t start.

That’s it.

So, making an HTTP request in iOS boils down to:

  • creating and configuring an instance of URLSession, to make one or more HTTP requests
  • creating and configuring an instance URLRequest for your requests, but only if you need some specific parameters. Otherwise, you can skip this;
  • starting a URLSessionDataTask through the URLSession instance.

This requires only a few lines of code:

Transforming the JSON data coming from a REST API into the model of your app

REST APIs usually return the data you request in the JSON format. A JSON payload is actually a string. So, before you can actually use the data, you have to parse this string and transform it into objects.

The iOS SDK offers the JSONSerialization class that takes care of this.

After parsing a JSON string, this class returns a structure that is very similar to a property list. The only difference is that a JSON serialization can include instances of the NSNull class to represent the null values that come in a JSON response (plists cannot have null values) (Note: Swift 4 introduced a better approach to decoding JSON using the Codable protocol instead of the JSONSerialization class.)

Let’s say we want to write some code that retrieves a list of questions from stack overflow.

This is how you would usually write it.

class NetworkController {

func loadQuestions(withCompletion completion: @escaping ([Question]?) -> Void) {

let session = URLSession(configuration: .ephemeral, delegate: nil, delegateQueue: OperationQueue.main)

let url = URL(string: “https://api.stackexchange.com/2.2/questions?order=desc&sort=votes&site=stackoverflow")!

let task = session.dataTask(with: url, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in

guard let data = data else {

completion(nil)

return

}

guard let json = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) else {

completion(nil)

return

}

let questions: [Question] = [] // Transform JSON into Question values

completion(questions)

})

task.resume()

}

}


The important concepts to remember:

  • how a REST API relies on URLs and the HTTP protocol. The REST architecture for web services uses URLs to specify resources and parameters and HTTP verbs to identify actions.
  • Responses use HTTP status code to express the result and the body to return the requested data, often in JSON format.
  • how to perform network requests in iOS apps using URLSession.
  • The URLSession class represents an HTTP session, URLRequest represents a single request in a session and URLSessionTask actually performs the asynchronous data transfer.

I have tried here explaining the Client Server communication basic concepts. I will try to however include the concept of networking architecture for your apps and how an MVC approach to networking in iOS can solve many problems. Please feel free to give feedback and also let me know if i missed any concepts here.

Thanks and Regards

Shubhang Dixit

Written by

Swift and Objective-C Developer

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade