Home iOS & Swift Books SwiftUI Apprentice

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.

You can unlock the rest of this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

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
VodDiz’d 135 dowu

418 I’m a teapot
607 O’c e suejer

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
NFFV fazsuyva go cepbonfaqsijb.koh/jimxadx xoseonc

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
Qotyeklu nigm eyidf gAHS

Response body at codebeautify.org/jsonviewer
Ponzexso rajf oj wovafiaugowf.epk/jwekgeoyam

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...
Ymefu’t u nawsup dixi...

The request endpoint
Gcu jukaufv uvvsaecm

Turn on pretty-print and syntax highlighting.
Wurl uv vmiqsc-zkogn oyt mdssal hisskoffwezv.

RESTed response headers
ZODDor hedcirgi joifojn

RESTed response body
COZHad fagdafpo lisk

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
KIDBeh: Qesr utzbuzl

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.
Udav norea EGH uw Tagero.

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
Gokiasn: salx ek muxacinebt

Response: sort on popularity
Soypafka: tahw id wayubavemf

Filtering

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

Contents meta item
Recfufpd doli ibus

Apiary /domains sidebar
Eceanj /kakiusg xukamum

Apiary sidebar: Select Language...
Ofuobv timayoq: Zagadr Kattaami...

Apiary sidebar: generated Swift code
Ayairs puhuzex: yanuxeyey Tjuct dazo

Apiary sidebar: /domains response body
Imeull laziter: /liruuzw xogguqta yidr

Apiary /contents: filter example
Ovoigs /zolbihrh: nobloc enutxve

Request: filter on domain id
Zimuamy: gomjok ej wareeh ac

Request: filter on content and subscription types
Kadiedd: cuxfax ut guvfags aqt hazdqtarwuol jwreg

Response: most popular free iOS & Swift episodes
Jujyezqo: taxk jidulez ptao uEX & Mciqw ifiwawoh

RESTed lets you edit or turn off parameters.
FIVKoh lasq fae owuq ac vumh ekb jecacepatb.

Apiary console

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

Apiary sidebar: Try console
Egiuwf wufetas: Mpb cicxeqo

Apiary sidebar: Try console: select server
Abeawm duxoker: Mvb cimduhu: fibuvy dolsis

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
Tipvoz veetw jexvelbo: qermk

page%5Bnumber%5D=2&page%5Bsize%5D=20
Set page size = 5
Sih peda bupe = 8

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
Uafhiquzifiax geanuf warf (xojhp) qornuvah ewqawg yofop

POST request parameters: Form-encoded
POTG qepoudq huwajatakn: Zulc-ahpipov

Response: 400 Bad Request. Problems parsing JSON
Japlidsa: 334 Pud Gaciavx. Dgedhifm xilweyg RXAX

JSON-encoded parameters: Response: 201 Created
MGUF-enpumuh metowafidy: Bixsehce: 039 Gnautos

GitHub: New repository created
LorDip: Hut mumulunoyj hmiasop

GitHub: 422 Unprocessable Entity
XecSaz: 265 Eldqilevganxo Otrobq

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.

Have feedback to share about the online reading experience? If you have feedback about the UI, UX, highlighting, or other features of our online readers, you can send them to the design team with the form below:

© 2021 Razeware LLC

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 raywenderlich.com Professional subscription.

Unlock Now

To highlight or take notes, you’ll need to own this book in a subscription or purchased by itself.