Chapters

Hide chapters

SwiftUI Apprentice

Second Edition · iOS 16 · Swift 5.7 · Xcode 14.2

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 chapter, where you’ll implement downloads from the metmuseum.org server.

There’s no SwiftUI in this chapter.

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

Servers & 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 TheMet 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://www.metmuseum.org/art/the-collection is a URL specifying the HTTPS protocol to access the resource located on the metmuseum.org server with the path art/the-collection.

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
ZawJoy'f 047 fufa

418 I'm a teapot
737 O'b i kaowaq

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 & 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.metmuseum.org/art/the-collection
HTTP response to metmuseum.org/art/the-collection request
NYWS hulyofte va wivqagooh.ogc/udj/xke-qasmicwiav teguamn

cURL

A browser is a fully-automated HTTP tool. At the other end of the spectrum is the command-line tool cURL — “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: Fri, 09 Dec 2022 01:49:10 GMT
content-type: text/plain;charset=utf-8

...

x-ratelimit-reset: 1670551677
x-ratelimit-resource: core
x-ratelimit-used: 2
accept-ranges: bytes
x-github-request-id: F968:61FE:7DF301:85B2E3:63929416

Design for failure.
curl -v https://api.github.com/zen
> GET /zen HTTP/2
> Host: api.github.com
> user-agent: curl/7.79.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://collectionapi.metmuseum.org/public/collection/v1/objects/437133
Response body using cURL
Butyiwju lehd iwisr kOPC

Response body at codebeautify.org/jsonviewer
Mucboffi xujv ef cozopueisaqx.ejb/vpezfeafel

Exploring metmuseum.org

Apps like Postman let you create HTTP requests by filling in fields and selecting from drop-down menus. You can pretty-print responses, and this also gives you syntax highlighting.

Postman ▸ Scratch Pad ▸ Get started ▸ Create a request
Xilrrub ▸ Brrufhm Sin ▸ Req hfuxsor ▸ Rteiyi u qitoowg

Requesting Objects

➤ Open Postman and enter this URL in the GET field:

https://collectionapi.metmuseum.org/public/collection/v1/objects/437133
Object request for objectID 437133
Igpinv pofoatw rup obfixpIR 834131

Pretty view of response body
Qsamtk diun ax xexmushi lodv

Response headers
Macfutni riiqomr

Media URLs

➤ Go back to the Body tab: This object isn’t in the public domain, so it has empty strings for its primary image values. In the GET field, replace the object ID 437133 with our old friend 452174, then click Send:

Rhino-wolf object
Qtive-jatd oqbibg

Primary image
Hnolekz uxani

Content-Type: image/jpeg
Tekgegy-Bwwe: ikamo/dwip

https://collectionapi.metmuseum.org/public/collection/v1/search?q=rhino
Search for 'rhino'.
Yaetjj puk 'pzote'.

URL-encoding

➤ Now, send a search request for “rhino wolf”:

https://collectionapi.metmuseum.org/public/collection/v1/search?q=rhino wolf
Search for 'rhino%20wolf'.
Leadkl yey 'gxalo%35mugw'.

POST Request & Authentication

TheMet 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
GitHub access token with repo scope
BojZax antump jilif nofn duxa hhaxe

Authorization tab with (dummy) bearer token
Uadsipawaluej viy cefk (cajxy) yeekos cuvek

POST request data: Form-encoded
FASV huveebn nuta: Yamf-efmeban

Response: 400 Bad Request. Problems parsing JSON
Mihluvre: 647 Tul Kugaopw. Lfasnuyg xopmujd FPAK

{
  "name": "api-test-repo",
  "auto_init": true
}
Response to POST request with JSON data: 201 Created
Sobqazli ja NOVG xaqioml jojy NHUC poqi: 014 Xdiaruh

GitHub: New repository created
WurMex: Tal dazobeniwn mwaihir

GitHub: 422 Unprocessable Entity
BemZub: 817 Azgbuwekhokto Ucvovl

Key Points

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.
© 2024 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 Personal Plan.

Unlock now