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

16. Making a Simple Web App, Part 1
Written by Tim Condon

Note: This update is an early-access release. This chapter has not yet been updated to Vapor 4.

In the previous chapters, you learned how to display data in a website and how to make the pages look nice with Bootstrap. In this chapter, you’ll learn how to create different models and how to edit acronyms.

Categories

You’ve created pages for viewing acronyms and users. Now it’s time to create similar pages for categories. Open WebsiteController.swift. At the bottom of the file, add a context for the “All Categories” page:

struct AllCategoriesContext: Encodable {
  // 1
  let title = "All Categories"
  // 2
  let categories: Future<[Category]>
}

Here’s what this does:

  1. Define the page’s title for the template.
  2. Define a future array of categories to display in the page.

Leaf knows how to handle futures. This helps tidy up your code when you don’t need access to the resolved futures in your request handler.

Next, add the following under allUsersHandler(_:) to create a new route handler for the “All Categories” page:

func allCategoriesHandler(_ req: Request) throws
  -> Future<View> {
  // 1
  let categories = Category.query(on: req).all()
  let context = AllCategoriesContext(categories: categories)
  // 2
  return try req.view().render("allCategories", context)
}

Here’s what this route handler does:

  1. Create an AllCategoriesContext. Notice that the context includes the query result directly, since Leaf can handle futures.
  2. Render the allCategories.leaf template with the provided context.

Create a new file in Resources/Views called allCategories.leaf for the “All Categories” page. Open the new file and add the following:

#// 1
#set("content") {

  <h1>All Categories</h1>

  #// 2
  #if(count(categories) > 0) {
    <table class="table table-bordered table-hover">
      <thead class="thead-light">
        <tr>
          <th>
            Name
          </th>
        </tr>
      </thead>
      <tbody>
        #// 3
        #for(category in categories) {
          <tr>
            <td>
              <a href="/categories/#(category.id)">
                #(category.name)
              </a>
            </td>
          </tr>
        }
      </tbody>
    </table>
  } else {
    <h2>There aren't any categories yet!</h2>
  }
}

#embed("base")

This template is like the table for all acronyms, but the important points are:

  1. Set the content variable for use by base.leaf.
  2. See if any categories exist. You access future variables in the exact same way as non-futures. Leaf makes this transparent to the templates.
  3. Loop through each category and add a row to the table with the name, linking to a category page.

Now, you need a way to display all of the acronyms in a category. Open, WebsiteController.swift and add the following context at the bottom of the file for the new category page:

struct CategoryContext: Encodable {
  // 1
  let title: String
  // 2
  let category: Category
  // 3
  let acronyms: Future<[Acronym]>
}

Here’s what the context contains:

  1. A title for the page; you’ll set this as the category name.
  2. The category for the page. This isn’t Future<Category> since you need the category’s name to set the title. This means you’ll have to unwrap the future in your route handler.
  3. The category’s acronyms, provided as a future.

Next, add the following under allCategoriesHandler(_:) to create a route handler for the page:

func categoryHandler(_ req: Request) throws -> Future<View> {
  // 1
  return try req.parameters.next(Category.self)
    .flatMap(to: View.self) { category in
      // 2
      let acronyms = try category.acronyms.query(on: req).all()
      // 3
      let context = CategoryContext(
        title: category.name,
        category: category,
        acronyms: acronyms)
      // 4
      return try req.view().render("category", context)
  }
}

Here’s what the route handler does:

  1. Get the category from the request’s parameters and unwrap the returned future.
  2. Create a query to get all the acronyms for the category. This is a Future<[Acronym]>.
  3. Create a context for the page.
  4. Return a rendered view using the category.leaf template.

Create the new template, category.leaf, in Resources/Views. Open the new file and add the following:

#set("content") {
  <h1>#(category.name)</h1>

  #embed("acronymsTable")
}

#embed("base")

This is almost the same as the user’s page just with the category name for the title. Notice that you’re using the acronymsTable.leaf template to display the table to acronyms. This avoids duplicating yet another table and, yet again, shows the power of templates. Open base.leaf and add the following after the link to the all users page:

