0Pricing
Swift Academy · Lesson

Content and JSON Encoding

Decode and encode request and response bodies.

The Content Protocol

Vapor models that travel over HTTP conform to Content. Content builds on Swift's Codable, adding the ability to be decoded from request bodies and encoded into responses automatically.

import Vapor

struct Todo: Content {
    var id: Int?
    var title: String
    var done: Bool
}

Encoding a Response as JSON

Return any Content value from a handler and Vapor encodes it to JSON, setting the correct Content-Type header for you.

app.get("todo") { req -> Todo in
    Todo(id: 1, title: "Learn Vapor", done: false)
}

All lessons in this course

  1. Routing and Request Handling
  2. Content and JSON Encoding
  3. Fluent ORM and Models
  4. Middleware and Authentication
← Back to Swift Academy