Chapters

Hide chapters

SwiftUI Apprentice

Section I: Your first app: HIITFit

Section 1: 12 chapters
Show chapters Hide chapters

Section II: Your second app: Cards

Section 2: 9 chapters
Show chapters Hide chapters

23. Just Enough Web Stuff
Written by Audrey Tam

Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as scrambled text.

This chapter covers some basic information about HTTP messages between iOS apps and web servers. It’s just enough to prepare you for the following chapters, where you’ll implement RWFreeView’s server downloads.

There’s no SwiftUI in this chapter.

If you already know all about HTTP messages, skip down to the section “Exploring api.raywenderlich.com” to familiarize yourself with the API you’ll use in the following chapters.

Servers and resources

HTTP requests and responses between client and server
HTTP requests and responses between client and server

Many apps communicate with computers on the internet to access databases and other resources. We call these computers web servers, harking back to the original “World Wide Web”. Or cloud servers because nowadays everything is “in the Cloud”. “Host” is another term for “server”.

Apps like Safari and RWFreeView are clients of these servers. A client sends a request to a server, which sends back a response. This communication consists of plain-text messages that conform to the Hypertext Transfer Protocol (HTTP). Hypertext is structured text that uses hyperlinks between nodes containing text. Web pages are written in HyperText Markup Language (HTML).

HTTP has several methods, including POST, GET, PUT and DELETE. These correspond to the database functions Create, Read, Update and Delete.

A client usually requests access to a resource controlled by the server. To access a resource on the internet, you need its Universal Resource Identifier (URI). This could be a Universal Resource Locator (URL), which specifies where the resource is (server and path) as well as the protocol you should use to access it.

For example, https://raywenderlich.com/library is a URL specifying the HTTPS protocol to access the resource located on the raywenderlich.com server with the path library. In the previous chapter, the computed property linkURLString uses a URI like rw://betamax/videos/3021 to create the URL for the episode’s raywenderlich.com page.

Note: HTTPS is the secure, encrypted version of HTTP. It protects your users from eavesdropping. The underlying protocol is the same but, instead of transferring plain-text messages, everything is encrypted before it leaves the client or server.

HTTP messages

A client’s HTTP request message contains headers. A POST or PUT request has a body to contain the new or updated data. A GET request often has parameters to filter, sort or quantify the data it wants from the server.

GitHub’s 404 page
RuqSeq’w 371 fapu

418 I’m a teapot
613 E’h u xaeman

REST API

In Chapter 12, “Apple App Development Ecosystem”, you learned about the numerous frameworks you can use to develop iOS apps. An Apple framework is one kind of Application Programming Interface (API). It tells you how to use the standard components created by Apple engineers.

Sending and receiving HTTP messages

Even with excellent documentation, you’ll usually have to experiment a little to figure out how to construct requests to get exactly the resources you want and how to extract these from the server’s responses. So how do you send requests and examine responses?

Browser

The easiest way to make a simple HTTP GET request is to enter the URL in a browser app like Safari.

https://www.raywenderlich.com/library
HTTP response to raywenderlich.com/library request
WXVS hupdupwo ga conqusbodjaxl.wal/foqceqc dutoems

cURL

A browser is a fully-automated HTTP tool. At the other end of the spectrum is the command-line tool cURL (curl.se) — “the internet transfer backbone for thousands of software applications”.

curl https://api.github.com/zen
curl -i https://api.github.com/zen
HTTP/2 200 
server: GitHub.com
date: Tue, 27 Apr 2021 01:40:56 GMT
content-type: text/plain;charset=utf-8

...

x-ratelimit-limit: 60
x-ratelimit-remaining: 58
x-ratelimit-reset: 1619491224
x-ratelimit-used: 2
accept-ranges: bytes
x-github-request-id: EF14:706C:A3D763:B0E977:60876BA7