<li class="nav-item #if(title == "All Categories"){active}">
  <a href="/categories" class="nav-link">All Categories</a>
</li>

This adds a new link to the navigation on the site for the all categories page. Finally open WebsiteController.swift and at the end of boot(router:), add the following to register the new routes:

// 1
router.get("categories", use: allCategoriesHandler)
// 2
router.get(
  "categories", Category.parameter,
  use: categoryHandler)

Here’s what this does:

  1. Register a route at /categories that accepts GET requests and calls allCategoriesHandler(_:).
  2. Register a route at /categories/<CATEGORY ID> that accepts GET requests and calls categoryHandler(_:).

Build and run, then go to http://localhost:8080/ in your browser. Click the new All Categories link in the menu and you’ll go to the new “All Categories” page:

Click a category and you’ll see the category information page with all the acronyms for that category:

Create acronyms

To create acronyms in a web application, you must actually implement two routes. You handle a GET request to display the form to fill in. Then, you handle a POST request to accept the data the form sends.

The page to create an acronym needs a list of all the users to permit selecting which user owns the acronym. Create a context at the bottom of WebsiteController.swift to represent this:

struct CreateAcronymContext: Encodable {
  let title = "Create An Acronym"
  let users: Future<[User]>
}

Again you’re using a Future in the context. Next, create a route handler to present the “Create An Acronym” page under categoryHandler(_:):

func createAcronymHandler(_ req: Request) throws
  -> Future<View> {
  // 1
  let context = CreateAcronymContext(
    users: User.query(on: req).all())
  // 2
  return try req.view().render("createAcronym", context)
}

Here’s what this does:

  1. Create a context by passing in a query to get all of the users.
  2. Render the page using the createAcronym.leaf template.

Next, add the following below createAcronymHandler(_:) to create a route handler for the POST request:

// 1
func createAcronymPostHandler(
  _ req: Request,
  acronym: Acronym
) throws -> Future<Response> {
  // 2
  return acronym.save(on: req)
    .map(to: Response.self) { acronym in
      // 3
      guard let id = acronym.id else {
        throw Abort(.internalServerError)
      }
      // 4
      return req.redirect(to: "/acronyms/\(id)")
  }
}

Here’s what this does:

  1. Declare a route handler that takes Acronym as a parameter. Vapor automatically decodes the form data to an Acronym object.
  2. Save the provided acronym and unwrap the returned future.
  3. Ensure that the ID has been set, otherwise throw a 500 Internal Server Error.
  4. Redirect to the page for the newly created acronym.

Next, to register these routes, add the following to the bottom of boot(router:):

// 1
router.get("acronyms", "create", use: createAcronymHandler)
// 2
router.post(
  Acronym.self, at: "acronyms", "create",
  use: createAcronymPostHandler)

Here’s what the code does:

  1. Register a route at /acronyms/create that accepts GET requests and calls createAcronymHandler(_:).
  2. Register a route at /acronyms/create that accepts POST requests and calls createAcronymPostHandler(_:acronym:). This also decodes the request’s body to an Acronym.

You now need a template to display the create acronym form. Create a new file in Resources/Views called createAcronym.leaf. Open the file and add the following:

#// 1
#set("content") {
  <h1>#(title)</h1>

  #// 2
  <form method="post">
    #// 3
    <div class="form-group">
      <label for="short">Acronym</label>
      <input type="text" name="short" class="form-control"
       id="short"/>
    </div>

    #// 4
    <div class="form-group">
      <label for="long">Meaning</label>
      <input type="text" name="long" class="form-control"
       id="long"/>
    </div>

    <div class="form-group">
      <label for="userID">User</label>
      #// 5
      <select name="userID" class="form-control" id="userID">
        #// 6
        #for(user in users) {
          <option value="#(user.id)">
            #(user.name)
          </option>
        }
      </select>
    </div>

    #// 7
    <button type="submit" class="btn btn-primary">
      Submit
    </button>
  </form>
}

#embed("base")

