Using Fluent and Persisting Models in Vapor

The Fluent ORM lets you use any number of database engines in your Vapor app. Learn how to persist your models in your server side Swift apps using Vapor! By Tim Condon.

Leave a rating/review
Download materials
Save for later
Share
You are currently viewing page 2 of 2 of this article. Click here to view the first page.

Saving Models

When your app’s user enters a new acronym, you need a way to save it. In Swift 4 and Vapor 3, Codable makes this trivial. Vapor provides Content, a wrapper around Codable, which allows you to convert models and other data between various formats. This is used extensively in Vapor.

Open Acronym.swift and add the following to the end of the file to make Acronym conform to Content:

extension Acronym: Content {}

Since Acronym already conforms to Codable, you don’t have to add anything else. To create an acronym, the user’s browser sends a POST request containing a JSON payload that looks similar to the following:

{
  "short": "OMG",
  "long": "Oh My God"
}

You’ll need a route to handle this POST request and save the new acronym. Open routes.swift and add the following to the end of routes(_:):

// 1
router.post("api", "acronyms") { req -> Future<Acronym> in
  // 2
  return try req.content.decode(Acronym.self).flatMap(to: Acronym.self) { acronym in
    // 3
    return acronym.save(on: req)
  }
}

Here’s what you do here:

  1. Register a new route at /api/acronyms that accepts a POST request and returns Future. It returns the acronym once it’s saved.
  1. Decode the request’s JSON into an Acronym model using Codable. This returns a Future so it uses a flatMap(to:) to extract the acronym when the decoding completes. In this route handler, you’re calling decode(_:) on Request yourself. You’re then unwrapping the result as decode(_:) returns a Future.
  2. Save the model using Fluent. This returns Future as it returns the model once it’s saved.

Fluent and Vapor’s integrated use of Codable makes this simple. Since Acronym conforms to Content, it’s easily converted between JSON and Model. This allows Vapor to return the model as JSON in the response without any effort on your part.

Build and run the application to try it out. A good tool to test this is RESTed, available as a free download from the Mac App Store. Other tools such as Paw and Postman are suitable as well.

In RESTed, configure the request as follows:

  • URL: http://localhost:8080/api/acronyms
  • method: POST
  • Parameter encoding: JSON-encoded

Add two parameters with names and values:

  • short: OMG
  • long: Oh My God

Setting the parameter encoding to JSON-encoded ensures the data is sent as JSON. It’s important to note this also sets the Content-Type header to application/json, which tells Vapor the request contains JSON. If you’re using a different client to send the request, you may need to set this manually.

Click Send Request and you’ll see the acronym provided in the response. The id field will have a value as it has now been saved in the database:

RESTed response to POST

Where to Go From Here?

You can download the final project for this tutorial with the Download Materials button found at the top and bottom of this page.

This tutorial has introduced you to Fluent, and how to create models in Vapor and save them to a database. If you enjoyed this tutorial, why not check out our full-length book on Vapor development: Server Side Swift with Vapor?

If you’re a beginner to web development, but have worked with Swift for some time, you’ll find it’s easy to create robust, fully-featured web apps and web APIs with Vapor 3.

Whether you’re looking to create a backend for your iOS app, or want to create fully-featured web apps, Vapor is the perfect platform for you.

Questions or comments on this tutorial? Leave them in the comments below!