Chapters

Hide chapters

Server-Side Swift with Vapor

Third Edition - Early Acess 1 · iOS 13 · Swift 5.2 - Vapor 4 Framework · Xcode 11.4

Before You Begin

Section 0: 3 chapters
Show chapters Hide chapters

Section I: Creating a Simple Web API

Section 1: 13 chapters
Show chapters Hide chapters

3. HTTP Basics
Written by Tim Condon

Before you begin your journey with Vapor, you’ll first review the fundamentals of how the web and HTTP operate.

This chapter explains what you need to know about HTTP, its methods, and its most common response codes. You’ll also learn how Vapor can augment your web development experience, its benefits, and what differentiates it from other Swift frameworks.

Powering the web

HyperText Transfer Protocol, or HTTP, is the foundation of the web. Each time you visit a website, your browser sends HTTP requests to and receives responses from the server. Many dedicated apps — ordering coffee from your smartphone, streaming video to your TV, or playing an online game — use HTTP behind the scenes.

At its core, HTTP is simple. There’s a client — an iOS application, a web browser or even a simple cURL session — and a server. The client sends an HTTP request to the server which returns an HTTP response.

HTTP requests

An HTTP request consists of several parts:

  • The request line: This specifies the HTTP method to use, the resource requested and the HTTP version. GET /about.html HTTP/1.1 is one example. You’ll learn about HTTP versions later in this chapter.
  • The host: The name of server to handle the request. This is needed when multiple servers are hosted at the same address.
  • Other request headers such as Authorization, Accept, Cache-Control, Content-Length, Content-Type etc.
  • Optional request data, if required by the HTTP method.

The HTTP method specifies the type of operation requested by the client. The HTTP specifications define the following methods:

  • GET
  • HEAD
  • POST
  • PUT
  • DELETE
  • CONNECT
  • OPTIONS
  • TRACE
  • PATCH

The most common HTTP method is GET. It allows a client to retrieve a resource from a server. Clicking a link in a browser or tapping a story in a News app both trigger a GET request to the server.

Another common HTTP method is POST. It allows a client to send data to a server. Clicking the login button after entering your username and password can trigger a POST request to the server. You’ll learn about other HTTP methods as you work through the book.

Frequently, the server needs more than the resource’s name to properly service a request. This additional information is sent in request headers. Request headers are nothing more than key-value pairs.

Some common request headers are: Authorization, Cookie, Content-Type and Accept. You’ll learn in later chapters how Vapor can use some of these to make your server-side apps more robust.

HTTP responses

The server returns an HTTP response when it has processed a request. An HTTP response consists of:

  • The status line: contains the version, status code and message
  • Response headers
  • An optional response body

The status code and its associated message indicate the outcome of the request. There are many status codes but you won’t use or encounter most of them. They’re broken into 5 groups, based on the first digit:

  • 1: informational response. These don’t occur frequently.
  • 2: success response. The most common, 200 OK, means the request was completed successfully.
  • 3: redirection response. These are used frequently.
  • 4: client error. One of the most common is 404 Not Found. You’ve probably seen some different and entertaining 404 pages!
  • 5: server error. This frequently indicates an improperly configured server, resource exhaustion or a bug in the server-side app.

There is even an April Fools’ joke status code: 418 I'm a teapot!

The response may include a response body such as the HTML content of a page, an image file, or a JSON description of a resource. The response body is optional, however, and some response codes — 204 No Content for example — won’t have one.

Finally, the response may include some response headers. These are analogous to the request headers described earlier. Some common response headers are: Set-Cookie, WWW-Authenticate, Cache-Control and Content-Length.

HTTP in web browsers

When you ask your browser to load a page, it sends an HTTP GET request for that page. The server returns the HTML in the response’s body. As the browser parses the HTML, it generates additional HTTP GET requests for any assets — images, JavaScript, CSS — the page references.

A properly formatted HTML page contains both a <head> and a <body> section. When processing a page, the browser waits until it receives all external resources referenced in the <head> section to render the page. The client renders assets referenced in the <body> section as it receives them.

Web browsers use only the GET and POST HTTP methods. The majority of browser requests are GET requests. The browser may use POST to submit form data or upload a file. This will become important in later chapters; you’ll learn techniques to address this then. It’s also impossible to customize the request headers sent by a browser without using JavaScript.

HTTP in iOS apps

Your iOS apps — this also applies to other HTTP clients, such as Rested, JavaScript, Postman — are far less constrained. These apps are able to use all HTTP methods, add custom request headers and implement custom response handling. This is more work but the flexibility allows you the freedom to develop exactly what you need.

HTTP 2.0

Most web services today use HTTP version 1.1 — released in January 1997 as RFC 2068. Everything you’ve learned so far is part of HTTP/1.1 and, unless otherwise noted, is the version used throughout this book.

HTTP/2 expands the communications between client and server to improve efficiency and reduce latency. Individual requests are identical to those in HTTP/1.1, but they may proceed in parallel. The server can anticipate the client’s requests and push data, such as stylesheets and images, to the client before it requests them. Vapor supports HTTP/1.1 and HTTP/2 in both its client and server functions.

REST

REST, or representational state transfer, is an architectural standard closely related to HTTP. Many APIs used by apps are REST APIs and you’ll hear the term often. You’ll learn more about REST and how it relates to HTTP and CRUD in Chapter 7: “CRUD Database Operations”. REST provides a way of defining a common standard for accessing resources from an API. For example, for an acronyms API, you might define the following endpoints:

  • GET /api/acronyms/: get all acronyms.
  • POST /api/acronyms: create a new acronym.
  • GET /api/acronyms/1: get the acronym with ID 1.
  • PUT /api/acronyms/1: update the acronym with ID 1.
  • DELETE /api/acronyms/1: delete the acronym with ID 1.

Having a common pattern to access resources from a REST API simplifies the process of building clients.

Why use Vapor?

Server-side app development with Swift and Vapor is a unique experience. In contrast to many traditional server-side languages — for example PHP, JavaScript, Ruby — Swift is strongly- and statically-typed. This characteristic has greatly reduced the number of runtime crashes in iOS apps and your server-side apps will also enjoy this benefit.

Another potential benefit of server-side Swift is improved performance. Because Swift is a compiled language, apps written using Swift are likely to perform better than those written in an interpreted language.

However, the biggest reason to write server-side Swift apps is you get to use Swift! Swift is one of the fastest-growing and most-loved languages, its modern syntax and features combining the best of many languages. If you currently develop for iOS, you probably already know the language well. This means you can start sharing core business logic code and models between your server-side apps and your iOS apps.

Choosing Swift also means you get to use Xcode to develop your server applications! Though Foundation on Linux is a subset of what you’ll find on iOS and macOS, you can do the majority of your development in Xcode. This gives you access to powerful debugging capabilities in the IDE, a feature most server-side languages don’t have.

Vapor and the server-side Swift ecosystem

Vapor has emerged as the main high-level server-side Swift framework and its developers work closely with the Swift Server Work Group (SSWG). The SSWG is a steering team that promotes the use of Swift on the server. It’s made up of engineers from Apple and the community, including the Vapor core team.

The SSWG also has an incubation process for recommended projects built on top of SwiftNIO, such as a PostgreSQL driver and metrics libraries. Because Vapor is also built on top of SwiftNIO, you can use any of these packages with your server-side Swift apps. Many of these projects are already integrated into Vapor!

Finally, Vapor has an amazing active and vibrant community, which you’re encouraged to get involved with!

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.