Here’s what the template does:

  1. Define the content variable used in the base template.
  2. Create an HTML form. Set the method to POST. This means the browser sends the data to the same URL using a POST request when a user submits the form.
  3. Create a group for the acronym’s short value. Use HTML’s <input> element to allow a user to insert text. The name property tells the browser what the key for this input should be when sending the data in the request.
  4. Create a group for the acronym’s long value using HTML’s <input> element.
  5. Create a group for the acronym’s user. Use HTML’s <select> element to display a drop-down menu of the different users.
  6. Use Leaf’s #for() loop to iterate through the provided users and add each as an option on the <select>.
  7. Create a submit button the user can click to send the form to your web app.

Finally, add a link to the new page in base.leaf just before the </ul> tag:

#// 1
<li class="nav-item #if(title == "Create An Acronym"){active}">
  #// 2
  <a href="/acronyms/create" class="nav-link">
    Create An Acronym
  </a>
</li>

Here’s what the code does:

  1. Add a new navigation item to the nav bar. If you’re on the “Create An Acronym” page, mark the item active.
  2. Add a link to the create page.

Build and run, then open your browser. Navigate to http://localhost:8080 and you’ll see a new option, “Create An Acronym”, in the navigation bar. Click the link to go to the new page. Fill in the form and click Submit.

The app redirects you to the new acronym’s page:

Editing acronyms

You now know how to create acronyms through the website. But what about editing an acronym? Thanks to Leaf, you can reuse many of the same components to allow users to edit acronyms. Open WebsiteController.swift.

At the end of the file, add the following context for editing an acronym:

struct EditAcronymContext: Encodable {
  // 1
  let title = "Edit Acronym"
  // 2
  let acronym: Acronym
  // 3
  let users: Future<[User]>
  // 4
  let editing = true
}

Here’s what the context contains:

  1. The title for the page: “Edit Acronym”.
  2. The acronym to edit.
  3. A future array of users to display in the form.
  4. A flag to tell the template that the page is for editing an acronym.

Next, add the following route handler below createAcronymPostHandler(_:acronymn:) to show the edit acronym form:

func editAcronymHandler(_ req: Request) throws -> Future<View> {
  // 1
  return try req.parameters.next(Acronym.self)
    .flatMap(to: View.self) { acronym in
      // 2
      let context = EditAcronymContext(
        acronym: acronym,
        users: User.query(on: req).all())
      // 3
      return try req.view().render("createAcronym", context)
  }
}

Here’s what this route does:

  1. Get the acronym to edit from the request’s parameter and unwrap the future.
  2. Create a context to edit the acronym, passing in all the users.
  3. Render the page using the createAcronym.leaf template, the same template used for the create page.

Next, add the following route handler for the POST request from the edit acronym page below editAcronymHandler(_:):

func editAcronymPostHandler(_ req: Request) throws
  -> Future<Response> {
  // 1
  return try flatMap(
    to: Response.self,
    req.parameters.next(Acronym.self),
    req.content.decode(Acronym.self)
  ) { acronym, data in
    // 2
    acronym.short = data.short
    acronym.long = data.long
    acronym.userID = data.userID

    // 3
    guard let id = acronym.id else {
      throw Abort(.internalServerError)
    }
    let redirect = req.redirect(to: "/acronyms/\(id)")
    // 4
    return acronym.save(on: req).transform(to: redirect)
  }
}

Here’s what the route does:

  1. Use the convenience form of flatMap to get the acronym from the request’s parameter, decode the incoming data and unwrap both results.
  2. Update the acronym with the new data.
  3. Ensure the ID has been set, otherwise throw a 500 Internal Server Error.
  4. Save the result and transform the result to redirect to the updated acronym’s page.

Next, add the following to register the two new routes at the bottom of boot(router:):

router.get(
  "acronyms", Acronym.parameter, "edit",
  use: editAcronymHandler)
router.post(
  "acronyms", Acronym.parameter, "edit",
  use: editAcronymPostHandler)

This registers a route at /acronyms/<ACRONYM ID>/edit to accept GET requests that calls editAcronymHandler(_:). It also registers a route to handle POST requests to the same URL that calls editAcronymPostHandler(_:).