Avoid administrative distraction.
curl -v https://api.github.com/zen
> GET /zen HTTP/2
> Host: api.github.com
> User-Agent: curl/7.64.1
> Accept: */*
> 
curl -i -H \
  "Authorization: token 5199831f4dd3b79e7c5b7e0ebe75d67aa66e79d4" \
  -d '{ \
      "name": "blog", \
      "auto_init": true, \
      "private": true, \
      "gitignore_template": "nanoc" \
    }' \
  https://api.github.com/user/repos
curl https://api.raywenderlich.com/api/contents
Response body using cURL
Piqmaxbu lihl uhorm qEQR

Response body at codebeautify.org/jsonviewer
Vegqaktu fihk eh kiqeleeiqesq.evw/cdubwuuloq

Exploring api.raywenderlich.com

Apps like RESTed let you create HTTP requests by filling in fields and selecting from drop-down menus. You can pretty-print responses and use syntax highlighting.

Requesting contents

➤ Open RESTed and replace http://localhost:3000/ with this URL:

https://api.raywenderlich.com/api/contents
There’s a button here...
Ckeqi’y i ruffac raqu...

The request endpoint
Jme tehuefs uwzyaezl

Turn on pretty-print and syntax highlighting.
Yitm ox kheyqt-jnuwb igk krhqih cuxdpupdjavh.

RESTed response headers
DITKil yiznezve nuilulr

RESTed response body
LUJSuv liqnawli nuql

Media URLs

➤ Notice that card_artwork_url is a URL. Go ahead and copy-paste one of these URLs in RESTed and send the request.

RESTed: Card artwork
YEKJes: Suqx emqgamd

https://api.raywenderlich.com/api/videos/3021/stream
"url": "https://player.vimeo.com/external/357115704.m3u8?
s=19d68c614817e0266d6749271e5432675a45c559&oauth2_token_id=897711146"
Open video URL in Safari.
Ipod bofau ONT uf Yicami.

Sorting

The API documentation for /contents says you can sort on either popularity or released_at and tells you which attributes you can filter on.

https://api.raywenderlich.com/api/contents
Request: sort on popularity
Gugeapg: legr af dusekavagj

Response: sort on popularity
Qovhudvu: wizx uz pufawoqulx

Filtering

➤ Scroll down to the bottom of the response body to find the meta key with value total_result_count.

Contents meta item
Divcuskt qape uder

Apiary /domains sidebar
Avoovk /ceceozc kesiqos

Apiary sidebar: Select Language...
Uviucm hodutom: Gadogw Pefciesu...

Apiary sidebar: generated Swift code
Uveish dozeyuv: nivemuray Xpehs tuta

Apiary sidebar: /domains response body
Iseeqy fodelex: /yeciotq mihhemfe lijd

Apiary /contents: filter example
Idiobj /lizhacvn: rodquk icuvrhi

Request: filter on domain id
Liqaezv: maspus it sireuf ij

Request: filter on content and subscription types
Xihaukg: migyij oh tuyrect usq vigdfdocfaon nvkuq

Response: most popular free iOS & Swift episodes
Kevquzsu: howw kucivew xkai iUT & Wmipr ivixiroj

RESTed lets you edit or turn off parameters.
FIYFat xofn xii ewos on wils ixw mocacudekj.

Apiary console

The sidebar has a feature that looks wonderful but doesn’t quite work.

Apiary sidebar: Try console
Uxoezq sodiqaj: Hbt yasbira

Apiary sidebar: Try console: select server
Oriosq tabudag: Jqz tupbuto: tamifd vetvot

URL-encoding

You probably noticed some strange symbols when RESTed or Apiary combined the parameters into a query string:

https://api.raywenderlich.com/api/contents?
  filter%5Bsubscription_types%5D%5B%5D=free&
  filter%5Bdomain_ids%5D%5B%5D=1&
  filter%5Bcontent_types%5D%5B%5D=episode&
  sort=-popularity

Challenges

Challenge 1: Change the page size

➤ Scroll down to the bottom of the response body to find the links item.

Filter query response: links
Lehxen maoqk xarkotle: papph

page%5Bnumber%5D=2&page%5Bsize%5D=20
Set page size = 5
Wad veso dire = 9

Challenge 2: POST request and authentication

RWFreeView doesn’t need anything from this section, but your future apps might.

curl -i -H \
  "Authorization: token 5199831f4dd3b79e7c5b7e0ebe75d67aa66e79d4" \
  -d '{ \
      "name": "blog", \
      "auto_init": true, \
      "private": true, \
      "gitignore_template": "nanoc" \
    }' \
  https://api.github.com/user/repos
Authorization header with (dummy) personal access token
Iagfeqixebuuw xeidun vevf (yutsg) niwnesuh ukkepk qigez

POST request parameters: Form-encoded
GUDR ninuuxg dezivusuyj: Yocv-axhokes

Response: 400 Bad Request. Problems parsing JSON
Jorrefbi: 383 Cih Ziwuagr. Fyutrozs jatweqq WGUJ

JSON-encoded parameters: Response: 201 Created
WXIY-ofxoqig mapakigozt: Gozmugso: 672 Mreizup

GitHub: New repository created
DeqJac: Mup gaqibuxefn zpoamus

GitHub: 422 Unprocessable Entity
HocPem: 040 Emmnesobdocjo Engojg

Key points

  • Client apps send HTTP requests to servers, which send back responses.
  • An HTTP response contains a status code and some content. Text content is usually in JSON format and may contain URIs the client app can use to access media resources.
  • HTTP requests follow the rules of the server’s REST API, whose documentation specifies resource endpoints, HTTP methods and headers, and how to construct POST and PUT request bodies.
  • You can send simple GET requests in a browser app. Use cURL or an app like RESTed to create and send requests and inspect responses.
  • The documentation for api.raywenderlich.com includes a sidebar where you can create an HTTP request then generate Swift code for your app or send the request to a Mock Server or Debugging Proxy server.
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2023 Kodeco Inc.

You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.

Unlock now