Communicate with a REST API

Estimated time

1/4 day

Some useful concepts

Communicating with a REST API relies on multiple concepts that we'll cover briefly below:

  • JSONopen in new window: a standard data interchange format used a lot in the HTTP messages of REST APIs.
  • REST APIopen in new window: it is a standard communication interface between a client and conforms to the constraints of REST architectural style. In a REST API, HTTP messages are stateless and use JSON data format.
  • HTTP messagesopen in new window: an http message is a textual message that contains different parts and can be either a request or a response. A request is the HTTP message that the client sends to the server and response is the HTTP message that the server sends to the client in reaction to the request. Both requests and responses have a part called a body. In rest APIs, the body is generally formatted in JSON.
  • Codableopen in new window: it is a type that can convert itself into and out of an external representation. It is equivalent to Serializable in Java. This type is helpful if we want to convert an object into an out of a JSON string.
  • async and await: these keywords are used to call an asynchronous function using a synchronous coding fashion. This means that callbacks are needed no more!
  • URLSessionopen in new window: The official iOS HTTP client which is part of the Foundation library. This library is not part of the Swift standard library but there is an implementation for non-Apple platforms which is called swift-corelibs-foundationopen in new window.

PW: call a REST API

This PW relies on the excellent tutorial from hackingwithswiftopen in new window. It guides you on how to fetch JSON data from iTunes's APIopen in new window. Please find and excerpt of the response body below.

{
   "resultCount":50,
   "results":[
      {
         "wrapperType":"track",
         "kind":"song",
         "artistId":159260351,
         "collectionId":1440913923,
         "trackId":1440914010,
         "artistName":"Taylor Swift",
         "collectionName":"Taylor Swift (Bonus Track Version)",
         "trackName":"Our Song",
         "collectionCensoredName":"Taylor Swift (Bonus Track Version)",
      }
   ]
}