Open createAcronym.leaf and change the template to accommodate editing an acronym. First, replace the input for the acronym short to accommodate editing:

<input type="text" name="short" class="form-control"
 id="short" #if(editing){value="#(acronym.short)"}/>

If the editing flag is set, this sets the value attribute of the <input> to the acronym’s short property. This is how you pre-fill the form for editing. Do the same for the acronym’s long input:

<input type="text" name="long" class="form-control"
 id="long" #if(editing){value="#(acronym.long)"}/>

Replace the users’ <select> option for editing:

<option value="#(user.id)"
 #if(editing){#if(acronym.userID == user.id){selected}}>
  #(user.name)
</option>

This sets the <option>’s selected property if the user’s ID matches the acronym’s userID. This makes that option in the drop-down menu appear as the selected one. Next, replace the button for submitting the form:

<button type="submit" class="btn btn-primary">
  #if(editing){Update} else{Submit}
</button>

This uses Leaf’s #if()/else tags to set the text of the button to “Update” or “Submit” depending on the page’s mode.

Finally, open acronym.leaf and add a button to edit that acronym at the bottom of #set("content"):

<a class="btn btn-primary" href="/acronyms/#(acronym.id)/edit"
 role="button">Edit</a>

This creates an HTML link to /acronyms/<ACRONYM ID>/edit and uses Bootstrap to style the link as a button. Save the files and in Xcode, build and run the app. Open http://localhost:8080/ in your browser.

Open an acronym page and there’s now an Edit button at the bottom:

Click Edit to go to the edit acronym page with all the information pre-populated. The title and button are also different:

Change the acronym and click Update. The app redirects you to the acronym’s page and you’ll see the updated information.

Deleting acronyms

Unlike creating and editing acronyms, deleting an acronym only requires a single route. However, with web browsers there’s no simple way to send a DELETE request.

Browsers can only send GET requests to request a page and POST requests to send data with forms.

Note: It’s possible to send a DELETE request with JavaScript, but that’s outside the scope of this chapter.

To work around this, you’ll send a POST request to a delete route.

Open, WebsiteController.swift and add the following route handler below editAcronymPostHandler(_:) to delete an acronym:

func deleteAcronymHandler(_ req: Request) throws
  -> Future<Response> {
  return try req.parameters.next(Acronym.self).delete(on: req)
    .transform(to: req.redirect(to: "/"))
}

This route extracts the acronym from the request’s parameter and calls delete(on:) on the acronym. The route then transforms the result to redirect the page to the home screen. Register the route at the bottom of boot(router:):

router.post(
  "acronyms", Acronym.parameter, "delete",
  use: deleteAcronymHandler)

This registers a route at /acronyms/<ACRONYM ID>/delete to accept POST requests and call deleteAcronymHandler(_:). Build and run. Open acronym.leaf and replace the edit button with the following:

#// 1
<form method="post" action="/acronyms/#(acronym.id)/delete">
  #// 2
  <a class="btn btn-primary" href="/acronyms/#(acronym.id)/edit"
   role="button">Edit</a>&nbsp;
  #// 3
  <input class="btn btn-danger" type="submit" value="Delete" />
</form>

Here’s what the new code does:

  1. Declare a form that sends a POST request. Set the action property to /acronyms/<ACRONYM ID>/delete. It’s good practice to use a POST request for actions that modify the database, such as create or delete. This enables you to protect them with CSRF (Cross Site Request Forgery) tokens in the future, for example.
  2. Incorporate the edit button that already exists on the page. This allows Bootstrap to align them. Use Bootstrap’s button styling so the buttons look the same.
  3. Create a submit button for the delete form.

Save the file, then open http://localhost:8080/ in the browser. Open an acronym page and you’ll see the delete button:

Click Delete to delete the acronym. The app redirects you to the homepage and the deleted acronym is no longer shown.

Where to go from here?

In this chapter, you learned how to display your categories and how to create, edit and delete acronyms. You still need to complete your support for categories, allowing your users to put acronyms into categories and remove them. You’ll learn how to do that in the next chapter!

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.
© 2026 Kodeco Inc.